generatesaas 2.2.0 → 2.4.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 CHANGED
@@ -1,27 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Pc}from"commander";import*as ii from"@clack/prompts";import{existsSync as Us,readdirSync as Ms,rmSync as Fs}from"fs";import{join as Vs,resolve as Bs}from"path";import{Option as Z}from"commander";import*as k from"@clack/prompts";import*as _t from"@clack/prompts";import rn from"picocolors";function Gn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";_t.intro(rn.bgYellow(rn.black(t)))}function Kn(){_t.outro(rn.yellow("Happy building!"))}import*as m from"@clack/prompts";import f from"picocolors";var st={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},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)"}},xt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ot={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Be={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}},pt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};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 ne={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}},K={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"}]}},re={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"}]}},lt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],dt=[{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)."}],Hn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Dt(e){let t=K[e.databaseProvider].managed,n=re[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var Re=["nextjs","nuxt"],Ge=["fullstack","separate"],Ke=["stripe","polar","none"],He=["smtp","ses","resend"],ze=["postgres","redis","inngest","mailpit"],Je=["claude-code","cursor","codex","gemini-cli","windsurf"],se=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ce=["node","vercel"],pe=["postgres","neon","supabase"],le=["redis","upstash"],Pe=["shared","vendored"];function Ct(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Ye(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Nt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function I(e){return e instanceof Error?e.message:String(e)}function W(e){let t=e?.trim();return t?`${Ye(t)} Companion`:"My Companion"}var Te="https://github.com/Duzbee/OpenCompanion";function de(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function zn(e){return e.desktop===!0&&e.ai===!0}function H(e){if(zn(e)){if(e.companionSource==="shared")throw new Error("A desktop app with AI bundles its own companion daemon, so its companion source must be vendored. Remove the shared companion source, or turn AI off on this project.");return"vendored"}return de(e)}function ue(e){return zn(e)?!0:e.companion===!0&&de(e)==="vendored"}function $t(e){return e.demo===!0&&e.companion===!0?!0:ue(e)}function ut(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Jn=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Re,adoptable:!1,impact:"structural"},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ge,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ce,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:le,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ke,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:se,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:He,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{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"},{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"},{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"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion 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) and decides whether a companion daemon is bundled inside the packaged app. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"companion",label:"Companion daemon",hint:"Lets your users install a companion daemon that runs their own AI subscriptions (and any device-side work you add) on their hardware. Point it at an existing shared companion like OpenCompanion (default, nothing to maintain), or vendor and publish your own branded daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionSource",label:"Companion source",hint:"Point at an existing shared companion repo (like OpenCompanion), or vendor a branded daemon you own and publish yourself.",category:"Features",kind:"enum",default:e=>H(e),choices:Pe,adoptable:!0,impact:"structural",requires:e=>e.companion===!0||e.desktop===!0&&e.ai===!0,requiresLabel:"requires the companion, or a desktop app with AI"},{key:"companionRepoUrl",label:"Companion repo URL",hint:"GitHub repository of the shared companion this project points at. Its brand.json supplies the daemon identity; your users install from its latest release.",category:"Features",kind:"text",default:()=>Te,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&de(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>W(e.projectName),adoptable:!0,impact:"config",requires:e=>ue(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{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",requires:e=>ut(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"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:ze,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:Je,adoptable:!1,impact:"config"}];function si(e,t){return e[t]!==void 0}function Yn(e){return Jn.filter(t=>t.adoptable&&!si(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 qn(e){let t={};for(let n of Jn)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}import{readFile as Xn}from"fs/promises";import{join as ci}from"path";var qe="GENERATESAAS_COMPANION_BRAND_JSON",Wn=["daemon/brand.json","apps/companion/brand.json"];function oe(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`);let r=n.hostname.toLowerCase();if(r!=="github.com"&&r!=="www.github.com")throw new Error(`Only GitHub-hosted shared companions are supported right now (got "${n.hostname}"). Host the companion on GitHub, or vendor your own with --companion-source vendored.`);let o=n.pathname.split("/").filter(Boolean),i=o[0],a=o[1]?.replace(/\.git$/,"");if(!i||!a)throw new Error(`"${t}" is missing the owner/repo path. Use a full GitHub URL like https://github.com/owner/repo.`);return{owner:i,repo:a,canonicalUrl:`https://github.com/${i}/${a}`}}function Zn(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function on(e,t){let n;try{n=JSON.parse(e)}catch{throw new Error(`The companion brand.json from ${t} is not valid JSON.`)}if(typeof n!="object"||n===null)throw new Error(`The companion brand.json from ${t} is not a JSON object.`);let r=n;for(let o of["name","binary","envPrefix"]){let i=r[o];if(typeof i!="string"||i.trim()==="")throw new Error(`The companion brand.json from ${t} is missing a usable "${o}" field. Point at a companion repo built with the GenerateSaaS export pipeline, or vendor your own with --companion-source vendored.`)}return{name:r.name,binary:r.binary,envPrefix:r.envPrefix}}function pi(e,t,n){let r=JSON.parse(e).repoUrl;if(typeof r!="string"||r.trim()==="")return;let o;try{o=oe(r)}catch{throw new Error(`The companion brand.json from ${t} names an unusable repoUrl ("${r}"), so it cannot be verified against ${n.canonicalUrl}. Fix that brand.json, or unset ${qe} to fetch the identity from GitHub.`)}if(!Zn(o,n))throw new Error(`The companion brand.json from ${t} belongs to ${o.canonicalUrl}, but the project points at ${n.canonicalUrl}. Point ${qe} and --companion-repo-url at the same companion, or unset ${qe} to fetch the identity from GitHub.`)}async function li(e,t){let n=ci(e,"apps/companion/brand.json"),r;try{r=await Xn(n,"utf8")}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(r).repoUrl}catch{throw new Error("The template's apps/companion/brand.json is not valid JSON (boilerplate drift).")}if(typeof o!="string"||o.trim()==="")return null;let i;try{i=oe(o)}catch{return null}return Zn(i,t)?on(r,`the template (${n})`):null}async function di(e){for(let t of Wn){let n=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/HEAD/${t}`,r;try{r=await fetch(n)}catch(o){throw new Error(`Could not reach GitHub to read the companion identity (${n}): ${I(o)}. Check your network, or set GENERATESAAS_COMPANION_BRAND_JSON to a local brand.json.`)}if(r.status!==404){if(!r.ok)throw new Error(`GitHub returned ${r.status} for ${n}. Check that ${e.canonicalUrl} exists and is public.`);return on(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Wn.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function Qn(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=oe(t),r=await li(e.projectDir,n);if(r)return r;let o=process.env[qe]?.trim();if(o){let i;try{i=await Xn(o,"utf8")}catch(u){throw new Error(`Could not read ${qe} (${o}): ${I(u)}.`)}let a=`${qe} (${o})`,s=on(i,a);return pi(i,a,n),s}return await di(n)}var tr=["companion"];function an(e){if(!tr.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function nr(e){return tr.some(n=>e[n]===!0)&&(e.ai=!0),e}function rr(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=ui(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&sn(e),n}function sn(e){return ue(e)&&(e.companionSource=H(e),e.companionName===void 0&&(e.companionName=W(e.projectName))),e}function ui(e,t){return e.desktop!==!0?{kind:"none"}:e.ai===!0&&e.companionSource==="shared"?{kind:"shared-source-contradiction"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:e.ai===!0&&e.companionName===void 0?{kind:"daemon-materialized"}:{kind:"none"}}function or(e){let t={};if(e.name!==void 0){if(!Nt(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.frontend!==void 0){if(!Re.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Re.join(", ")}`);t.frontend=e.frontend}if(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.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!Pe.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${Pe.join(", ")}`);if(e.companion===!1)throw new Error("--companion-source requires the companion; remove --no-companion.");t.companionSource=e.companionSource,t.companion===void 0&&(t.companion=!0)}if(e.companionRepoUrl!==void 0){if(e.companion===!1)throw new Error("--companion-repo-url requires the companion; remove --no-companion.");t.companionRepoUrl=oe(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(t.companionSource==="vendored"&&t.companionRepoUrl!==void 0)throw new Error("--companion-repo-url applies to a shared companion; remove it or use --companion-source shared.");if(an(t),e.desktop===!0&&t.ai===!0&&t.companionRepoUrl!==void 0)throw new Error("--companion-repo-url points at a SHARED companion, but a desktop app with AI bundles its own; remove it, or turn AI off with --no-ai.");if(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.docker!==void 0&&(t.dockerServices=er(e.docker,ze,"docker service")),e.aiTools!==void 0&&(t.aiTools=er(e.aiTools,Je,"AI tool")),e.currency!==void 0){if(!se.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${se.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ce.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ce.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.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.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var ye={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,companion:!1,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function ir(e){let t=e.projectName??ye.projectName,n=e.projectDir??`./${t}`,r=e.appName??Ye(t),o=e.deploymentTarget??ye.deploymentTarget,i=ne[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":ye.databaseProvider),s=e.cacheProvider??(i?"upstash":ye.cacheProvider),u=e.emailProvider??(i?"resend":ye.emailProvider),g=e.dockerServices??(i?ye.dockerServices.filter(h=>h!=="postgres"&&h!=="redis"):ye.dockerServices),l={...ye,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.desktop&&l.ai&&(l.companionSource=H(l)),ue(l)&&l.companionName===void 0&&(l.companionName=W(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=de(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=W(l.projectName)):l.companionRepoUrl===void 0&&(l.companionRepoUrl=Te));for(let h of lt){if(l.deploymentTarget!==h.target)continue;let S=l.databaseProvider===h.provider?"database":"cache";if(l.databaseProvider===h.provider||l.cacheProvider===h.provider)throw new Error(`Incompatible: --deploy ${h.target} + --${S} ${h.provider}. ${h.reason}`)}for(let h of dt)if(l.architecture===h.architecture&&l.deploymentTarget===h.target)throw new Error(`Incompatible: --architecture ${h.architecture} + --deploy ${h.target}. ${h.reason}`);return l}function er(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(i=>i.trim()).filter(Boolean),o=r.filter(i=>!t.includes(i));if(o.length>0)throw new Error(`Invalid ${n}(s): ${o.join(", ")}. Valid values: ${t.join(", ")}`);return r}function A(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function cn(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 ar(e,t){let n=!1;e&&an(e),m.log.info(f.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Nt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return A(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await m.text({message:"App name:",initialValue:Ye(r),validate:d=>{if(!d?.trim())return"App name is required."}});return A(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await m.text({message:"Project location:",initialValue:`./${r}`});return A(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(st),d=await m.select({message:"Frontend framework:",options:c.map(b=>({value:b,label:st[b].label,hint:st[b].hint}))});return A(d),d})();m.log.info(f.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await m.select({message:"Deployment target:",options:ce.map(d=>({value:d,label:ne[d].label,hint:ne[d].hint}))});A(c),s=c}let u=e?.architecture?dt.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(u)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);let g=new Set(dt.filter(c=>c.target===s).map(c=>c.architecture)),l=Ge.filter(c=>!g.has(c)),h=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return m.log.info(`Auto-selected ${ct[d].label} architecture (only compatible option for ${ne[s].label}).`),d}n=!0;let c=await m.select({message:"Architecture:",options:l.map(d=>({value:d,label:ct[d].label,hint:ct[d].hint}))});return A(c),c})(),S=e?.databaseProvider??await(async()=>{n=!0;let c=pe.filter(b=>!lt.some(q=>q.target===s&&q.provider===b));if(c.length===1){let b=c[0];return m.log.info(`Auto-selected ${K[b].label} (only compatible option for ${ne[s].label}).`),b}let d=await m.select({message:"Database provider:",options:c.map(b=>({value:b,label:K[b].label,hint:K[b].hint}))});return A(d),d})(),C=e?.cacheProvider??await(async()=>{n=!0;let c=le.filter(b=>!lt.some(q=>q.target===s&&q.provider===b));if(c.length===1){let b=c[0];return m.log.info(`Auto-selected ${re[b].label} (only compatible option for ${ne[s].label}).`),b}let d=await m.select({message:"Cache provider:",options:c.map(b=>({value:b,label:re[b].label,hint:re[b].hint}))});return A(d),d})();if(ne[s]?.edgeRuntime){let c=Hn.map(d=>` - ${d}`).join(`
3
- `);m.note(c,"Unavailable on edge runtime")}m.log.info(f.bold("Features"));let E=e?.paymentProvider??await(async()=>{n=!0;let c=await m.select({message:"Payment provider:",options:Ke.map(d=>({value:d,label:xt[d].label,hint:xt[d].hint}))});return A(c),c})(),N=e?.defaultCurrency??await(async()=>{if(E==="none")return"USD";n=!0;let c=await m.select({message:"Default currency:",options:se.map(d=>({value:d,label:d,hint:Ie[d].name}))});return A(c),c})(),te=e?.emailProvider??await(async()=>{n=!0;let c=await m.select({message:"Email provider:",options:He.map(d=>({value:d,label:Ot[d].label,hint:Ot[d].hint}))});return A(c),c})(),Fe=e?.multiTenancy??await(async()=>{n=!0;let c=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return A(c),c})(),ae=e?.blog??await(async()=>{n=!0;let c=await m.confirm({message:"Enable blog?",initialValue:!0});return A(c),c})(),Ee=e?.docs??await(async()=>{n=!0;let c=await m.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return A(c),c})(),Ve=t?.desktopAllowed!==!1,he=e?.desktop??(Ve?await(async()=>{n=!0;let c=await m.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack and bundles its own companion daemon.",initialValue:!1});return A(c),c})():(m.log.info(f.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),y=e?.ai??await(async()=>{n=!0;let c=await m.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion)",initialValue:!1});return A(c),c})(),O=t?.companionAllowed!==!1,j=y?e?.companion??(O?await(async()=>{n=!0;let c=await m.confirm({message:"Add the companion daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex / OpenCode 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 A(c),c})():(m.log.info(f.dim("Companion: available on the Pro plan and up - skipped.")),!1)):!1,Y=he&&y,w=Y?H({desktop:he,ai:y,companion:j,companionSource:e?.companionSource,companionName:e?.companionName}):j?e?.companionSource??await(async()=>{n=!0;let c=await m.select({message:"Companion source:",options:[{value:"shared",label:"Shared companion",hint:"point at an existing companion repo (OpenCompanion by default) - nothing to publish or maintain"},{value:"vendored",label:"Vendored companion",hint:"own a branded daemon: source in this repo, published to your own GitHub repo"}],initialValue:"shared"});return A(c),c})():void 0;Y&&m.log.info(f.dim("Companion source: your desktop app bundles its own daemon, so it is vendored into this repo. Nothing to publish - it ships inside the app."));let M=w!=="shared"?void 0:e?.companionRepoUrl??await(async()=>{n=!0;let c=await m.text({message:"Companion repo URL (GitHub):",initialValue:Te,validate:d=>{if(!d?.trim())return"A companion repo URL is required for a shared companion.";try{oe(d)}catch(b){return I(b)}}});return A(c),oe(c).canonicalUrl})(),Ae=w!=="vendored"?void 0:e?.companionName??await(async()=>{n=!0;let c=await m.text({message:Y&&!j?"Companion name (your app's bundled daemon - names its binary, service and data folder):":"Companion name (what your users install):",initialValue:W(r),validate:d=>{if(!d?.trim())return"Companion name is required."}});return A(c),c})(),ot=e?.revenueSharing??await(async()=>{n=!0;let c=await m.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return A(c),c})(),Vn=E==="none"?!1:e?.credits??await(async()=>{n=!0;let c=await m.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return A(c),c})();m.log.info(f.bold("Tooling"));let en=e?.dockerServices??await(async()=>{n=!0;let c=[...ze].filter(F=>F!=="mailpit");te==="smtp"&&c.push("mailpit");let d=c.map(F=>({value:F,label:Be[F].label,hint:Be[F].hint})),b=d.map(F=>F.value).filter(F=>!(F==="postgres"&&(S==="neon"||S==="supabase")||F==="redis"&&C==="upstash")),q=await m.multiselect({message:"Which services should we set up in Docker for you?",options:d,initialValues:b,required:!1});return A(q),q})(),tn=e?.aiTools??await(async()=>{n=!0;let c=Je.map(b=>({value:b,label:pt[b].label})),d=await m.multiselect({message:"Which AI coding tools do you use?",options:c,initialValues:[],required:!1});return A(d),d})(),nn=e?.demo,Tt=cn({databaseProvider:S,cacheProvider:C,paymentProvider:E,emailProvider:te,demo:nn}),it={};if(Tt.length>0&&n){m.log.info(f.bold("Credentials")+f.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Tt)if(n=!0,c.secret){let d=await m.password({message:c.message,mask:"*"});A(d),typeof d=="string"&&d.trim()&&(it[c.key]=d.trim())}else{let d=await m.text({message:c.message,placeholder:c.placeholder});A(d),typeof d=="string"&&d.trim()&&(it[c.key]=d.trim())}}if(n){let c=[` Name: ${f.cyan(r)}`,` App name: ${f.cyan(o)}`,` Location: ${f.cyan(i)}`,` Frontend: ${f.cyan(st[a].label)}`,` Architecture: ${f.cyan(ct[h].label)}`].join(`
4
- `),d=[` Deploy target: ${f.cyan(ne[s]?.label??"Node.js / Docker")}`,` Database: ${f.cyan(K[S].label)}`,` Cache: ${f.cyan(re[C].label)}`,en.length>0?` Docker: ${f.cyan(en.map(at=>Be[at].label).join(", "))}`:` Docker: ${f.dim("none")}`].filter(Boolean).join(`
5
- `),b=[E!=="none"?` Payment: ${f.cyan(xt[E].label)} (${N})`:` Payment: ${f.dim("none")}`,` Credits: ${Vn?f.cyan("Yes"):f.dim("No")}`,` AI features: ${y?f.cyan("Yes"):f.dim("No")}`,...y?[` Companion: ${j?f.cyan("Yes"):f.dim("No")}`,...j?[` Comp. source: ${f.cyan(w==="shared"?"Shared":"Vendored")}`,w==="shared"?` Comp. repo: ${f.cyan(M??"")}`:` Comp. name: ${f.cyan(Ae??"")}`]:[]]:[],` Email: ${f.cyan(Ot[te].label)}`,` Multi-tenancy: ${Fe?f.cyan("Yes"):f.dim("No")}`,` Blog: ${ae?f.cyan("Yes"):f.dim("No")}`,` Docs app: ${Ee?f.cyan("Yes"):f.dim("No")}`,` Desktop app: ${he?f.cyan("Yes"):f.dim("No")}`,...Y&&!j?[` Desktop AI: ${f.cyan("Yes")} (bundles ${Ae??""})`]:[],` Rev. sharing: ${ot?f.cyan("Yes"):f.dim("No")}`,tn.length>0?` AI tools: ${f.cyan(tn.map(at=>pt[at].label).join(", "))}`:` AI tools: ${f.dim("none")}`].join(`
6
- `),q=[f.bold("Project"),c,"",f.bold("Infrastructure"),d,"",f.bold("Features"),b];if(Tt.length>0){let at=Tt.map(Bn=>{let ai=it[Bn.key]?f.green("provided"):f.dim("skipped");return` ${Bn.key}: ${ai}`}).join(`
7
- `);q.push("",f.bold("Credentials"),at)}m.note(q.join(`
8
- `),"Summary");let F=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(F)||!F)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:r,appName:o,projectDir:i,frontend:a,architecture:h,deploymentTarget:s,databaseProvider:S,cacheProvider:C,paymentProvider:E,emailProvider:te,multiTenancy:Fe,blog:ae,docs:Ee,desktop:he,ai:y,companion:j,...Ae!==void 0?{companionName:Ae}:{},...w!==void 0?{companionSource:w}:{},...M!==void 0?{companionRepoUrl:M}:{},revenueSharing:ot,credits:Vn,dockerServices:en,aiTools:tn,defaultCurrency:N,...Object.keys(it).length>0?{credentials:it}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...nn!==void 0?{demo:nn}:{}}}import{createReadStream as fr,existsSync as Ai}from"fs";import{mkdir as Ii}from"fs/promises";import{join as Ri}from"path";import{Readable as Pi}from"stream";import{pipeline as gn}from"stream/promises";import{extract as Ti}from"tar";import{join as _e}from"path";import{homedir as mi}from"os";var mt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",V=".generatesaas",we=_e(V,"manifest.json"),sr=_e(V,"hashes.json"),Lt=_e(V,"template-hashes.json"),jt=_e(V,"template"),cr=_e(V,"staging"),pr=_e(V,"staging.json"),me=_e(mi(),".generatesaas");var $=class extends Error{constructor(n,r,o){super(r);this.status=n;this.body=o}status;body;name="ApiError"};function fe(e){return{apiKey:e,baseUrl:mt}}async function ve(e,t,n){let r=`${e.baseUrl}${t}`,o=await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/2.2.0"}});if(!o.ok){let i,a;try{a=await o.json(),i=a.error??`API ${o.status}: ${t}`}catch{i=`API ${o.status}: ${t}`}throw new $(o.status,i,a)}return o}import{existsSync as fi,readFileSync as gi,writeFileSync as hi,mkdirSync as yi}from"fs";import{dirname as wi}from"path";import*as ke from"@clack/prompts";function ft(){if(!fi(me))return null;try{let e=JSON.parse(gi(me,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&ke.log.warning(`Found old GitHub token in ${me}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function xe(e){yi(wi(me),{recursive:!0}),hi(me,JSON.stringify({apiKey:e},null," ")+`
9
- `,{mode:384})}async function We(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=ft();if(n)return n;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return gt()}async function gt(){let e=await ke.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return ke.isCancel(e)&&(ke.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as vi}from"fs/promises";async function be(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await vi(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 pn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await ve(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(n){if(n instanceof $&&n.status===404)return null;throw n}}async function lr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
10
- `,scripts:{}}:await(await ve(e,`/skill/${encodeURIComponent(t)}`)).json()}function Ut(e){if(!(e instanceof $)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}function dr(e){return{frontend:e.frontend,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,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,aiTools:e.aiTools,currency:e.defaultCurrency}}async function ln(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 ur(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 dn(e,t){let n=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Verification service returned ${n.status}`);return await n.json()}async function mr(e,t,n){let r=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});if(!r.ok){let o=await r.json().catch(()=>null);throw new Error(o?.error??`Inspect endpoint returned ${r.status}`)}return await r.json()}var un=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),mn=new Set(["pnpm-lock.yaml"]);function Xe(e){if(fn(e))return!0;for(let t of e.split("/"))if(mn.has(t))return!0;return!1}var ki=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","README.md","TODO.md","OVERVIEW.md"]),bi=["scripts/docs-lint.ts"],Si=["scripts/companion-export/"],Ei=["docs/superpowers","packages/cli","packages/cli-api","docs/opencompanion","infra/docker-compose.yml",".claude/commands",".claude/skills/web-next-port",".claude/skills/web-next-port-workspace",".claude/settings.local.json",".claude/worktrees"];function fn(e){let t=e.split("/");for(let n of t)if(un.has(n))return!0;if(bi.includes(e))return!1;for(let n of Si)if(e.startsWith(n)||`${e}/`===n)return!1;if(ki.has(t[0]))return!0;for(let n of Ei)if(e===n||e.startsWith(n+"/"))return!0;return!1}async function Mt(e,t,n){await Ii(n,{recursive:!0});let r=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(r){let s=Ri(r,`v${t}.tar.gz`);if(!Ai(s))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${s} does not exist.`);await gn(fr(s),hn(n));return}let o=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(o){await gn(fr(o),hn(n));return}let i=await ve(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let a=Pi.fromWeb(i.body);await gn(a,hn(n))}function hn(e){return Ti({cwd:e,strip:1,filter:t=>{let n=t.replace(/^[^/]+\//,"");return n?!fn(n):!0},sync:!1})}import{readdir as Vi,readFile as vt,rm as yn,writeFile as kt}from"fs/promises";import{join as ge}from"path";import{readFile as wt,rm as ji}from"fs/promises";import{join as yt}from"path";import{mkdir as _i,readdir as xi,rm as Oi,rmdir as Di,writeFile as Ci}from"fs/promises";import{dirname as Ft,join as Ni,relative as $i,sep as Li}from"path";function Oe(e){return e.split(Li).join("/")}async function Vt(e){await _i(e,{recursive:!0})}async function p(e,t){await Vt(Ft(e)),await Ci(e,t,"utf-8")}async function ht(e,t){await Oi(e,{force:!0});let n=Ft(e);for(;n!==t&&n!==Ft(n);){try{await Di(n)}catch{return}n=Ft(n)}}async function De(e,t,n){let r=[],o=await xi(e,{withFileTypes:!0});for(let i of o){let a=Ni(e,i.name),s=Oe($i(t,a));n(s)||(i.isDirectory()?r.push(...await De(a,t,n)):i.isFile()&&r.push(a))}return r}function Ui(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Se(e,t,n,r){let o=Ui(n);if(e.match(o)===null)throw new Error(`${r}: expected gsaas ${n} markers in ${t}, but found none (boilerplate drift).`);let i=e.replace(o,"");if(i.includes(`gsaas:${n}-start`)||i.includes(`gsaas:${n}-end`))throw new Error(`${r}: an unbalanced gsaas ${n} marker is left in ${t} (boilerplate drift).`);return i.replace(/\n{3,}/g,`
11
-
12
- `)}async function B(e,t,n,r,o){let i=await wt(e,"utf-8"),a=i.indexOf(t);if(a===-1)throw new Error(`${o}: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(i.indexOf(t,a+t.length)!==-1)throw new Error(`${o}: the ${r} seam appears more than once (boilerplate drift).`);await p(e,i.slice(0,a)+n+i.slice(a+t.length))}async function Bt(e,t,n,r){let o=/\n([\t ]+)"/.exec(await wt(e,"utf-8"))?.[1];if(o!==n){let i=a=>a===" "?"tab":`${a.length}-space`;throw new Error(`${r}: expected ${e} to be ${i(n)}-indented, but it is ${o===void 0?"not indented":i(o)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await p(e,`${JSON.stringify(t,null,n)}
13
- `)}function Gt(e){return e.frontend==="nextjs"?"next":"nuxt"}async function Mi(e,t,n,r){let o=yt(e,"ai.mdx"),a=(await wt(o,"utf-8")).split(`
14
- `).find(s=>s.includes(`href="${n}"`));if(a===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${n} (boilerplate drift).`);await B(o,`${a}
15
- `,"",`${t} ai.mdx ${n} card`,r)}async function Fi(e,t,n,r){let o=yt(e,"ai.mdx"),i=`| **${n}** |`,s=(await wt(o,"utf-8")).split(`
16
- `).find(u=>u.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${n}" hub-table row (boilerplate drift).`);await B(o,`${s}
17
- `,"",`${t} ai.mdx ${n} hub-table row`,r)}async function gr(e,t,n,r,o,i){let a=yt(e,"docs",t);await ji(yt(a,n),{recursive:!0}),await B(yt(a,"meta.json"),` "${n}",
18
- `,"",`${t} meta.json ${n} nav entry`,o);for(let s of r)await Mi(a,t,s,o);i!==void 0&&await Fi(a,t,i,o)}async function hr(e){let t=`import { config } from "@repo/config";
19
- `,n=await wt(e,"utf-8");if(!n.includes(t))return;let r=n.replace(t,""),o=r.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(o)||await p(e,r)}var Bi=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function wr(e){await Promise.all(Bi.map(t=>yn(ge(e,t),{recursive:!0,force:!0})))}var Gi=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function vr(e){let t="removeDesktopDemoScreen";await yn(ge(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let n of Gi){let r=ge(e,n);await kt(r,Se(await vt(r,"utf-8"),n,"demo",t))}}var Ki="packages/config/src/blog.ts";async function kr(e){let t=ge(e,Ki),n=await vt(t,"utf-8"),r=yr(yr(n,"blogCategories",t),"blogAuthors",t);await kt(t,r)}function yr(e,t,n){let r=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!r.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${n}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(r,"$1[];")}async function br(e){let t=ge(e,"packages/i18n/translations"),n;try{n=await Vi(t)}catch{return}for(let r of n){let o=ge(t,r,"web.json"),i;try{i=await vt(o,"utf-8")}catch{continue}let a=JSON.parse(i);!a.blog||a.blog.categories===void 0||(a.blog.categories={},await kt(o,JSON.stringify(a,null," ")+`
20
- `))}}var Hi="packages/config/src/ai/tasks.ts";async function Sr(e){let t=ge(e,Hi),n=await vt(t,"utf-8"),r=n.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(r===n)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.`);await kt(t,r)}async function Er(e,t){t.includes("claude-code")||await yn(ge(e,".claude"),{recursive:!0,force:!0})}async function Ar(e,t){let n=ge(e,".claude","settings.json"),r;try{r=await vt(n,"utf8")}catch{return}let o=JSON.parse(r);delete o.alwaysThinkingEnabled,delete o.enableAllProjectMcpServers,o.env&&(delete o.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(o.env).length===0&&delete o.env),o.permissions?.allow&&(o.permissions.allow=o.permissions.allow.filter(i=>zi(i,t))),await kt(n,JSON.stringify(o,null," ")+`
21
- `)}function zi(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as Ir}from"path";var Ji={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Yi={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},qi={redis:"Redis",upstash:"Upstash Redis"},Wi={node:"Node.js / Docker",vercel:"Vercel"},Xi={stripe:"Stripe",polar:"Polar"};function Zi(e){let t=e.frontend==="nuxt",n=t?"Nuxt 4":"Next.js 16",r=t?"apps/web-nuxt":"apps/web-next",o=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",i=e.architecture==="fullstack",a=i?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",s=i?`Mounted inside \`${r}\`. 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.",u=qi[e.cacheProvider],g=Wi[e.deploymentTarget],l=e.paymentProvider==="none"?"":`
22
- - **Payments:** ${Xi[e.paymentProvider]}`,h=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",S="";e.companion&&(de(e)==="vendored"?S=`
23
- - \`apps/companion\` - the source of **${e.companionName??W(e.projectName)}**, the branded companion daemon your users install. Publish releases with \`pnpm companion:publish\`; \`generatesaas update\` flags when a re-release is due.`:S=`
24
- - **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\` (your users install it from that repo's releases). It cannot be modified from this repo; to customize device-side behavior, switch \`companionSource\` to \`vendored\` via \`generatesaas update\`.`);let C=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",E=t?"**Navigation:** always use `localePath()` for paths (hardcoded paths break non-default locales); `await navigateTo()` in SSR.":"**Navigation:** `next/link` for links; `redirect()` from `next/navigation` for programmatic redirects in Server Components.";return`# AGENTS.md
2
+ import{Command as Mp}from"commander";import*as mi from"@clack/prompts";import{existsSync as Wc,readdirSync as qc,rmSync as Xc}from"fs";import{join as Zc,resolve as Qc}from"path";import{Option as z}from"commander";import*as v from"@clack/prompts";import*as vt from"@clack/prompts";import qt from"picocolors";function Dr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";vt.intro(qt.bgYellow(qt.black(t)))}function _r(){vt.outro(qt.yellow("Happy building!"))}import*as m from"@clack/prompts";import g from"picocolors";var et={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},tt={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)"}},kt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},bt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},St={none:{label:"None",hint:"no reporting SDK is generated at all"},sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server only - no Electron SDK, so a desktop build reports nothing"}},Nr={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 be={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}},re={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"}]}},Se={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"}]}},rt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],nt=[{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)."}],hi=[{feature:"companion",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the companion 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 hi.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var Cr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Me(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 Ee=["nextjs","nuxt"],Ue=["fullstack","separate"],Fe=["stripe","polar","none"],Ve=["smtp","ses","resend"];var $r=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ie=["node","vercel"],se=["postgres","neon","supabase"],ae=["redis","upstash"],B=["none","sentry","posthog"];function jr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Et(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Rt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Lr=["companion"];function Xt(e){if(!Lr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--companion requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Mr(e){return Lr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Ur(e){let t=yi(e,e.desktopAi);return delete e.desktopAi,t}function yi(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 Fr(e){let t={};if(e.name!==void 0){if(!Rt(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.frontend!==void 0){if(!Ee.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ee.join(", ")}`);t.frontend=e.frontend}if(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.companion!==void 0&&(t.companion=e.companion),Xt(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(!ie.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ie.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!se.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${se.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ae.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ae.join(", ")}`);t.cacheProvider=e.cache}if(e.errorTracking!==void 0){if(!B.includes(e.errorTracking))throw new Error(`Invalid error tracking provider "${e.errorTracking}". Valid values: ${B.join(", ")}`);t.errorTracking=e.errorTracking}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 Be={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,companion:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",errorTracking:"none"};function Vr(e){let t=e.projectName??Be.projectName,r=e.projectDir??`./${t}`,n=e.appName??Et(t),o=e.deploymentTarget??Be.deploymentTarget,i=G[o]?.edgeRuntime??!1,s=e.databaseProvider??(i?"neon":Be.databaseProvider),a=e.cacheProvider??(i?"upstash":Be.cacheProvider),l=e.emailProvider??(i?"resend":Be.emailProvider),u={...Be,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:o,databaseProvider:s,cacheProvider:a,emailProvider:l};u.paymentProvider==="none"&&(u.credits=!1);for(let f of rt){if(u.deploymentTarget!==f.target)continue;let h=u.databaseProvider===f.provider?"database":"cache";if(u.databaseProvider===f.provider||u.cacheProvider===f.provider)throw new Error(`Incompatible: --deploy ${f.target} + --${h} ${f.provider}. ${f.reason}`)}for(let f of nt)if(u.architecture===f.architecture&&u.deploymentTarget===f.target)throw new Error(`Incompatible: --architecture ${f.architecture} + --deploy ${f.target}. ${f.reason}`);let y=ne(u);if(y)throw new Error(`Incompatible: --${y.feature} + --deploy ${y.target}. ${y.reason}`);return u}function I(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function Zt(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 Br(e,t){let r=!1;e&&Xt(e),m.log.info(g.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let p=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Rt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return I(p),p})(),o=e?.appName??await(async()=>{r=!0;let p=await m.text({message:"App name:",initialValue:Et(n),validate:d=>{if(!d?.trim())return"App name is required."}});return I(p),p})(),i=e?.projectDir??await(async()=>{r=!0;let p=await m.text({message:"Project location:",initialValue:`./${n}`});return I(p),p==="."?process.cwd():p})(),s=e?.frontend??await(async()=>{r=!0;let p=Object.keys(et),d=await m.select({message:"Frontend framework:",options:p.map(E=>({value:E,label:et[E].label,hint:et[E].hint}))});return I(d),d})();m.log.info(g.bold("Infrastructure"));let a=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){r=!0;let p=await m.select({message:"Deployment target:",options:ie.map(d=>({value:d,label:G[d].label,hint:G[d].hint}))});I(p),a=p}let l=e?.architecture?nt.find(p=>p.architecture===e.architecture&&p.target===a):void 0;if(l)throw new Error(`Incompatible: --architecture ${l.architecture} + --deploy ${l.target}. ${l.reason}`);let u=ne({...e,deploymentTarget:a});if(u)throw new Error(`Incompatible: --${u.feature} + --deploy ${u.target}. ${u.reason}`);let y=ne({companion:!0,deploymentTarget:a})!==void 0,f=new Set(nt.filter(p=>p.target===a).map(p=>p.architecture)),h=Ue.filter(p=>!f.has(p)),$=e?.architecture??await(async()=>{if(h.length===1){let d=h[0];return m.log.info(`Auto-selected ${tt[d].label} architecture (only compatible option for ${G[a].label}).`),d}r=!0;let p=await m.select({message:"Architecture:",options:h.map(d=>({value:d,label:tt[d].label,hint:tt[d].hint}))});return I(p),p})(),b=e?.databaseProvider??await(async()=>{r=!0;let p=se.filter(E=>!rt.some(ue=>ue.target===a&&ue.provider===E));if(p.length===1){let E=p[0];return m.log.info(`Auto-selected ${re[E].label} (only compatible option for ${G[a].label}).`),E}let d=await m.select({message:"Database provider:",options:p.map(E=>({value:E,label:re[E].label,hint:re[E].hint}))});return I(d),d})(),U=e?.cacheProvider??await(async()=>{r=!0;let p=ae.filter(E=>!rt.some(ue=>ue.target===a&&ue.provider===E));if(p.length===1){let E=p[0];return m.log.info(`Auto-selected ${Se[E].label} (only compatible option for ${G[a].label}).`),E}let d=await m.select({message:"Cache provider:",options:p.map(E=>({value:E,label:Se[E].label,hint:Se[E].hint}))});return I(d),d})();if(G[a]?.edgeRuntime){let p=Cr.map(d=>` - ${d}`).join(`
3
+ `);m.note(p,"Unavailable on edge runtime")}m.log.info(g.bold("Features"));let Q=e?.paymentProvider??await(async()=>{r=!0;let p=await m.select({message:"Payment provider:",options:Fe.map(d=>({value:d,label:kt[d].label,hint:kt[d].hint}))});return I(p),p})(),ee=e?.defaultCurrency??await(async()=>{if(Q==="none")return"USD";r=!0;let p=await m.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:be[d].name}))});return I(p),p})(),le=e?.emailProvider??await(async()=>{r=!0;let p=await m.select({message:"Email provider:",options:Ve.map(d=>({value:d,label:bt[d].label,hint:bt[d].hint}))});return I(p),p})(),ve=e?.errorTracking??await(async()=>{r=!0;let p=await m.select({message:"Error tracking:",options:B.map(d=>({value:d,label:St[d].label,hint:St[d].hint}))});return I(p),p})(),ke=e?.multiTenancy??await(async()=>{r=!0;let p=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return I(p),p})(),w=e?.blog??await(async()=>{r=!0;let p=await m.confirm({message:"Enable blog?",initialValue:!0});return I(p),p})(),N=e?.docs??await(async()=>{r=!0;let p=await m.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return I(p),p})(),de=t?.desktopAllowed!==!1,q=e?.desktop??(de?await(async()=>{r=!0;let p=await m.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return I(p),p})():(m.log.info(g.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),A=e?.ai??await(async()=>{r=!0;let p=await m.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion)",initialValue:!1});return I(p),p})(),Le=t?.companionAllowed!==!1,te=!A||y?!1:e?.companion??(Le?await(async()=>{r=!0;let p=await m.confirm({message:"Add the companion daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex / OpenCode 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 I(p),p})():(m.log.info(g.dim("Companion: available on the Pro plan and up - skipped.")),!1));A&&y&&m.log.info(g.dim(`Companion: ${G[a].label} cannot hold a connection open - skipped.`));let P=e?.revenueSharing??await(async()=>{r=!0;let p=await m.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return I(p),p})(),Ze=Q==="none"?!1:e?.credits??await(async()=>{r=!0;let p=await m.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return I(p),p})(),Wt=e?.demo,wt=Zt({databaseProvider:b,cacheProvider:U,paymentProvider:Q,emailProvider:le,demo:Wt}),Qe={};if(wt.length>0&&r){m.log.info(g.bold("Credentials")+g.dim(" all optional - press Enter to skip, fill in .env later"));for(let p of wt)if(r=!0,p.secret){let d=await m.password({message:p.message,mask:"*"});I(d),typeof d=="string"&&d.trim()&&(Qe[p.key]=d.trim())}else{let d=await m.text({message:p.message,placeholder:p.placeholder});I(d),typeof d=="string"&&d.trim()&&(Qe[p.key]=d.trim())}}if(r){let p=[` Name: ${g.cyan(n)}`,` App name: ${g.cyan(o)}`,` Location: ${g.cyan(i)}`,` Frontend: ${g.cyan(et[s].label)}`,` Architecture: ${g.cyan(tt[$].label)}`].join(`
4
+ `),d=[` Deploy target: ${g.cyan(G[a]?.label??"Node.js / Docker")}`,` Database: ${g.cyan(re[b].label)}`,` Cache: ${g.cyan(Se[U].label)}`].filter(Boolean).join(`
5
+ `),E=[Q!=="none"?` Payment: ${g.cyan(kt[Q].label)} (${ee})`:` Payment: ${g.dim("none")}`,` Credits: ${Ze?g.cyan("Yes"):g.dim("No")}`,` AI features: ${A?g.cyan("Yes"):g.dim("No")}`,...A?[` Companion: ${te?g.cyan("Yes"):g.dim("No")}`]:[],` Email: ${g.cyan(bt[le].label)}`,` Error track.: ${ve==="none"?g.dim("none"):g.cyan(St[ve].label)}`,` Multi-tenancy: ${ke?g.cyan("Yes"):g.dim("No")}`,` Blog: ${w?g.cyan("Yes"):g.dim("No")}`,` Docs app: ${N?g.cyan("Yes"):g.dim("No")}`,` Desktop app: ${q?g.cyan("Yes"):g.dim("No")}`,` Rev. sharing: ${P?g.cyan("Yes"):g.dim("No")}`].join(`
6
+ `),ue=[g.bold("Project"),p,"",g.bold("Infrastructure"),d,"",g.bold("Features"),E];if(wt.length>0){let fi=wt.map(xr=>{let gi=Qe[xr.key]?g.green("provided"):g.dim("skipped");return` ${xr.key}: ${gi}`}).join(`
7
+ `);ue.push("",g.bold("Credentials"),fi)}m.note(ue.join(`
8
+ `),"Summary");let Or=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(Or)||!Or)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:o,projectDir:i,frontend:s,architecture:$,deploymentTarget:a,databaseProvider:b,cacheProvider:U,paymentProvider:Q,emailProvider:le,errorTracking:ve,multiTenancy:ke,blog:w,docs:N,desktop:q,ai:A,companion:te,revenueSharing:P,credits:Ze,defaultCurrency:ee,...Object.keys(Qe).length>0?{credentials:Qe}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...Wt!==void 0?{demo:Wt}:{}}}import{createReadStream as qr,existsSync as Ai}from"fs";import{mkdir as Oi}from"fs/promises";import{join as xi}from"path";import{Readable as Di}from"stream";import{pipeline as ir}from"stream/promises";import{extract as _i}from"tar";import{join as Re}from"path";import{homedir as wi}from"os";var ot=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",H=".generatesaas",me=Re(H,"manifest.json"),Kr=Re(H,"hashes.json"),Pt=Re(H,"template-hashes.json"),It=Re(H,"template"),Gr=Re(H,"staging"),Hr=Re(H,"staging.json"),ce=Re(wi(),".generatesaas");var C=class extends Error{constructor(r,n,o){super(n);this.status=r;this.body=o}status;body;name="ApiError"};function pe(e){return{apiKey:e,baseUrl:ot}}async function fe(e,t,r){let n=`${e.baseUrl}${t}`,o=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/2.4.0"}});if(!o.ok){let i,s;try{s=await o.json(),i=s.error??`API ${o.status}: ${t}`}catch{i=`API ${o.status}: ${t}`}throw new C(o.status,i,s)}return o}import{existsSync as vi,readFileSync as ki,writeFileSync as bi,mkdirSync as Si}from"fs";import{dirname as Ei}from"path";import*as ge from"@clack/prompts";function it(){if(!vi(ce))return null;try{let e=JSON.parse(ki(ce,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&ge.log.warning(`Found old GitHub token in ${ce}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Pe(e){Si(Ei(ce),{recursive:!0}),bi(ce,JSON.stringify({apiKey:e},null," ")+`
9
+ `,{mode:384})}async function Ke(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=it();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 st()}async function st(){let e=await ge.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return ge.isCancel(e)&&(ge.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Ri}from"fs/promises";async function he(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ri(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 fe(e,"/versions")).json()}async function Qt(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await fe(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof C&&r.status===404)return null;throw r}}async function Yr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
10
+ `,scripts:{}}:await(await fe(e,`/skill/${encodeURIComponent(t)}`)).json()}function Tt(e){if(!(e instanceof C)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}function Jr(e){return{frontend:e.frontend,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,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function er(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await fe(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function zr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await fe(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function tr(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 Wr(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 o=await n.json().catch(()=>null);throw new Error(o?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var rr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),nr=new Set(["pnpm-lock.yaml"]);function Ge(e){if(or(e))return!0;for(let t of e.split("/"))if(nr.has(t))return!0;return!1}var Pi=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md"]),Ii=["scripts/docs-lint.ts"],Ti=["docs/superpowers","packages/cli","packages/cli-api","apps/companion","docs/opencompanion","infra/docker-compose.yml",".claude/commands",".claude/skills/web-next-port",".claude/skills/web-next-port-workspace",".claude/settings.local.json",".claude/worktrees"];function or(e){let t=e.split("/");for(let r of t)if(rr.has(r))return!0;if(Ii.includes(e))return!1;if(Pi.has(t[0]))return!0;for(let r of Ti)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function At(e,t,r){await Oi(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=xi(n,`v${t}.tar.gz`);if(!Ai(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await ir(qr(a),sr(r));return}let o=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(o){await ir(qr(o),sr(r));return}let i=await fe(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let s=Di.fromWeb(i.body);await ir(s,sr(r))}function sr(e){return _i({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!or(r):!0},sync:!1})}import{readdir as Hi,readFile as pt,rm as en,writeFile as lt}from"fs/promises";import{join as we}from"path";import{readFile as ct,rm as Vi}from"fs/promises";import{join as at}from"path";import{mkdir as Ni,readdir as Ci,rm as $i,rmdir as ji,writeFile as Li}from"fs/promises";import{dirname as Ot,join as Mi,relative as Ui,sep as Fi}from"path";function Ie(e){return e.split(Fi).join("/")}async function xt(e){await Ni(e,{recursive:!0})}async function c(e,t){await xt(Ot(e)),await Li(e,t,"utf-8")}async function He(e,t){await $i(e,{force:!0});let r=Ot(e);for(;r!==t&&r!==Ot(r);){try{await ji(r)}catch{return}r=Ot(r)}}async function Te(e,t,r){let n=[],o=await Ci(e,{withFileTypes:!0});for(let i of o){let s=Mi(e,i.name),a=Ie(Ui(t,s));r(a)||(i.isDirectory()?n.push(...await Te(s,t,r)):i.isFile()&&n.push(s))}return n}function Bi(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function ye(e,t,r,n){let o=Bi(r);if(e.match(o)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let i=e.replace(o,"");if(i.includes(`gsaas:${r}-start`)||i.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return i.replace(/\n{3,}/g,`
11
+
12
+ `)}async function j(e,t,r,n,o){let i=await ct(e,"utf-8"),s=i.indexOf(t);if(s===-1)throw new Error(`${o}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(i.indexOf(t,s+t.length)!==-1)throw new Error(`${o}: the ${n} seam appears more than once (boilerplate drift).`);await c(e,i.slice(0,s)+r+i.slice(s+t.length))}async function Dt(e,t,r,n){let o=/\n([\t ]+)"/.exec(await ct(e,"utf-8"))?.[1];if(o!==r){let i=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${i(r)}-indented, but it is ${o===void 0?"not indented":i(o)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await c(e,`${JSON.stringify(t,null,r)}
13
+ `)}function _t(e){return e.frontend==="nextjs"?"next":"nuxt"}async function Ki(e,t,r,n){let o=at(e,"ai.mdx"),s=(await ct(o,"utf-8")).split(`
14
+ `).find(a=>a.includes(`href="${r}"`));if(s===void 0)throw new Error(`${n}: expected the ai.mdx card linking to ${r} (boilerplate drift).`);await j(o,`${s}
15
+ `,"",`${t} ai.mdx ${r} card`,n)}async function Gi(e,t,r,n){let o=at(e,"ai.mdx"),i=`| **${r}** |`,a=(await ct(o,"utf-8")).split(`
16
+ `).find(l=>l.startsWith(i));if(a===void 0)throw new Error(`${n}: expected the ai.mdx "${r}" hub-table row (boilerplate drift).`);await j(o,`${a}
17
+ `,"",`${t} ai.mdx ${r} hub-table row`,n)}async function Xr(e,t,r,n,o,i){let s=at(e,"docs",t);await Vi(at(s,r),{recursive:!0}),await j(at(s,"meta.json"),` "${r}",
18
+ `,"",`${t} meta.json ${r} nav entry`,o);for(let a of n)await Ki(s,t,a,o);i!==void 0&&await Gi(s,t,i,o)}async function Zr(e){let t=`import { config } from "@repo/config";
19
+ `,r=await ct(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),o=n.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(o)||await c(e,n)}var Yi=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function tn(e){await Promise.all(Yi.map(t=>en(we(e,t),{recursive:!0,force:!0})))}var Ji=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function rn(e){let t="removeDesktopDemoScreen";await en(we(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let r of Ji){let n=we(e,r);await lt(n,ye(await pt(n,"utf-8"),r,"demo",t))}}var zi="packages/config/src/blog.ts";async function nn(e){let t=we(e,zi),r=await pt(t,"utf-8"),n=Qr(Qr(r,"blogCategories",t),"blogAuthors",t);await lt(t,n)}function Qr(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 on(e){let t=we(e,"packages/i18n/translations"),r;try{r=await Hi(t)}catch{return}for(let n of r){let o=we(t,n,"web.json"),i;try{i=await pt(o,"utf-8")}catch{continue}let s=JSON.parse(i);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await lt(o,JSON.stringify(s,null," ")+`
20
+ `))}}var Wi="packages/config/src/ai/tasks.ts";async function sn(e){let t=we(e,Wi),r=await pt(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.`);await lt(t,n)}async function an(e,t){let r=we(e,".claude","settings.json"),n;try{n=await pt(r,"utf8")}catch{return}let o=JSON.parse(n);delete o.alwaysThinkingEnabled,delete o.enableAllProjectMcpServers,o.env&&(delete o.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(o.env).length===0&&delete o.env),o.permissions?.allow&&(o.permissions.allow=o.permissions.allow.filter(i=>qi(i,t))),await lt(r,JSON.stringify(o,null," ")+`
21
+ `)}function qi(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as cn}from"path";var Xi={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Zi={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Qi={redis:"Redis",upstash:"Upstash Redis"},es={node:"Node.js / Docker",vercel:"Vercel"},ts={stripe:"Stripe",polar:"Polar"};function rs(e){let t=e.frontend==="nuxt",r=t?"Nuxt 4":"Next.js 16",n=t?"apps/web-nuxt":"apps/web-next",o=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",i=e.architecture==="fullstack",s=i?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",a=i?`Mounted inside \`${n}\`. 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.",l=Qi[e.cacheProvider],u=es[e.deploymentTarget],y=e.paymentProvider==="none"?"":`
22
+ - **Payments:** ${ts[e.paymentProvider]}`,f=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",h=e.companion?"\n- **Companion daemon** - your users install OpenCompanion on a machine they control and pair it with their account. Everything you own lives in this repo: the `/companion/*` routes, the relay, the Companions page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",$=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",b=t?"**Navigation:** always use `localePath()` for paths (hardcoded paths break non-default locales); `await navigateTo()` in SSR.":"**Navigation:** `next/link` for links; `redirect()` from `next/navigation` for programmatic redirects in Server Components.";return`# AGENTS.md
25
23
 
26
24
  Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
27
25
  Keep this file tight: add a rule only when it prevents a recurring mistake - too
@@ -35,7 +33,7 @@ and go find it:
35
33
 
36
34
  1. \`docs/${t?"nuxt":"next"}/index.mdx\` - the catalog of every shipped feature and its config flag.
37
35
  2. \`packages/config/src/index.ts\` - the flag that turns the feature on/off (check it before rendering).
38
- 3. Search \`packages/\` and \`${r}/\` for the name before creating anything.
36
+ 3. Search \`packages/\` and \`${n}/\` for the name before creating anything.
39
37
 
40
38
  Already built - extend these, never re-implement: auth (email / OAuth / 2FA / passkeys),
41
39
  billing & subscriptions, credits, organizations & teams, notifications, email, SMS,
@@ -47,13 +45,13 @@ flag, route, or translation is the most common and most costly mistake in this r
47
45
 
48
46
  ## Stack
49
47
 
50
- - **Frontend:** ${n} ${a}
51
- - **API:** Hono, RPC-typed. ${s}
52
- - **Database:** Drizzle ORM + ${Ji[e.databaseProvider]}
53
- - **Cache + jobs:** ${u} + Inngest
54
- - **Auth:** Better Auth${l}
55
- - **Email:** ${Yi[e.emailProvider]}
56
- - **Deploy:** ${g}
48
+ - **Frontend:** ${r} ${s}
49
+ - **API:** Hono, RPC-typed. ${a}
50
+ - **Database:** Drizzle ORM + ${Xi[e.databaseProvider]}
51
+ - **Cache + jobs:** ${l} + Inngest
52
+ - **Auth:** Better Auth${y}
53
+ - **Email:** ${Zi[e.emailProvider]}
54
+ - **Deploy:** ${u}
57
55
 
58
56
  ## Where things live (extend these - don't reinvent)
59
57
 
@@ -63,8 +61,8 @@ flag, route, or translation is the most common and most costly mistake in this r
63
61
  - \`packages/auth/src/config.ts\` - Better Auth config.
64
62
  - \`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\`.
65
63
  - \`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.
66
- - \`${r}\` - the ${n} app (${o}).${S}
67
- - \`docs/${t?"nuxt":"next"}/\` - 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/\`${h}.
64
+ - \`${n}\` - the ${r} app (${o}).${h}
65
+ - \`docs/${t?"nuxt":"next"}/\` - 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/\`${f}.
68
66
 
69
67
  ## Code style
70
68
 
@@ -81,8 +79,8 @@ flag, route, or translation is the most common and most costly mistake in this r
81
79
 
82
80
  - **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
83
81
  - **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
84
- - **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${C} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
85
- - ${E}
82
+ - **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${$} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
83
+ - ${b}
86
84
  - **Routes:** use \`config.routes.*\`, never hardcoded path strings.
87
85
  - **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
88
86
 
@@ -93,25 +91,23 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
93
91
  ## This project
94
92
 
95
93
  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\`.
96
- `}async function Rr(e){await p(Ir(e.projectDir,"AGENTS.md"),Zi(e)),await p(Ir(e.projectDir,"CLAUDE.md"),`@AGENTS.md
97
- `)}import{join as Qi}from"path";var ea={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ta(e){let t=e.appName.trim()||e.projectName,n=e.frontend==="nuxt",r=n?"Nuxt 4":"Next.js 16",o=n?"apps/web-nuxt":"apps/web-next",i=ea[e.databaseProvider],a=Dt(e),s=e.architecture==="fullstack"?`${r} app at \`${o}/\` 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.`:`${r} app at \`${o}/\` and a separate Hono backend at \`apps/backend/\`.`,u=e.architecture==="fullstack"?`- App + API: http://localhost:3000
94
+ `}async function pn(e){await c(cn(e.projectDir,"AGENTS.md"),rs(e)),await c(cn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
95
+ `)}import{join as ns}from"path";var os={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function is(e){let t=e.appName.trim()||e.projectName,r=e.frontend==="nuxt",n=r?"Nuxt 4":"Next.js 16",o=r?"apps/web-nuxt":"apps/web-next",i=os[e.databaseProvider],s=e.architecture==="fullstack"?`${n} app at \`${o}/\` 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.`:`${n} app at \`${o}/\` and a separate Hono backend at \`apps/backend/\`.`,a=e.architecture==="fullstack"?`- App + API: http://localhost:3000
98
96
  - Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
99
97
  - API: http://localhost:3010
100
- - Inngest dev server: http://127.0.0.1:8288`,g=a?`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
101
- `:"",l=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
102
-
103
- This 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).${a?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,h=e.aiTools.length>0?"To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: `update my GenerateSaaS project`.":"To pull the latest boilerplate changes into this project, install an AI coding agent (Claude Code / Cursor / Codex / Gemini CLI / Windsurf) and ask: `update my GenerateSaaS project`. The skill bundle that drives the update lives under each tool's skill root.";return`# ${t}
98
+ - Inngest dev server: http://127.0.0.1:8288`,l=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
99
+ `,u=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}
104
100
 
105
101
  ${s}
106
102
 
107
103
  ## Stack
108
104
 
109
- - **Frontend:** ${r}
105
+ - **Frontend:** ${n}
110
106
  - **Backend:** Hono (TypeScript, RPC-typed)
111
107
  - **Auth:** Better Auth
112
108
  - **ORM / DB:** Drizzle + ${i}
113
109
  - **Background jobs:** Inngest
114
- - **i18n:** ${n?"@nuxtjs/i18n":"next-intl"}
110
+ - **i18n:** ${r?"@nuxtjs/i18n":"next-intl"}
115
111
 
116
112
  ## Development
117
113
 
@@ -120,11 +116,11 @@ pnpm install
120
116
  # A ready-to-run \`.env\` was generated for you - open it and fill in the
121
117
  # values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
122
118
  # reference. All apps load the single root \`.env\`.
123
- ${g}pnpm db:setup # first run: create the database schema (idempotent)
119
+ ${l}pnpm db:setup # first run: create the database schema (idempotent)
124
120
  pnpm dev
125
121
  \`\`\`
126
122
 
127
- ${u}
123
+ ${a}
128
124
 
129
125
  ## Build your SaaS
130
126
 
@@ -144,7 +140,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
144
140
  pnpm auth:generate # regenerate Better Auth schema after config changes
145
141
  \`\`\`
146
142
 
147
- ${l}
143
+ ${u}
148
144
 
149
145
  ## Removing the GenerateSaaS license
150
146
 
@@ -156,19 +152,34 @@ pnpm dlx generatesaas eject
156
152
 
157
153
  ## Updates
158
154
 
159
- ${h}
160
- `}async function Pr(e){await p(Qi(e.projectDir,"README.md"),ta(e))}import{access as ra,readFile as oa}from"fs/promises";import{join as Ce}from"path";import{join as na}from"path";function wn(e,t){let n=Ct(e,"companion"),r=t?new URL(t).hostname.split(".").reverse().join("."):"com",o=n.toUpperCase().replace(/-/g,"_");return{name:e,binary:n,scope:`@${n}`,serviceLabel:`${r}.${n}`,appDirName:n,envPrefix:/^[0-9]/.test(o)?`_${o}`:o,docsUrl:"",repoUrl:"",installBase:""}}async function Tr(e){if(!ue(e)||e.demo||H(e)==="shared")return;if(!e.companionName)throw new Error("generateCompanionBrand: this project ships a companion daemon but options.companionName is missing.");let t=wn(e.companionName,e.baseUrl);await p(na(e.projectDir,"apps/companion/brand.json"),JSON.stringify(t,null,2)+`
161
- `)}async function ia(e,t,n){let r=Ce(e,"apps/electron/dev-app-update.yml");try{await ra(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await p(r,`provider: generic
155
+ To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
156
+ `}async function ln(e){await c(ns(e.projectDir,"README.md"),is(e))}import{access as ss,readFile as as}from"fs/promises";import{join as Ae}from"path";async function cs(e,t,r){let n=Ae(e,"apps/electron/dev-app-update.yml");try{await ss(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await c(n,`provider: generic
162
157
  url: ${t}
163
- updaterCacheDirName: ${n}
164
- `)}function aa(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function sa(e,t){let n=Ct(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${n.replace(/-/g,"")}`,productName:e,protocol:n}}async function ca(e){if(!e.companion&&!ue(e))return'{ enabled: false, clientId: "companion" }';let t;if(e.demo)t=JSON.parse(await oa(Ce(e.projectDir,"apps/companion/brand.json"),"utf8"));else if(H(e)==="shared"){let r=await Qn(e),o=oe(e.companionRepoUrl??"").canonicalUrl;t={name:r.name,binary:r.binary,envPrefix:r.envPrefix,repoUrl:o,installBase:`${o}/releases/latest/download`}}else{if(!e.companionName)throw new Error("generateConfig: this project ships a companion daemon but options.companionName is missing.");t=wn(e.companionName,e.baseUrl)}let n={name:t.name,binary:t.binary,envPrefix:t.envPrefix,repoUrl:t.repoUrl,installBase:t.installBase};return["{",` enabled: ${e.companion},`,' clientId: "companion",'," daemon: {",` name: ${JSON.stringify(n.name)},`,` binary: ${JSON.stringify(n.binary)},`,` envPrefix: ${JSON.stringify(n.envPrefix)},`,` repoUrl: ${JSON.stringify(n.repoUrl)},`,` installBase: ${JSON.stringify(n.installBase)}`," }"," }"].join(`
165
- `)}async function _r(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=e.paymentProvider!=="none",r=e.baseUrl??"http://localhost:3000",o=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",i=aa(o),a=e.demo?"false":"true",s=e.demo?`{
158
+ updaterCacheDirName: ${r}
159
+ `)}function ps(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function ls(e,t){let r=jr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var dt={name:"OpenCompanion",binary:"opencompanion",envPrefix:"OPENCOMPANION",repoUrl:"https://github.com/AlexChelan/OpenCompanion",installBase:"https://github.com/AlexChelan/OpenCompanion/releases/latest/download"};function ds(e){return e.companion?["{"," enabled: true,",' clientId: "companion",'," daemon: {",` name: ${JSON.stringify(dt.name)},`,` binary: ${JSON.stringify(dt.binary)},`,` envPrefix: ${JSON.stringify(dt.envPrefix)},`,` repoUrl: ${JSON.stringify(dt.repoUrl)},`,` installBase: ${JSON.stringify(dt.installBase)}`," }"," }"].join(`
160
+ `):'{ enabled: false, clientId: "companion" }'}var us="// Off by default and off costs nothing: every surface checks `errorTracking.enabled`\n// and the selected provider's credentials before it dynamically imports an SDK. Turn\n// it on by flipping `enabled`, picking a `provider` and pasting that provider's key.\n// Keep `enabled` a literal - the bundler folds the branch away only when it can see\n// the value, and a computed flag ships the SDK to every visitor.",ms="// `enabled` MUST stay a literal true/false. Every surface checks it before it dynamically\n// imports an SDK, and your bundler drops the whole branch only when it can see the value\n// inline - a computed or imported flag ships the SDK to every visitor instead.",fs=`// Both provider blocks are always written, so toggling \`enabled\` off or switching
161
+ // provider never loses a key. The Sentry DSN and the PostHog public key are public by
162
+ // design (they only authorize sending events, never reading them), which is why they
163
+ // are committed here rather than kept in env - a packaged desktop app has no env to
164
+ // read. Server-side, SENTRY_DSN and POSTHOG_API_KEY override the values below.`,gs=` enabled: false,
165
+ provider: "sentry",`;function hs(e){return e==="sentry"?`// Paste your project DSN below (Sentry: Settings -> Projects -> Client Keys). The DSN is
166
+ // public by design - it only authorizes SENDING events, never reading them - which is why it
167
+ // lives here rather than in env, and why a packaged desktop app can carry it. Server-side,
168
+ // SENTRY_DSN overrides it.`:e==="posthog"?`// Paste your PostHog project API key below (it starts with \`phc_\`) and set the host of your
169
+ // instance. The key is public by design - it only authorizes SENDING events - which is why it
170
+ // lives here rather than in env. Server-side, POSTHOG_API_KEY overrides it.
171
+ //
172
+ // PostHog ships no Electron SDK, so a desktop build reports nothing and says so once at startup.
173
+ // PostHog error tracking uses its own client, separate from PostHog analytics, so declining
174
+ // cookies stops analytics but never stops error reports.`:"// Your project was generated with error tracking OFF, so no reporting SDK was installed and no\n// provider adapter was generated. Flipping `enabled` here alone reports nothing: set\n// `errorTracking` in `.generatesaas/manifest.json` to the provider you want and run\n// `generatesaas update`, which re-shapes the project and brings that provider's adapter and SDK in.\n// The update stages nothing while you are already on the latest version, so the switch lands with\n// the next release."}async function ys(e,t){let r=Ae(e,"packages/config/src/observability.mjs"),n;try{n=await as(r,"utf-8")}catch{throw new Error("generateConfig: expected packages/config/src/observability.mjs to exist - did the config package move?")}let o=t!=="none",i=[{find:us,replace:ms},{find:fs,replace:hs(t)},{find:gs,replace:` enabled: ${String(o)},
175
+ provider: "${o?t:"sentry"}",`}];for(let s of i){if(!n.includes(s.find))throw new Error(`generateConfig: packages/config/src/observability.mjs no longer contains the text this generator rewrites - re-point the anchor. Missing: ${s.find.split(`
176
+ `)[0]}`);n=n.replace(s.find,s.replace)}return n}async function dn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",o=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",i=ps(o),s=e.demo?"false":"true",a=e.demo?`{
166
177
  enableInDev: true,
167
178
  chatwoot: {
168
179
  baseUrl: "https://support.alexchelan.com",
169
180
  websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
170
181
  }
171
- }`:"{}",u=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",g=sa(t,i),l=`https://cdn.${i}/desktop`,h=await ca(e),S=`import type { AppConfig } from "@repo/config/types";
182
+ }`:"{}",l=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",u=ls(t,i),y=`https://cdn.${i}/desktop`,f=ds(e),h=`import type { AppConfig } from "@repo/config/types";
172
183
  import { desktopConfig } from "./desktop.mjs";
173
184
  import { observabilityConfig } from "./observability.mjs";
174
185
  import { supportConfig } from "./support.mjs";
@@ -180,8 +191,8 @@ export const config: AppConfig = {
180
191
  siteName: "${t}",
181
192
  fullSiteName: "${t}",
182
193
  domain: "${o}",
183
- baseUrl: process.env.BASE_URL ?? "${r}",
184
- indexable: ${a},
194
+ baseUrl: process.env.BASE_URL ?? "${n}",
195
+ indexable: ${s},
185
196
  logo: {
186
197
  main: "/images/logo.svg",
187
198
  square: "/images/logo-square.svg"
@@ -231,7 +242,7 @@ export const config: AppConfig = {
231
242
  maxFileSizeMB: 5,
232
243
  dailyUploadLimit: 20
233
244
  },
234
- payment: ${n?`{
245
+ payment: ${r?`{
235
246
  enabled: true,
236
247
  provider: "${e.paymentProvider}",
237
248
  bannedCountries: ["BY", "CU", "IR", "KP", "RU", "SY"]
@@ -243,7 +254,7 @@ export const config: AppConfig = {
243
254
  prefix: "key_"
244
255
  },
245
256
  apiDocs: true,
246
- performanceMonitor: { enabled: ${u} },
257
+ performanceMonitor: { enabled: ${l} },
247
258
  observability: observabilityConfig,
248
259
  notifications: {
249
260
  enabled: true,
@@ -283,7 +294,7 @@ export const config: AppConfig = {
283
294
  }`:`{
284
295
  base: "${e.defaultCurrency}",
285
296
  list: [
286
- { symbol: "${Ie[e.defaultCurrency].symbol}", name: "${Ie[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Ie[e.defaultCurrency].place}", space: ${Ie[e.defaultCurrency].space} }
297
+ { symbol: "${be[e.defaultCurrency].symbol}", name: "${be[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${be[e.defaultCurrency].place}", space: ${be[e.defaultCurrency].space} }
287
298
  ],
288
299
  countryMap: {
289
300
  default: "${e.defaultCurrency}"
@@ -310,7 +321,7 @@ export const config: AppConfig = {
310
321
  // Built-in AI: your app offers models under its OWN name, billed from user credits (which need a
311
322
  // payment provider to buy), so it is generated on exactly when a payment provider exists. Powered by
312
323
  // OpenRouter - set OPENROUTER_API_KEY in your env, that is the whole setup. Flip this to change it.
313
- builtin: ${n},
324
+ builtin: ${r},
314
325
  // Let users connect their own provider API keys; flip to false to disable.
315
326
  byok: true,
316
327
  // What every user starts on (their own choice, once made, always wins). Plain
@@ -331,8 +342,8 @@ export const config: AppConfig = {
331
342
  }
332
343
  },
333
344
  desktop: desktopConfig,
334
- // Companion: your vendored companion daemon (apps/companion) that your users install to run their own subscription CLIs. Off by default.
335
- companion: ${h},
345
+ // Companion: the OpenCompanion daemon your users install to run their own subscription CLIs for this app. Off by default.
346
+ companion: ${f},
336
347
  // Outward MCP server exposing the capability layer to external agents. Its code ships with every
337
348
  // project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
338
349
  mcpServer: { enabled: ${e.demo?"true":"false"} },
@@ -376,7 +387,7 @@ export * from "./pricing";
376
387
  export * from "./roles";
377
388
  export * from "./section-tabs";
378
389
  export * from "./tenancy";
379
- `,C=Ce(e.projectDir,"packages/config/src/index.ts");await p(C,S),await p(Ce(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
390
+ `,$=Ae(e.projectDir,"packages/config/src/index.ts");await c($,h),await c(Ae(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
380
391
  // TypeScript config index reads it directly: the Electron main + renderer bundles,
381
392
  // the CSP policy builder, and the electron-builder packaging config. Edit these
382
393
  // values once to rebrand - they are the same in dev and production, so they live in
@@ -384,10 +395,10 @@ export * from "./tenancy";
384
395
 
385
396
  export const desktopConfig = {
386
397
  enabled: ${e.desktop},
387
- appId: "${g.appId}",
388
- productName: "${g.productName}",
389
- protocol: "${g.protocol}",
390
- baseUrl: "${r}",
398
+ appId: "${u.appId}",
399
+ productName: "${u.productName}",
400
+ protocol: "${u.protocol}",
401
+ baseUrl: "${n}",
391
402
  // Name of the app's data folder (created under the OS app-data dir). Where the app
392
403
  // and its AI agents persist files - logs, gathered data, generated artifacts. Rename
393
404
  // it freely; it is a plain folder name, not a path.
@@ -395,7 +406,12 @@ export const desktopConfig = {
395
406
  // Public base URL the release workflow uploads to; electron-updater polls
396
407
  // \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
397
408
  // the per-installer blockmaps, and the stable installer download links live under it.
398
- autoUpdate: { url: "${l}" },
409
+ autoUpdate: { url: "${y}" },
410
+ // Whether the support live-chat widget you configured in config.support (Crisp,
411
+ // Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
412
+ // every surface. Set false to keep live chat on your website only - the app then
413
+ // mounts no widget and its CSP never names the provider's origins.
414
+ supportChat: true,
399
415
  agents: {
400
416
  // Feature toggles only. Agents run in the app's main process (companion supervision +
401
417
  // the daemon transport bridge), driven through the @repo/agent-core seam - typed
@@ -420,10 +436,15 @@ export const desktopConfig = {
420
436
  // connection lock). Default false: the app is local-first and connecting is an
421
437
  // OPTIONAL, explicit user action. Set true for a structurally private product - the
422
438
  // connect surface never renders AND the daemon refuses pairing.
423
- connectionLock: false
439
+ connectionLock: false,
440
+ // Whether agent work continues after the window closes. OFF by default: the runtime is a
441
+ // child process of the app and is killed at quit. Turn it on if your product's value
442
+ // depends on schedules firing while the app is closed; end users then get a
443
+ // "Keep running after I close the window" toggle.
444
+ background: false
424
445
  }
425
446
  };
426
- `),await p(Ce(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
447
+ `),await c(Ae(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
427
448
  // TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
428
449
  // desktop.mjs pattern. The config index re-exports this as config.tenancy.
429
450
 
@@ -432,32 +453,14 @@ export const tenancyConfig = ${e.multiTenancy?`{
432
453
  organizationLimit: 5,
433
454
  billingScope: "${e.demo?"organization":"user"}"
434
455
  }`:"{ multiTenant: false }"};
435
- `),await p(Ce(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
456
+ `),await c(Ae(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
436
457
  // the TypeScript config index reads it directly (the Electron main + renderer and
437
458
  // the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
438
459
  // index re-exports this as config.support.
439
460
 
440
- export const supportConfig = ${s};
441
- `),await p(Ce(e.projectDir,"packages/config/src/observability.mjs"),`// Plain-JS observability (error reporting) config. NO env reads, so tooling that
442
- // cannot import the TypeScript config index reads it directly (the Electron main +
443
- // renderer, which have no env at all once packaged). Mirrors the support.mjs
444
- // pattern. The config index re-exports this as config.observability.
445
- //
446
- // Off by default and off costs nothing: every surface checks \`sentry.enabled\` and a
447
- // non-empty \`dsn\` before it dynamically imports the SDK, so nothing ships to your
448
- // users' browsers and nothing loads on your server. Turn it on by flipping \`enabled\`
449
- // and pasting your project DSN (Sentry: Settings -> Projects -> Client Keys) - the DSN
450
- // is public by design (it only authorizes sending events, never reading them), which is
451
- // why it lives here rather than in env. Server-side, SENTRY_DSN overrides it.
452
-
453
- export const observabilityConfig = {
454
- sentry: {
455
- enabled: false,
456
- dsn: ""
457
- }
458
- };
459
- `),e.desktop&&await ia(e.projectDir,l,`${g.protocol}-updater`)}import{join as pa}from"path";function la(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function vn(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxSchedules!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxSchedules: ${e.maxSchedules}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
460
- `)}async function xr(e){let t=pa(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let C=`import type { PricingConfig } from "@repo/config/types";
461
+ export const supportConfig = ${a};
462
+ `),await c(Ae(e.projectDir,"packages/config/src/observability.mjs"),await ys(e.projectDir,e.errorTracking)),e.desktop&&await cs(e.projectDir,y,`${u.protocol}-updater`)}import{join as ws}from"path";function vs(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function ar(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxSchedules!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxSchedules: ${e.maxSchedules}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
463
+ `)}async function un(e){let t=ws(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let $=`import type { PricingConfig } from "@repo/config/types";
461
464
 
462
465
  export const pricingConfig: PricingConfig = {
463
466
  defaultPlan: "free",
@@ -477,7 +480,7 @@ export const pricingConfig: PricingConfig = {
477
480
  prices: [
478
481
  {
479
482
  interval: "lifetime",
480
- amounts: { ${n}: 0 }
483
+ amounts: { ${r}: 0 }
481
484
  }
482
485
  ],
483
486
  apiRateLimit: { maxRequests: 100 }
@@ -486,21 +489,21 @@ export const pricingConfig: PricingConfig = {
486
489
  credits: { enabled: false },
487
490
  products: { enabled: false, items: [] }
488
491
  };
489
- `;await p(t,C);return}let r=e.paymentProvider,o=la(r),i=e.credits,a=!!e.ai,s=vn({credits:5,rateLimit:100,withCredits:i,...a&&{maxSchedules:3}}),u=vn({credits:10,rateLimit:1e3,withCredits:i,...a&&{maxSchedules:10}}),g=vn({credits:50,rateLimit:5e3,withCredits:i}),l=n==="USD"?"":` // !! ${n} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
490
- // !! USD), but your plan prices and credit purchases are denominated in ${n}. Verify that the
491
- // !! ${n} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
492
+ `;await c(t,$);return}let n=e.paymentProvider,o=vs(n),i=e.credits,s=!!e.ai,a=ar({credits:5,rateLimit:100,withCredits:i,...s&&{maxSchedules:3}}),l=ar({credits:10,rateLimit:1e3,withCredits:i,...s&&{maxSchedules:10}}),u=ar({credits:50,rateLimit:5e3,withCredits:i}),y=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
493
+ // !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
494
+ // !! ${r} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
492
495
  // !! 20% markup) - and raise prices or creditsPerUsd if they do not.
493
- `;i&&n!=="USD"&&console.warn(`
494
- !! ${n} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
495
- !! plan prices and credit purchases are denominated in ${n}. At the shipped economics 1 credit
496
- !! carries ~0.42 USD of AI cost - verify every ${n} price still covers it (see the comment on the
496
+ `;i&&r!=="USD"&&console.warn(`
497
+ !! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
498
+ !! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
499
+ !! carries ~0.42 USD of AI cost - verify every ${r} price still covers it (see the comment on the
497
500
  !! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
498
- `);let h=i?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
501
+ `);let f=i?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
499
502
  // 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
500
503
  // external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
501
504
  // the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
502
505
  // full utilization runs you at a loss.
503
- ${l} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",S=`import type { PricingConfig } from "@repo/config/types";
506
+ ${y} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",h=`import type { PricingConfig } from "@repo/config/types";
504
507
 
505
508
  export const pricingConfig: PricingConfig = {
506
509
  defaultPlan: "free",
@@ -521,10 +524,10 @@ export const pricingConfig: PricingConfig = {
521
524
  prices: [
522
525
  {
523
526
  interval: "lifetime",
524
- amounts: { ${n}: 0 }
527
+ amounts: { ${r}: 0 }
525
528
  }
526
529
  ],
527
- ${s}
530
+ ${a}
528
531
  },
529
532
  {
530
533
  id: "starter",
@@ -541,16 +544,16 @@ ${s}
541
544
  {
542
545
  ${o}
543
546
  interval: "month",
544
- amounts: { ${n}: 9 }
547
+ amounts: { ${r}: 9 }
545
548
  },
546
549
  {
547
550
  ${o}
548
551
  interval: "year",
549
- amounts: { ${n}: 90 },
550
- anchorAmounts: { ${n}: 109 }
552
+ amounts: { ${r}: 90 },
553
+ anchorAmounts: { ${r}: 109 }
551
554
  }
552
555
  ],
553
- ${u}
556
+ ${l}
554
557
  },
555
558
  {
556
559
  id: "pro",
@@ -570,31 +573,31 @@ ${u}
570
573
  {
571
574
  ${o}
572
575
  interval: "month",
573
- amounts: { ${n}: 29 },
574
- anchorAmounts: { ${n}: 39 },
576
+ amounts: { ${r}: 29 },
577
+ anchorAmounts: { ${r}: 39 },
575
578
  featured: true
576
579
  },
577
580
  {
578
581
  ${o}
579
582
  interval: "year",
580
- amounts: { ${n}: 290 },
581
- anchorAmounts: { ${n}: 349 }
583
+ amounts: { ${r}: 290 },
584
+ anchorAmounts: { ${r}: 349 }
582
585
  }
583
586
  ],
584
- ${g}
587
+ ${u}
585
588
  }
586
589
  ],
587
- ${h},
590
+ ${f},
588
591
  products: {
589
592
  enabled: false,
590
593
  items: []
591
594
  }
592
595
  };
593
- `;await p(t,S)}var da={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"}]},ua={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 bt(e,t){return t?e.map(n=>{let r=t[n.key];return r?{...n,defaultValue:r,comment:void 0}:n}):e}function St(e,t){for(let n of e)n.comment&&t.push(n.comment),n.defaultValue!==void 0?t.push(`${n.key}=${n.defaultValue}`):t.push(`#${n.key}=`)}function kn(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Dr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function ma(e){let{architecture:t,deploymentTarget:n}=e;return t==="fullstack"?n==="vercel"?{frontend:"https://your-app.vercel.app",backend:"https://your-app.vercel.app"}:n==="node"?{frontend:"https://your-app.example.com",backend:"https://your-app.example.com"}:null:{frontend:"https://your-app.example.com",backend:"https://your-app.example.com/api"}}function Kt(e,t,n,r){e.push(r==="example"?`${t}=`:`${t}=${n}`)}function Or(e,t){let n=t==="example"?void 0:e.credentials,{apiUrl:r,baseUrl:o}=Dr(e),i=[];e.architecture==="separate"?i.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${r}`,`BASE_URL=${o}`):i.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${o}`),i.push("","# Database"),St(bt(K[e.databaseProvider].envVars,n),i),i.push("","# Cache"),St(bt(re[e.cacheProvider].envVars,n),i),i.push("","# Authentication"),t==="example"&&i.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Kt(i,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),i.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Kt(i,"CONTENT_API_KEY",kn(32),t),i.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Kt(i,"INNGEST_EVENT_KEY",kn(32),t),Kt(i,"INNGEST_SIGNING_KEY",kn(32),t),i.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(i.push("","# API Port (standalone backend)","API_PORT=3010"),i.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 a=da[e.emailProvider];if(a&&(i.push("","# Email"),St(bt(a,n),i)),e.paymentProvider!=="none"){let s=ua[e.paymentProvider];s&&(i.push("","# Payment"),St(bt(s,n),i))}return e.demo&&(i.push("","# Captcha (Cloudflare Turnstile)"),St(bt([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],n),i)),i.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="),i.push("","# AI base - provider API keys (optional)","# Enable config.ai in packages/config and set the key for your chosen provider.","# OPENROUTER_API_KEY above also works as an AI provider key.","#ANTHROPIC_API_KEY=","#OPENAI_API_KEY="),i.push(""),i.join(`
594
- `)}function fa(e){let{apiUrl:t}=Dr(e),n=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",r=["# API Configuration",`${n}=${t}`],o=ma(e);return o&&e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${n}=${o.backend}`),r.push(""),r.join(`
595
- `)}async function Cr(e){let t=fa(e);await p(`${e.projectDir}/.env`,t+`
596
- `+Or(e,"env")),await p(`${e.projectDir}/.env.example`,t+`
597
- `+Or(e,"example"))}import{join as ga}from"path";async function Nr(e){let t=[...e.dockerServices];if(K[e.databaseProvider].managed&&(t=t.filter(i=>i!=="postgres")),re[e.cacheProvider].managed&&(t=t.filter(i=>i!=="redis")),t.length===0)return!1;let n=[],r=[];t.includes("postgres")&&(n.push(` postgres:
596
+ `;await c(t,h)}var ks={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"}]},bs={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 ut(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 cr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function fn(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function Ss(e){let{architecture:t,deploymentTarget:r}=e;return t==="fullstack"?r==="vercel"?{frontend:"https://your-app.vercel.app",backend:"https://your-app.vercel.app"}:r==="node"?{frontend:"https://your-app.example.com",backend:"https://your-app.example.com"}:null:{frontend:"https://your-app.example.com",backend:"https://your-app.example.com/api"}}function Nt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function mn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:o}=fn(e),i=[];e.architecture==="separate"?i.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${o}`):i.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${o}`),i.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"&&e.frontend==="nextjs"?i.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."):i.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),i.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"),i.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"),i.push("","# Database"),mt(ut(re[e.databaseProvider].envVars,r),i),i.push("","# Cache"),mt(ut(Se[e.cacheProvider].envVars,r),i),i.push("","# Authentication"),t==="example"&&i.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Nt(i,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),i.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Nt(i,"CONTENT_API_KEY",cr(32),t),i.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Nt(i,"INNGEST_EVENT_KEY",cr(32),t),Nt(i,"INNGEST_SIGNING_KEY",cr(32),t),i.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(i.push("","# API Port (standalone backend)","API_PORT=3010"),i.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let s=ks[e.emailProvider];if(s&&(i.push("","# Email"),mt(ut(s,r),i)),e.paymentProvider!=="none"){let a=bs[e.paymentProvider];a&&(i.push("","# Payment"),mt(ut(a,r),i))}return e.demo&&(i.push("","# Captcha (Cloudflare Turnstile)"),mt(ut([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],r),i)),i.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="),i.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."),i.push(""),i.join(`
597
+ `)}function Es(e){let{apiUrl:t}=fn(e),r=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",n=["# API Configuration",`${r}=${t}`],o=Ss(e);return o&&e.architecture==="separate"&&n.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${r}=${o.backend}`),n.push(""),n.join(`
598
+ `)}async function gn(e){let t=Es(e);await c(`${e.projectDir}/.env`,t+`
599
+ `+mn(e,"env")),await c(`${e.projectDir}/.env.example`,t+`
600
+ `+mn(e,"example"))}import{join as Rs}from"path";async function hn(e){let t=Me(e),r=[],n=[];t.includes("postgres")&&(r.push(` postgres:
598
601
  image: postgres:18-alpine
599
602
  ports:
600
603
  - "\${POSTGRES_PORT:-5432}:5432"
@@ -609,7 +612,7 @@ ${h},
609
612
  test: ["CMD-SHELL", "pg_isready -U postgres"]
610
613
  interval: 5s
611
614
  timeout: 5s
612
- retries: 5`),r.push(" postgres_data:")),t.includes("redis")&&(n.push(` redis:
615
+ retries: 5`),n.push(" postgres_data:")),t.includes("redis")&&(r.push(` redis:
613
616
  image: redis:8-alpine
614
617
  ports:
615
618
  - "\${REDIS_PORT:-6379}:6379"
@@ -619,27 +622,27 @@ ${h},
619
622
  test: ["CMD", "redis-cli", "ping"]
620
623
  interval: 5s
621
624
  timeout: 5s
622
- retries: 5`),r.push(" redis_data:")),t.includes("mailpit")&&n.push(` mailpit:
625
+ retries: 5`),n.push(" redis_data:")),t.includes("mailpit")&&r.push(` mailpit:
623
626
  image: axllent/mailpit
624
627
  ports:
625
628
  - "\${MAILPIT_SMTP_PORT:-1025}:1025"
626
629
  - "\${MAILPIT_UI_PORT:-8025}:8025"
627
630
  environment:
628
631
  MP_SMTP_AUTH_ACCEPT_ANY: 1
629
- MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")&&n.push(` inngest:
632
+ MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")&&r.push(` inngest:
630
633
  image: inngest/inngest:v1.17.4
631
634
  ports:
632
635
  - "\${INNGEST_PORT:-8288}:8288"
633
636
  command: inngest dev`);let o=`services:
634
- ${n.join(`
637
+ ${r.join(`
635
638
 
636
639
  `)}
637
- `;return r.length>0&&(o+=`
640
+ `;n.length>0&&(o+=`
638
641
  volumes:
639
- ${r.join(`
642
+ ${n.join(`
640
643
  `)}
641
- `),await p(ga(e.projectDir,"infra/docker-compose.yml"),o),!0}import{join as ha}from"path";function ya(e){let t=[];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"}});let n=e.frontend==="nextjs"?"Next.js":"Nuxt";if(t.push({type:"node-terminal",request:"launch",name:n,command:"pnpm dev",cwd:`\${workspaceFolder}/apps/web-${e.frontend==="nextjs"?"next":"nuxt"}`,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 wa(e){let t=e.frontend==="nextjs"?"Next.js":"Nuxt",n=[];return e.architecture==="separate"?n.push({name:`Dev (${t} + Backend + Inngest)`,configurations:["Backend",t,"Inngest"]}):n.push({name:`Dev (${t} + Inngest)`,configurations:[t,"Inngest"]}),n}async function $r(e){let t={version:"0.2.0",configurations:ya(e),compounds:wa(e)};await p(ha(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
642
- `)}import{join as va}from"path";async function Lr(e){if(e.architecture!=="separate")return;await p(va(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
644
+ `),await c(Rs(e.projectDir,"infra/docker-compose.yml"),o)}import{join as Ps}from"path";function Is(e){let t=[];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"}});let r=e.frontend==="nextjs"?"Next.js":"Nuxt";if(t.push({type:"node-terminal",request:"launch",name:r,command:"pnpm dev",cwd:`\${workspaceFolder}/apps/web-${e.frontend==="nextjs"?"next":"nuxt"}`,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 n=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:n}})}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 n=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 ${n}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function Ts(e){let t=e.frontend==="nextjs"?"Next.js":"Nuxt",r=[];return e.architecture==="separate"?r.push({name:`Dev (${t} + Backend + Inngest)`,configurations:["Backend",t,"Inngest"]}):r.push({name:`Dev (${t} + Inngest)`,configurations:[t,"Inngest"]}),r}async function yn(e){let t={version:"0.2.0",configurations:Is(e),compounds:Ts(e)};await c(Ps(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
645
+ `)}import{join as As}from"path";async function wn(e){if(e.architecture!=="separate")return;await c(As(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
643
646
  import app from "@repo/api";
644
647
  import { closeRedis, env, logger } from "@repo/runtime";
645
648
 
@@ -670,12 +673,12 @@ bootstrap().catch((error) => {
670
673
  logger.error("[Backend] Fatal error", error);
671
674
  process.exit(1);
672
675
  });
673
- `)}import{readFile as ka}from"fs/promises";import{join as ba}from"path";var bn='import { drizzle } from "drizzle-orm/node-postgres";',Sn=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
674
- export const pool = db.$client;`,Sa={postgres:{importLine:bn,instantiation:Sn},neon:{importLine:`import { neon } from "@neondatabase/serverless";
675
- import { drizzle } from "drizzle-orm/neon-http";`,instantiation:`const sql = neon(parsed.data.DATABASE_URL);
676
- export const db = drizzle(sql, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
676
+ `)}import{readFile as Os}from"fs/promises";import{join as xs}from"path";var pr='import { drizzle } from "drizzle-orm/node-postgres";',lr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
677
+ export const pool = db.$client;`,Ds={postgres:{importLine:pr,instantiation:lr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
678
+ import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
679
+ export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
677
680
  import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
678
- export const db = drizzle(client, { schema });`}};async function jr(e){let t=ba(e.projectDir,"packages/database/src/index.ts"),n=await ka(t,"utf-8");if(!n.includes(bn)||!n.includes(Sn))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 r=Sa[e.databaseProvider],o=n.replace(bn,r.importLine).replace(Sn,r.instantiation);await p(t,o)}import{join as Ht}from"path";async function Ur(e){switch(e.cacheProvider){case"redis":await Ea(e),await Aa(e);break;case"upstash":await Ia(e),await Ra(e);break}}async function Ea(e){await p(Ht(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
681
+ export const db = drizzle(client, { schema });`}};async function vn(e){let t=xs(e.projectDir,"packages/database/src/index.ts"),r=await Os(t,"utf-8");if(!r.includes(pr)||!r.includes(lr))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=Ds[e.databaseProvider],o=r.replace(pr,n.importLine).replace(lr,n.instantiation);await c(t,o)}import{join as Ct}from"path";async function kn(e){switch(e.cacheProvider){case"redis":await _s(e),await Ns(e);break;case"upstash":await Cs(e),await $s(e);break}}async function _s(e){await c(Ct(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
679
682
  import { Redis } from "ioredis";
680
683
  import { RedisStore, type RedisReply } from "rate-limit-redis";
681
684
  import { env } from "./env";
@@ -804,7 +807,7 @@ export async function closeRedis() {
804
807
  closed = true;
805
808
  }
806
809
  }
807
- `)}async function Aa(e){await p(Ht(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
810
+ `)}async function Ns(e){await c(Ct(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
808
811
  import { redis } from "./redis";
809
812
 
810
813
  export class MutexTimeoutError extends Error {
@@ -841,7 +844,7 @@ export async function withMutex<T>(
841
844
  await mutex.release();
842
845
  }
843
846
  }
844
- `)}async function Ia(e){await p(Ht(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
847
+ `)}async function Cs(e){await c(Ct(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
845
848
  import type { Store } from "hono-rate-limiter";
846
849
  import { env } from "./env";
847
850
 
@@ -959,7 +962,7 @@ export const limiterStore: Store = createLimiterStore();
959
962
 
960
963
  /** No persistent connection to close with Upstash REST. */
961
964
  export async function closeRedis(): Promise<void> {}
962
- `)}async function Ra(e){await p(Ht(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
965
+ `)}async function $s(e){await c(Ct(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
963
966
  import { redis } from "./redis";
964
967
 
965
968
  export class MutexTimeoutError extends Error {
@@ -1004,144 +1007,18 @@ export async function withMutex<T>(
1004
1007
  await lock.release();
1005
1008
  }
1006
1009
  }
1007
- `)}async function Mr(e){await p(`${e.projectDir}/packages/runtime/src/env.ts`,Pa(e))}function Pa(e){return`import { z } from "zod";
1008
-
1009
- const EnvSchema = z.object({
1010
- NODE_ENV: z.enum(["development", "production"]).default("development"),
1011
-
1012
- API_PORT: z.coerce.number().int().positive().default(3010),
1013
- API_URL: z.url(),
1014
- BASE_URL: z.url().optional(),
1015
- TRUSTED_ORIGINS: z.string().optional(),
1016
- AUTH_COOKIE_DOMAIN: z.string().optional(),
1017
-
1018
- DATABASE_URL: z.url(),
1019
- ${e.cacheProvider==="upstash"?` UPSTASH_REDIS_REST_URL: z.string(),
1020
- UPSTASH_REDIS_REST_TOKEN: z.string(),`:" REDIS_URL: z.string(),"}
1021
-
1022
- BETTER_AUTH_SECRET: z.string().min(32),
1023
-
1024
- GOOGLE_CLIENT_ID: z.string().optional(),
1025
- GOOGLE_CLIENT_SECRET: z.string().optional(),
1026
-
1027
- GITHUB_CLIENT_ID: z.string().optional(),
1028
- GITHUB_CLIENT_SECRET: z.string().optional(),
1029
-
1030
- FACEBOOK_CLIENT_ID: z.string().optional(),
1031
- FACEBOOK_CLIENT_SECRET: z.string().optional(),
1032
-
1033
- DISCORD_CLIENT_ID: z.string().optional(),
1034
- DISCORD_CLIENT_SECRET: z.string().optional(),
1035
-
1036
- TWITTER_CLIENT_ID: z.string().optional(),
1037
- TWITTER_CLIENT_SECRET: z.string().optional(),
1038
-
1039
- INNGEST_APP_ID: z.string(),
1040
- INNGEST_EVENT_KEY: z.string(),
1041
- INNGEST_BASE_URL: z.url(),
1042
-
1043
- AMAZON_SES_REGION: z.string().optional(),
1044
- AMAZON_SES_KEY: z.string().optional(),
1045
- AMAZON_SES_SECRET: z.string().optional(),
1046
-
1047
- RESEND_API_KEY: z.string().optional(),
1048
- RESEND_AUDIENCE_ID: z.string().optional(),
1049
-
1050
- LISTMONK_URL: z.url().optional(),
1051
- LISTMONK_API_USER: z.string().optional(),
1052
- LISTMONK_API_TOKEN: z.string().optional(),
1053
- LISTMONK_LIST_ID: z.coerce.number().int().positive().optional(),
1054
-
1055
- SMTP_HOST: z.string().optional(),
1056
- SMTP_PORT: z.coerce.number().int().positive().optional(),
1057
- SMTP_USER: z.string().optional(),
1058
- SMTP_PASSWORD: z.string().optional(),
1059
-
1060
- TWILIO_ACCOUNT_SID: z.string().optional(),
1061
- TWILIO_AUTH_TOKEN: z.string().optional(),
1062
- TWILIO_PHONE_NUMBER: z.string().optional(),
1063
-
1064
- AMAZON_SNS_REGION: z.string().optional(),
1065
- AMAZON_SNS_KEY: z.string().optional(),
1066
- AMAZON_SNS_SECRET: z.string().optional(),
1067
- AMAZON_SNS_SENDER_ID: z.string().optional(),
1068
- AMAZON_SNS_ORIGINATION_NUMBER: z.string().optional(),
1069
-
1070
- STRIPE_SECRET_KEY: z.string().optional(),
1071
- STRIPE_WEBHOOK_SECRET: z.string().optional(),
1072
-
1073
- POLAR_ACCESS_TOKEN: z.string().optional(),
1074
- POLAR_WEBHOOK_SECRET: z.string().optional(),
1075
-
1076
- STORAGE_REGION: z.string().optional(),
1077
- STORAGE_ENDPOINT: z.string().optional(),
1078
- STORAGE_ACCESS_KEY_ID: z.string().optional(),
1079
- STORAGE_SECRET_ACCESS_KEY: z.string().optional(),
1080
- STORAGE_PUBLIC_BUCKET: z.string().optional(),
1081
- STORAGE_PRIVATE_BUCKET: z.string().optional(),
1082
- STORAGE_PUBLIC_URL: z.string().optional(),
1083
-
1084
- STORAGE_LOCAL_PATH: z.string().optional(),
1085
- STORAGE_LOCAL_PUBLIC_URL: z.string().optional(),
1086
-
1087
- DISCORD_WEBHOOK_URL: z.url().optional(),
1088
- SLACK_WEBHOOK_URL: z.url().optional(),
1089
- TELEGRAM_BOT_TOKEN: z
1090
- .string()
1091
- .regex(/^\\d+:[A-Za-z0-9_-]+$/, "Invalid Telegram bot token format")
1092
- .optional(),
1093
- TELEGRAM_CHAT_ID: z.string().optional(),
1094
- TELEGRAM_TOPIC_ID: z.string().optional(),
1095
-
1096
- TURNSTILE_SECRET_KEY: z.string().optional(),
1097
-
1098
- CONTENT_API_KEY: z.string().min(16).optional(),
1099
-
1100
- ANTHROPIC_API_KEY: z.string().optional(),
1101
- OPENAI_API_KEY: z.string().optional(),
1102
- OPENROUTER_API_KEY: z.string().optional(),
1103
-
1104
- MASTRA_TELEMETRY_DISABLED: z.string().optional(),
1105
-
1106
- /** Server-side override for \`config.observability.sentry.dsn\`. Optional: the committed config value is the default. */
1107
- SENTRY_DSN: z.string().optional()
1108
- });
1109
-
1110
- export const env = (() => {
1111
- // Compute API_URL fallback BEFORE Zod sees the input. Zod 4.4 ignores
1112
- // \`z.preprocess\` output when the input key is absent from the parent
1113
- // object - this guarantees the key is always present and avoids the regression.
1114
- const rawEnv = { ...process.env };
1115
- rawEnv.API_URL =
1116
- rawEnv.API_URL ||
1117
- rawEnv.NUXT_PUBLIC_API_URL ||
1118
- rawEnv.NEXT_PUBLIC_API_URL ||
1119
- rawEnv.PUBLIC_API_URL;
1120
- const parsed = EnvSchema.safeParse(rawEnv);
1121
-
1122
- if (!parsed.success) {
1123
- const message = parsed.error.issues
1124
- .map((issue) => \`\${issue.path.join(".") || "unknown"}: \${issue.message}\`)
1125
- .join(", ");
1126
- throw new Error(\`Invalid runtime package environment: \${message}\`);
1127
- }
1128
- return parsed.data;
1129
- })();
1130
-
1131
- const parsedApiUrl = new URL(env.API_URL);
1132
- export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
1133
- export const apiOrigin = parsedApiUrl.origin;
1134
- `}import{readFile as Ta}from"fs/promises";import{join as z}from"path";var zt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function Qe(e){let t=await Ta(e,"utf-8");return JSON.parse(t)}async function et(e,t){await p(e,JSON.stringify(t,null," ")+`
1135
- `)}function Et(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function Ze(e,t,n,r=!1){let o=r?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=n}async function Fr(e){await _a(e),await xa(e),await Oa(e),await Da(e),e.frontend==="nextjs"?await La(e):await $a(e)}async function _a(e){let t=z(e.projectDir,"packages/api/package.json"),n=await Qe(t);Et(n,["sharp","@types/sharp"]),await et(t,n)}async function xa(e){let t=z(e.projectDir,"packages/runtime/package.json"),n=await Qe(t);e.cacheProvider==="upstash"&&(Et(n,["ioredis","rate-limit-redis","redis-semaphore"]),Ze(n,"@upstash/redis",zt["@upstash/redis"]),Ze(n,"@upstash/lock",zt["@upstash/lock"])),await et(t,n)}async function Oa(e){let t=z(e.projectDir,"packages/database/package.json"),n=await Qe(t);e.databaseProvider==="neon"?(Et(n,["pg","@types/pg"]),Ze(n,"@neondatabase/serverless",zt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Et(n,["pg","@types/pg"]),Ze(n,"postgres",zt.postgres)),await et(t,n)}async function Da(e){if(e.architecture!=="separate")return;let t=z(e.projectDir,"apps/backend/package.json"),n=await Qe(t);e.deploymentTarget!=="node"&&Et(n,["@hono/node-server"]),await et(t,n)}var Ca=["server/routes/.well-known/oauth-authorization-server/[...path].ts","server/routes/.well-known/oauth-protected-resource/[...path].ts","server/routes/.well-known/oauth-authorization-server.ts","server/routes/.well-known/oauth-protected-resource.ts"],Na=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function $a(e){if(e.architecture!=="separate")return;let t=z(e.projectDir,"apps/web-nuxt");await ht(z(t,"server/api/[...paths].ts"),t);for(let i of Ca)await ht(z(t,i),t);let n=z(t,"package.json"),r=await Qe(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],Ze(r,"@repo/api",o,!0)),await et(n,r)}async function La(e){if(e.architecture!=="separate")return;let t=z(e.projectDir,"apps/web-next");await ht(z(t,"app/api/[[...rest]]/route.ts"),t);for(let i of Na)await ht(z(t,i),t);let n=z(t,"package.json"),r=await Qe(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],Ze(r,"@repo/api",o,!0)),await et(n,r)}import{readFile as Br}from"fs/promises";import{join as Gr}from"path";async function Kr(e){let t=Gr(e.projectDir,"turbo.json"),n;try{n=await Br(t,"utf-8")}catch{return}let r=JSON.parse(n),o=r.tasks?.build;if(!o)return;let i=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",a=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),s=!1;if(Array.isArray(o.env)){let u=o.env.filter(g=>g!==i);u.length!==o.env.length&&(o.env=u,s=!0)}if(Array.isArray(o.outputs)){let u=o.outputs.filter(g=>!a.has(g));u.length!==o.outputs.length&&(o.outputs=u,s=!0)}s&&await p(t,JSON.stringify(r,null," ")+`
1136
- `)}var ja=["base.json","node.json","next.json"],Vr="GenerateSaaS ";async function Hr(e){if(!e.demo)for(let t of ja){let n=Gr(e.projectDir,"tooling/typescript",t),r;try{r=await Br(n,"utf-8")}catch{continue}let o=JSON.parse(r);typeof o.display!="string"||!o.display.startsWith(Vr)||(o.display=o.display.slice(Vr.length),await p(n,JSON.stringify(o,null," ")+`
1137
- `))}}import{readFile as Ua,rm as Ma}from"fs/promises";import{existsSync as zr}from"fs";import{join as Jr}from"path";async function Yr(e){if(e.frontend==="nuxt")return;let t=Jr(e.projectDir,"packages/i18n/package.json");if(!zr(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await Ua(t,"utf-8")),r=!!(n.exports?.["./module"]??n.exports?.["./nuxt"]),o=!1;if(n.exports)for(let a of["./module","./nuxt"])a in n.exports&&(delete n.exports[a],o=!0);n.devDependencies&&"@nuxt/kit"in n.devDependencies&&(delete n.devDependencies["@nuxt/kit"],o=!0),o&&await p(t,JSON.stringify(n,null," ")+`
1138
- `);let i=Jr(e.projectDir,"packages/i18n/nuxt");if(r&&!zr(i))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${i} is missing - did the i18n Nuxt module move?`);await Ma(i,{recursive:!0,force:!0})}import{readFile as Wr,rm as Fa}from"fs/promises";import{join as Jt}from"path";async function Xr(e){e.cacheProvider==="upstash"&&await Promise.all([qr(Jt(e.projectDir,"packages/runtime/tests/setup.ts")),qr(Jt(e.projectDir,"packages/mail/tests/setup.ts")),Va(e.projectDir),Fa(Jt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function qr(e){let t;try{t=await Wr(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let n=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1010
+ `)}import{readFile as js}from"fs/promises";import{join as Ls}from"path";var bn=" REDIS_URL: z.string(),",Ms=` UPSTASH_REDIS_REST_URL: z.string(),
1011
+ UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Sn(e){let t=Ls(e.projectDir,"packages/runtime/src/env.ts"),r=await js(t,"utf-8");if(!r.includes(bn))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(bn,Ms):r;await c(t,n)}import{readFile as Us}from"fs/promises";import{join as L}from"path";var $t={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function Oe(e){let t=await Us(e,"utf-8");return JSON.parse(t)}async function xe(e,t){await c(e,JSON.stringify(t,null," ")+`
1012
+ `)}function Ye(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function Je(e,t,r,n=!1){let o=n?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=r}async function En(e){await Fs(e),await Vs(e),await Gs(e),await Hs(e),await Ys(e),e.frontend==="nextjs"?await Xs(e):await Ws(e)}async function Fs(e){let t=L(e.projectDir,"packages/api/package.json"),r=await Oe(t);Ye(r,["sharp","@types/sharp"]),await xe(t,r)}async function Vs(e){let t=L(e.projectDir,"packages/runtime/package.json"),r=await Oe(t);e.cacheProvider==="upstash"&&(Ye(r,["ioredis","rate-limit-redis","redis-semaphore"]),Je(r,"@upstash/redis",$t["@upstash/redis"]),Je(r,"@upstash/lock",$t["@upstash/lock"])),await xe(t,r)}var dr={none:[],sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Bs=["@sentry/electron"],Ks=[...dr.sentry,...dr.posthog];async function Gs(e){let t=L(e.projectDir,"packages/observability/package.json"),r=await Oe(t),n=new Set(dr[e.errorTracking]);if(!e.desktop)for(let o of Bs)n.delete(o);Ye(r,Ks.filter(o=>!n.has(o))),await xe(t,r)}async function Hs(e){let t=L(e.projectDir,"packages/database/package.json"),r=await Oe(t);e.databaseProvider==="neon"?(Ye(r,["pg","@types/pg"]),Je(r,"@neondatabase/serverless",$t["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ye(r,["pg","@types/pg"]),Je(r,"postgres",$t.postgres)),await xe(t,r)}async function Ys(e){if(e.architecture!=="separate")return;let t=L(e.projectDir,"apps/backend/package.json"),r=await Oe(t);e.deploymentTarget!=="node"&&Ye(r,["@hono/node-server"]),await xe(t,r)}var Js=["server/routes/.well-known/oauth-authorization-server/[...path].ts","server/routes/.well-known/oauth-protected-resource/[...path].ts","server/routes/.well-known/oauth-authorization-server.ts","server/routes/.well-known/oauth-protected-resource.ts"],zs=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Ws(e){if(e.architecture!=="separate")return;let t=L(e.projectDir,"apps/web-nuxt");await He(L(t,"server/api/[...paths].ts"),t);for(let i of Js)await He(L(t,i),t);let r=L(t,"package.json"),n=await Oe(r),o=n.dependencies?.["@repo/api"];o&&(delete n.dependencies?.["@repo/api"],Je(n,"@repo/api",o,!0)),await xe(r,n)}var qs=["instrumentation.ts","tests/instrumentation.test.ts"];async function Xs(e){if(e.architecture!=="separate")return;let t=L(e.projectDir,"apps/web-next");await He(L(t,"app/api/[[...rest]]/route.ts"),t);for(let i of zs)await He(L(t,i),t);for(let i of qs)await He(L(t,i),t);let r=L(t,"package.json"),n=await Oe(r),o=n.dependencies?.["@repo/api"];o&&(delete n.dependencies?.["@repo/api"],Je(n,"@repo/api",o,!0)),await xe(r,n)}import{readFile as Pn}from"fs/promises";import{join as In}from"path";async function Tn(e){let t=In(e.projectDir,"turbo.json"),r;try{r=await Pn(t,"utf-8")}catch{return}let n=JSON.parse(r),o=n.tasks?.build;if(!o)return;let i=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",s=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),a=!1;if(Array.isArray(o.env)){let l=o.env.filter(u=>u!==i);l.length!==o.env.length&&(o.env=l,a=!0)}if(Array.isArray(o.outputs)){let l=o.outputs.filter(u=>!s.has(u));l.length!==o.outputs.length&&(o.outputs=l,a=!0)}a&&await c(t,JSON.stringify(n,null," ")+`
1013
+ `)}var Zs=["base.json","node.json","next.json"],Rn="GenerateSaaS ";async function An(e){if(!e.demo)for(let t of Zs){let r=In(e.projectDir,"tooling/typescript",t),n;try{n=await Pn(r,"utf-8")}catch{continue}let o=JSON.parse(n);typeof o.display!="string"||!o.display.startsWith(Rn)||(o.display=o.display.slice(Rn.length),await c(r,JSON.stringify(o,null," ")+`
1014
+ `))}}import{readFile as Qs,rm as ea}from"fs/promises";import{existsSync as On}from"fs";import{join as xn}from"path";async function Dn(e){if(e.frontend==="nuxt")return;let t=xn(e.projectDir,"packages/i18n/package.json");if(!On(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let r=JSON.parse(await Qs(t,"utf-8")),n=!!(r.exports?.["./module"]??r.exports?.["./nuxt"]),o=!1;if(r.exports)for(let s of["./module","./nuxt"])s in r.exports&&(delete r.exports[s],o=!0);r.devDependencies&&"@nuxt/kit"in r.devDependencies&&(delete r.devDependencies["@nuxt/kit"],o=!0),o&&await c(t,JSON.stringify(r,null," ")+`
1015
+ `);let i=xn(e.projectDir,"packages/i18n/nuxt");if(n&&!On(i))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${i} is missing - did the i18n Nuxt module move?`);await ea(i,{recursive:!0,force:!0})}import{readFile as Nn,rm as ta}from"fs/promises";import{join as jt}from"path";async function Cn(e){e.cacheProvider==="upstash"&&await Promise.all([_n(jt(e.projectDir,"packages/runtime/tests/setup.ts")),_n(jt(e.projectDir,"packages/mail/tests/setup.ts")),ra(e.projectDir),ta(jt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function _n(e){let t;try{t=await Nn(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",
1139
1016
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1140
- `);n!==t&&await p(e,n)}async function Va(e){let t=Jt(e,"packages/api/tests/setup.ts"),n;try{n=await Wr(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let r=n;r=r.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1017
+ `);r!==t&&await c(e,r)}async function ra(e){let t=jt(e,"packages/api/tests/setup.ts"),r;try{r=await Nn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1141
1018
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1142
- `),r=r.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1019
+ `),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",
1143
1020
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1144
- `),r=r.replace(/(^vi\.mock\("@repo\/runtime")/m,`vi.mock("@upstash/redis", () => {
1021
+ `),n=n.replace(/(^vi\.mock\("@repo\/runtime")/m,`vi.mock("@upstash/redis", () => {
1145
1022
  class Redis {
1146
1023
  get = vi.fn().mockResolvedValue(null);
1147
1024
  set = vi.fn().mockResolvedValue("OK");
@@ -1158,25 +1035,26 @@ vi.mock("@upstash/lock", () => {
1158
1035
  return { Lock };
1159
1036
  });
1160
1037
 
1161
- $1`),r!==n&&await p(t,r)}import{readdir as eo,readFile as Rn,rm as G}from"fs/promises";import{join as P}from"path";import{readFile as Qr,rm as T}from"fs/promises";import{join as R}from"path";import{readFile as At}from"fs/promises";import{join as It}from"path";async function Zr(e,t){let n=It(e,"packages/api/src/routes/internal/index.ts");await p(n,Se(await At(n,"utf-8"),"internal router","companion",t)),await hr(n);let r=It(e,"packages/api/src/ai/schedule-runner.ts");await p(r,Se(await At(r,"utf-8"),"schedule-runner.ts","companion",t));for(let a of["packages/api/src/routes/internal/notifications.ts","packages/api/src/routes/internal/ai/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let s=It(e,a);await p(s,Se(await At(s,"utf-8"),a,"companion",t))}let o=It(e,"packages/api/src/ai/settings-store.ts");await p(o,Se(await At(o,"utf-8"),"settings-store.ts","companion",t));let i=It(e,"packages/api/tests/ai/settings-store.test.ts");await p(i,Se(await At(i,"utf-8"),"settings-store.test.ts","companion",t))}var Ba=["companion:export","companion:verify","companion:publish"];async function En(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await T(R(t,"packages/api/src/relay"),{recursive:!0}),await T(R(t,"packages/api/src/companion"),{recursive:!0}),await T(R(t,"packages/api/src/ai/companion-model.ts")),await T(R(t,"packages/api/tests/relay"),{recursive:!0}),await T(R(t,"packages/api/tests/companion"),{recursive:!0}),await T(R(t,"packages/api/src/routes/internal/companion.ts")),await T(R(t,"packages/api/src/routes/internal/companion-transport.ts")),await T(R(t,"packages/api/tests/routes/companion.test.ts")),await T(R(t,"packages/api/tests/routes/companion-transport-harness.ts")),await T(R(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await T(R(t,"packages/api/tests/routes/companion-transport-poll.test.ts")),await T(R(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await T(R(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await T(R(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await T(R(t,"packages/api/tests/ai/companion-model.test.ts")),await T(R(t,"packages/api/tests/ai/companion-chat.test.ts")),await T(R(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await T(R(t,"packages/api/tests/helpers/redis-mock.ts"));let r=R(t,"packages/api/package.json"),o=JSON.parse(await Qr(r,"utf-8"));if(!o.exports?.["./companion"])throw new Error(`${n}: expected packages/api/package.json to carry the ./companion export`);delete o.exports["./companion"],await Bt(r,o," ",n),await Zr(t,n);let i=Gt(e);await gr(t,i,"companion",[`/${i}/companion`,`/${i}/companion/publishing`],n,"Companions"),await B(R(t,`docs/${i}/ai.mdx`),`Runs on a paired [companion](/${i}/companion) CLI are never metered either - the user's own subscription executes them. `,"","ai.mdx companion metering sentence",n);let a=R(t,`docs/${i}/configuration.mdx`),s="| `companion.enabled` |",u=(await Qr(a,"utf-8")).split(`
1162
- `).find(g=>g.startsWith(s));if(u===void 0)throw new Error(`${n}: expected the ${i} configuration.mdx \`companion.enabled\` row (boilerplate drift).`);await B(a,`${u}
1163
- `,"","configuration.mdx companion config-table row",n)}async function An(e){if($t(e))return;let t=e.projectDir;await T(R(t,"apps/companion"),{recursive:!0}),await T(R(t,"scripts/companion-export"),{recursive:!0}),await Ga(t)}async function Ga(e){await In(e,Ba)}var Ka=new Set(["ci.yml","desktop-release.yml"]),Ha={nextjs:["apps/web-next/app/[locale]/(marketing)/download","apps/web-next/tests/routes/download-page.test.tsx"],nuxt:["apps/web-nuxt/app/pages/download.vue","apps/web-nuxt/app/middleware/desktop.ts","apps/web-nuxt/server/api/desktop-releases.get.ts","apps/web-nuxt/tests/pages/download.test.ts"]},za=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:build","playground:test:companion","ai:parity"];async function to(e){let t=P(e.projectDir,".github/workflows"),n=await eo(t).catch(()=>[]);for(let r of n)Ka.has(r)||await G(P(t,r),{recursive:!0,force:!0})}async function In(e,t){let n=P(e,"package.json"),r=JSON.parse(await Rn(n,"utf-8"));if(!r.scripts)return!1;let o=!1;for(let i of t)i in r.scripts&&(delete r.scripts[i],o=!0);return o&&await p(n,JSON.stringify(r,null," ")+`
1164
- `),o}async function no(e){let t=[...za];Dt(e)||t.push("infra","infra:stop"),await In(e.projectDir,t)}async function ro(e){let t=P(e.projectDir,"package.json"),n=await Rn(t,"utf-8"),r=JSON.parse(n);!r.scripts||!("dev"in r.scripts)||(r.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await p(t,JSON.stringify(r,null," ")+`
1165
- `))}async function oo(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await G(P(e.projectDir,t),{recursive:!0,force:!0})}async function io(e){e.docs||await G(P(e.projectDir,"apps/docs"),{recursive:!0})}async function ao(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";await G(P(e.projectDir,t),{recursive:!0,force:!0}),await G(P(e.projectDir,"docs/index.mdx")),e.desktop||await G(P(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await Ja(e)}async function Ja(e){let t=e.projectDir,n="stripUnusedDocsSilo",r=Gt(e),o=P(t,`docs/${r}/configuration.mdx`),i=e.desktop,a=e.desktop&&e.ai;e.desktop||(await B(o,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",n),await B(o,"<Callout>\n**Shipping the [desktop app](/desktop)?** It needs no entry in `TRUSTED_ORIGINS`: its main process makes every backend call - dev and packaged alike - with no `Origin` header, so the backend treats it as a native client and never CORS-checks it. `TRUSTED_ORIGINS` governs your web frontends.\n</Callout>\n\n","","configuration.mdx desktop TRUSTED_ORIGINS callout",n),await B(P(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",n)),i||await B(o,"The desktop app's AI orchestration gates on `config.desktop.agents.enabled`, which a desktop project derives from your AI option (not a separate switch). The app always ships that AI source, so flipping the flag on turns the screens back on - but the bundled companion daemon is **not** runtime-toggleable: a project generated without AI never received `apps/companion`. Leaving the flag off costs nothing (the staging step skips itself and the app packages fine); it is turning it on that requires re-running the CLI with AI on first - see [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",n),!a&&e.companion&&(await B(P(t,`docs/${r}/companion/index.mdx`),`## Set up from the desktop app
1038
+ $1`),n!==r&&await c(t,n)}import{readdir as Ln,readFile as Lt,rm as F}from"fs/promises";import{join as R}from"path";import{readFile as jn,rm as T}from"fs/promises";import{join as S}from"path";import{readFile as ft}from"fs/promises";import{join as gt}from"path";async function $n(e,t){let r=gt(e,"packages/api/src/routes/internal/index.ts");await c(r,ye(await ft(r,"utf-8"),"internal router","companion",t)),await Zr(r);let n=gt(e,"packages/api/src/ai/schedule-runner.ts");await c(n,ye(await ft(n,"utf-8"),"schedule-runner.ts","companion",t));for(let s of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let a=gt(e,s);await c(a,ye(await ft(a,"utf-8"),s,"companion",t))}let o=gt(e,"packages/api/src/ai/settings-store.ts");await c(o,ye(await ft(o,"utf-8"),"settings-store.ts","companion",t));let i=gt(e,"packages/api/tests/ai/settings-store.test.ts");await c(i,ye(await ft(i,"utf-8"),"settings-store.test.ts","companion",t))}async function ur(e){if(e.companion)return;let t=e.projectDir,r="stripCompanion";await T(S(t,"packages/api/src/relay"),{recursive:!0}),await T(S(t,"packages/api/src/companion"),{recursive:!0}),await T(S(t,"packages/api/src/ai/companion-model.ts")),await T(S(t,"packages/api/src/ai/companion-routing.ts")),await T(S(t,"packages/api/tests/relay"),{recursive:!0}),await T(S(t,"packages/api/tests/companion"),{recursive:!0}),await T(S(t,"packages/api/src/routes/internal/companion.ts")),await T(S(t,"packages/api/src/routes/internal/companion-transport.ts")),await T(S(t,"packages/api/src/routes/internal/companion-limits.ts")),await T(S(t,"packages/api/tests/routes/companion.test.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-harness.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await T(S(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await T(S(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await T(S(t,"packages/api/tests/ai/companion-model.test.ts")),await T(S(t,"packages/api/tests/unit/companion-offline-routing.test.ts")),await T(S(t,"packages/api/tests/unit/companion-offline-interactive.test.ts")),await T(S(t,"packages/api/tests/ai/companion-chat.test.ts")),await T(S(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await T(S(t,"packages/api/tests/helpers/redis-mock.ts"));let n=S(t,"packages/api/package.json"),o=JSON.parse(await jn(n,"utf-8"));if(!o.exports?.["./companion"])throw new Error(`${r}: expected packages/api/package.json to carry the ./companion export`);delete o.exports["./companion"],await Dt(n,o," ",r),await $n(t,r);let i=_t(e);await Xr(t,i,"companion",[`/${i}/companion`],r,"Companions"),await j(S(t,`docs/${i}/ai.mdx`),`Runs on a paired [companion](/${i}/companion) CLI are never metered either - the user's own subscription executes them. `,"","ai.mdx companion metering sentence",r),await j(S(t,`docs/${i}/caching.mdx`),` - see [per-companion request budgets](/${i}/companion/install#per-companion-request-budgets)`,"","caching.mdx companion budgets link",r);let s=S(t,`docs/${i}/configuration.mdx`),a="| `companion.enabled` |",l=(await jn(s,"utf-8")).split(`
1039
+ `).find(u=>u.startsWith(a));if(l===void 0)throw new Error(`${r}: expected the ${i} configuration.mdx \`companion.enabled\` row (boilerplate drift).`);await j(s,`${l}
1040
+ `,"","configuration.mdx companion config-table row",r)}var na=new Set(["ci.yml","desktop-release.yml"]),oa={nextjs:["apps/web-next/app/[locale]/(marketing)/download","apps/web-next/tests/routes/download-page.test.tsx"],nuxt:["apps/web-nuxt/app/pages/download.vue","apps/web-nuxt/app/middleware/desktop.ts","apps/web-nuxt/server/api/desktop-releases.get.ts","apps/web-nuxt/tests/pages/download.test.ts"]},ia=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:build","check-types:scripts","ai:parity","companion:export","companion:verify","companion:publish"];async function Mn(e){let t=R(e.projectDir,".github/workflows"),r=await Ln(t).catch(()=>[]);for(let n of r)na.has(n)||await F(R(t,n),{recursive:!0,force:!0})}async function sa(e,t){let r=R(e,"package.json"),n=JSON.parse(await Lt(r,"utf-8"));if(!n.scripts)return!1;let o=!1;for(let i of t)i in n.scripts&&(delete n.scripts[i],o=!0);return o&&await c(r,JSON.stringify(n,null," ")+`
1041
+ `),o}async function Un(e){await sa(e.projectDir,[...ia])}async function Fn(e){let t=R(e.projectDir,"package.json"),r=await Lt(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 c(t,JSON.stringify(n,null," ")+`
1042
+ `))}async function Vn(e){let t=R(e.projectDir,"package.json"),r=JSON.parse(await Lt(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 c(t,JSON.stringify(r,null," ")+`
1043
+ `)}async function Bn(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await F(R(e.projectDir,t),{recursive:!0,force:!0})}async function Kn(e){e.docs||await F(R(e.projectDir,"apps/docs"),{recursive:!0})}async function Gn(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";await F(R(e.projectDir,t),{recursive:!0,force:!0}),await F(R(e.projectDir,"docs/index.mdx")),e.desktop||await F(R(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await aa(e)}async function aa(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=_t(e),o=R(t,`docs/${n}/configuration.mdx`),i=e.desktop,s=e.desktop&&e.ai;e.desktop||(await j(o,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await j(o,"<Callout>\n**Shipping the [desktop app](/desktop)?** It needs no entry in `TRUSTED_ORIGINS`: its main process makes every backend call - dev and packaged alike - with no `Origin` header, so the backend treats it as a native client and never CORS-checks it. `TRUSTED_ORIGINS` governs your web frontends.\n</Callout>\n\n","","configuration.mdx desktop TRUSTED_ORIGINS callout",r),await j(R(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r)),i||await j(o,"The desktop app's AI orchestration gates on `config.desktop.agents.enabled`, which a desktop project derives from your AI option (not a separate switch). Every desktop project ships the agent runtime the app forks, so flipping the flag on turns the screens back on with no regeneration - what your AI option changes is generated content (the config values, the pricing plan's AI fields), not whether the engine is there. See [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",r),!s&&e.companion&&(await j(R(t,`docs/${n}/companion/index.mdx`),`## Set up from the desktop app
1166
1044
 
1167
1045
  If your product also ships the [desktop app](/desktop), it runs the companion for each user as a local daemon on their own machine - consent-first, with no terminal, no pairing, and no code to copy. It attaches to any daemon already serving the machine - including the user's own always-on service - and starts its own only when none is running, so one daemon serves both the app and any paired backend. It supervises that daemon while the app is open and, on quit, stops only the one it started - never the user's service. See [Companion setup](/desktop/companion).
1168
1046
 
1169
- `,"","companion index.mdx desktop-setup section",n),await B(P(t,`docs/${r}/companion/terminal.mdx`),`## In the desktop app
1047
+ `,"","companion index.mdx desktop-setup section",r),await j(R(t,`docs/${n}/companion/terminal.mdx`),`## In the desktop app
1170
1048
 
1171
1049
  If your product ships the [desktop app](/desktop), its **Terminal** side-panel tab is this same session, in an embedded terminal: the app spawns the daemon's \`terminal\` command in a real pty, and its folder picker **grants** the folder it picked (the durable, per-app grant above) before the session opens. See [Terminal and side panel](/desktop/ai/terminal).
1172
1050
 
1173
- `,"","companion terminal.mdx desktop-panel section",n))}async function so(e){if(e.desktop)return;await G(P(e.projectDir,"apps/electron"),{recursive:!0});let t=P(e.projectDir,"packages/i18n/translations");for(let o of await eo(t,{withFileTypes:!0}))o.isDirectory()&&await G(P(t,o.name,"desktop.json"),{force:!0});await G(P(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of Ha[e.frontend])await G(P(e.projectDir,o),{recursive:!0});await G(P(e.projectDir,"packages/utils/src/desktop-download.ts")),await G(P(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=P(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await Rn(n,"utf-8"));if(!r.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete r.exports["./desktop-download"],await Bt(n,r," ","stripDesktopApp")}function Ya(e){return $t(e)||e.desktop}async function co(e){Ya(e)||await G(P(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as qa}from"fs/promises";import{join as Wa}from"path";var po=`on:
1051
+ `,"","companion terminal.mdx desktop-panel section",r))}async function Hn(e){if(e.desktop)return;await F(R(e.projectDir,"apps/electron"),{recursive:!0});let t=R(e.projectDir,"packages/i18n/translations");for(let o of await Ln(t,{withFileTypes:!0}))o.isDirectory()&&await F(R(t,o.name,"desktop.json"),{force:!0});await F(R(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of oa[e.frontend])await F(R(e.projectDir,o),{recursive:!0});await F(R(e.projectDir,"packages/utils/src/desktop-download.ts")),await F(R(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=R(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await Lt(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 Dt(r,n," ","stripDesktopApp")}function ca(e){return e.desktop}async function Yn(e){ca(e)||await F(R(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as pa}from"fs/promises";import{join as la}from"path";var Jn=`on:
1174
1052
  workflow_run:
1175
1053
  workflows: ["Tag Release"]
1176
1054
  branches: [main]
1177
1055
  types: [completed]
1178
- workflow_dispatch:`,Xa=`on:
1179
- workflow_dispatch:`;async function lo(e){if(!e.desktop)return;let t=Wa(e.projectDir,".github/workflows/desktop-release.yml"),n=await qa(t,"utf8");if(!n.includes(po))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 p(t,n.replace(po,Xa))}import{join as Za}from"path";async function uo(e){let t=Qa(e);await p(Za(e.projectDir,".github/workflows/ci.yml"),t)}function Qa(e){let t=K[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",o=t?"":` services:
1056
+ workflow_dispatch:`,da=`on:
1057
+ workflow_dispatch:`;async function zn(e){if(!e.desktop)return;let t=la(e.projectDir,".github/workflows/desktop-release.yml"),r=await pa(t,"utf8");if(!r.includes(Jn))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 c(t,r.replace(Jn,da))}import{join as ua}from"path";async function Wn(e){let t=ma(e);await c(ua(e.projectDir,".github/workflows/ci.yml"),t)}function ma(e){let t=re[e.databaseProvider].managed,r=e.cacheProvider==="upstash",n=e.frontend==="nuxt",o=t?"":` services:
1180
1058
  postgres:
1181
1059
  image: postgres:18-alpine
1182
1060
  env:
@@ -1190,13 +1068,13 @@ If your product ships the [desktop app](/desktop), its **Terminal** side-panel t
1190
1068
  --health-interval 10s
1191
1069
  --health-timeout 5s
1192
1070
  --health-retries 5
1193
- `,i=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",a=n?`
1071
+ `,i=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",s=r?`
1194
1072
  UPSTASH_REDIS_REST_URL: https://test.upstash.io
1195
- UPSTASH_REDIS_REST_TOKEN: test-token`:"",s=(()=>{switch(e.paymentProvider){case"stripe":return`
1073
+ UPSTASH_REDIS_REST_TOKEN: test-token`:"",a=(()=>{switch(e.paymentProvider){case"stripe":return`
1196
1074
  STRIPE_SECRET_KEY: test
1197
1075
  STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
1198
1076
  POLAR_ACCESS_TOKEN: test
1199
- POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let l=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(l)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
1077
+ POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let y=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(y)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
1200
1078
  # which auto-deploys on push. CI runs in parallel as a quality gate.
1201
1079
  # For PR-based workflows, enable GitHub branch protection to require CI before merging.
1202
1080
 
@@ -1221,7 +1099,7 @@ jobs:
1221
1099
  runs-on: ubuntu-latest
1222
1100
  timeout-minutes: 20
1223
1101
  ${o} env:
1224
- CONTENT_API_KEY: test-contentapi-key-16chars${a}${s}
1102
+ CONTENT_API_KEY: test-contentapi-key-16chars${s}${a}
1225
1103
  STORAGE_REGION: test
1226
1104
  STORAGE_ENDPOINT: http://test
1227
1105
  STORAGE_ACCESS_KEY_ID: test
@@ -1234,7 +1112,7 @@ ${o} env:
1234
1112
 
1235
1113
  - run: pnpm lint
1236
1114
 
1237
- ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
1115
+ ${n?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
1238
1116
  # the type graph (Nuxt + Pinia + vue-i18n + content collections)
1239
1117
  # crosses a threshold. Bump to 6 GB; ubuntu-latest has ~7 GB RAM.
1240
1118
  - run: pnpm check-types
@@ -1245,50 +1123,153 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
1245
1123
  run: echo "DATABASE_URL=${i}" > .env
1246
1124
 
1247
1125
  - run: pnpm test
1248
- `}import{readFile as mo}from"fs/promises";import{existsSync as es}from"fs";import{join as Pn}from"path";var fo="@repo/database";function ts(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function ns(e,t){switch(e){case"fullstack":return t==="nextjs"?"web-next":"web-nuxt";case"separate":return"backend";default:{let n=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(n)}"`)}}}async function rs(e,t,n){let r=await mo(e,"utf-8"),o=JSON.parse(r),i=o.scripts?.[t];if(!i)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);i.includes(fo)||(o.scripts={...o.scripts,[t]:`${n} && ${i}`},await p(e,JSON.stringify(o,null," ")+`
1249
- `))}async function os(e,t){let n=es(e)?JSON.parse(await mo(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},r=n.buildCommand?.trim()||"pnpm build";r.includes(fo)||(n.buildCommand=`${t} && ${r}`,await p(e,JSON.stringify(n,null," ")+`
1250
- `))}async function go(e){let t=ts(e.demo===!0),n=ns(e.architecture,e.frontend),r=Pn(e.projectDir,"apps",n);switch(e.deploymentTarget){case"node":await rs(Pn(r,"package.json"),"start",t);return;case"vercel":await os(Pn(r,"vercel.json"),t);return;default:{let o=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(o)}"`)}}}import{readFile as is}from"fs/promises";import{existsSync as as}from"fs";import{join as Yt}from"path";var ss=["stripe","polar"];async function ho(e){let t=Yt(e.projectDir,"packages/payments/src"),n=e.paymentProvider,r=`// Active payment provider. To switch, change the path below to
1126
+ `}import{readFile as qn}from"fs/promises";import{existsSync as fa}from"fs";import{join as mr}from"path";var Xn="@repo/database";function ga(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function ha(e,t){switch(e){case"fullstack":return t==="nextjs"?"web-next":"web-nuxt";case"separate":return"backend";default:{let r=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(r)}"`)}}}async function ya(e,t,r){let n=await qn(e,"utf-8"),o=JSON.parse(n),i=o.scripts?.[t];if(!i)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);i.includes(Xn)||(o.scripts={...o.scripts,[t]:`${r} && ${i}`},await c(e,JSON.stringify(o,null," ")+`
1127
+ `))}async function wa(e,t){let r=fa(e)?JSON.parse(await qn(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(Xn)||(r.buildCommand=`${t} && ${n}`,await c(e,JSON.stringify(r,null," ")+`
1128
+ `))}async function Zn(e){let t=ga(e.demo===!0),r=ha(e.architecture,e.frontend),n=mr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await ya(mr(n,"package.json"),"start",t);return;case"vercel":await wa(mr(n,"vercel.json"),t);return;default:{let o=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(o)}"`)}}}import{readFile as va}from"fs/promises";import{existsSync as ka}from"fs";import{join as Mt}from"path";var ba=["stripe","polar"];async function Qn(e){let t=Mt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,n=`// Active payment provider. To switch, change the path below to
1251
1129
  // "./polar/index" or "./none/index" (other folders are kept in place).
1252
- export { ops } from "./${n}/index";
1253
- `;await p(Yt(t,"providers/index.ts"),r),await p(Yt(t,"index.ts"),await cs(t,n))}async function cs(e,t){let n=Yt(e,"index.ts");if(!as(n))throw new Error(`generatePaymentBarrel: expected ${n} to exist - did packages/payments move?`);let r=await is(n,"utf-8"),o=ss.filter(a=>a!==t);return r.split(`
1254
- `).filter(a=>!o.some(s=>a.includes(`./providers/${s}/`))).join(`
1255
- `)}import{readdir as ps,readFile as ls}from"fs/promises";import{join as yo}from"path";async function wo(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,n=JSON.stringify(t).slice(1,-1),r=yo(e.projectDir,"packages/i18n/translations"),o;try{o=await ps(r)}catch{return}for(let i of o){let a=yo(r,i,"web.json"),s;try{s=await ls(a,"utf-8")}catch{continue}let u=s.replaceAll("GenerateSaaS",n);u!==s&&await p(a,u)}}import{readFile as ds}from"fs/promises";import{join as vo}from"path";var us=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],ms=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function bo(e){let n=e.frontend==="nuxt"?ms:us;await ko(vo(e.projectDir,".gitignore"),n),await ko(vo(e.projectDir,".dockerignore"),n)}async function ko(e,t){let n;try{n=await ds(e,"utf-8")}catch{return}let r=new Set(t),o=n.split(`
1256
- `).filter(i=>!r.has(i.trim()));o.length!==n.split(`
1257
- `).length&&await p(e,o.join(`
1258
- `))}async function qt(e){let t=e.projectDir;e.demo||(await wr(t),await kr(t),await br(t),await Sr(t),e.desktop&&await vr(t)),await Er(t,e.aiTools),await Ar(t,e.frontend),await Rr(e),await Pr(e),await _r(e),await Tr(e),e.demo||await xr(e),await Cr(e);let n=await Nr(e);return await $r(e),await Lr(e),await jr(e),await Ur(e),await Mr(e),await Fr(e),await Kr(e),await Hr(e),await Yr(e),await Xr(e),await to(e),await uo(e),await no(e),await ro(e),await oo(e),await io(e),await ao(e),await so(e),await co(e),await lo(e),await En(e),await An(e),await go(e),await ho(e),await wo(e),await bo(e),{dockerComposeGenerated:n}}import{basename as Eo,join as Ao,relative as gs}from"path";import{createHash as So}from"crypto";import{readFile as fs}from"fs/promises";async function Wt(e){let t=await fs(e);return So("sha256").update(t).digest("hex")}function Tn(e){return So("sha256").update(e).digest("hex")}var hs=new Set(["data",V]);function ys(e){let t=e.split("/");for(let n of t)if(un.has(n)||mn.has(n)||hs.has(n)||n.startsWith(".env")&&!n.includes("example"))return!0;return!1}function Io(e,t){return{projectName:e.projectName??Eo(t),appName:e.appName??e.projectName??Eo(t),projectDir:t,frontend:e.frontend==="nextjs"?"nextjs":"nuxt",architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,companion:e.companion??!1,companionSource:H(e),companionRepoUrl:e.companionRepoUrl??Te,companionName:e.companionName??W(e.projectName),revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,dockerServices:e.dockerServices??[],aiTools:e.aiTools??[],defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function ws(e,t){return{version:e.version,initialVersion:e.version,repo:"Duzbee/GenerateSaaS",appName:e.appName,projectName:e.projectName,frontend:e.frontend,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,ai:e.ai,companion:e.companion,...e.companionName?{companionName:e.companionName}:{},...e.companionSource?{companionSource:e.companionSource}:{},...e.companionRepoUrl?{companionRepoUrl:e.companionRepoUrl}:{},credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,dockerServices:e.dockerServices,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,aiTools:e.aiTools,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Ro(e,t){let r=(await De(e.projectDir,e.projectDir,ys)).sort(),o=await Promise.all(r.map(async s=>[Oe(gs(e.projectDir,s)),await Wt(s)])),i=Object.fromEntries(o),a=ws(e,t);await p(Ao(e.projectDir,we),JSON.stringify(a,null," ")+`
1259
- `),await p(Ao(e.projectDir,sr),JSON.stringify(i,null," ")+`
1260
- `)}import{relative as vs}from"path";async function Ne(e){let n=(await De(e,e,Xe)).sort(),r=await Promise.all(n.map(async o=>[Oe(vs(e,o)),await Wt(o)]));return Object.fromEntries(r)}import{copyFile as ks,mkdir as bs,rm as Ss}from"fs/promises";import{dirname as Es,join as Po,relative as As}from"path";import{existsSync as Is}from"fs";async function _n(e,t){Is(t)&&await Ss(t,{recursive:!0,force:!0});let n=await De(e,e,Xe);for(let r of n){let o=Oe(As(e,r)),i=Po(t,o);await bs(Es(i),{recursive:!0}),await ks(r,i)}}async function To(e,t){await _n(e,Po(t,jt))}import{existsSync as Rs}from"fs";import{readFile as _o,readdir as Ps}from"fs/promises";import{join as ie,dirname as Ts,resolve as _s,sep as xs}from"path";import{fileURLToPath as Os}from"url";var Rt={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Vu=Object.values(Rt),xn="generatesaas-update",xo=Ts(Os(import.meta.url));function Ds(){let e=ie(xo,"skill","content");return Rs(e)?e:ie(xo,"content")}function On(e){return!e||e.length===0?[]:e.map(t=>Rt[t])}async function Dn(e,t,n,r){let o=On(r);for(let i of o){let a=ie(e,i,xn),s=ie(a,"scripts"),u=ie(a,"references");await Vt(s),await Vt(u),await p(ie(a,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",i)),await p(ie(u,".gitkeep"),"");for(let[g,l]of Object.entries(n)){let h=_s(s,g);h.startsWith(s+xs)&&await p(h,l)}}}async function Oo(e,t){let n=Ds(),r=await _o(ie(n,"SKILL.md"),"utf-8"),o=ie(n,"scripts"),i=await Ps(o),a={};for(let s of i)s!==".gitkeep"&&(a[s]=await _o(ie(o,s),"utf-8"));await Dn(e,r,a,t)}import{execFile as Cs,execFileSync as Ns}from"child_process";import{access as Do,readFile as $s}from"fs/promises";import{join as Cn}from"path";import*as D from"@clack/prompts";function Le(e){try{let t=process.platform==="win32"?"where":"which";return Ns(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function $e(e,t,n,r=3e5){return new Promise((o,i)=>{Cs(e,t,{cwd:n,timeout:r,maxBuffer:50*1024*1024},(a,s,u)=>{if(a){let g=String(s||"").trim(),h=[String(u||"").trim(),g].filter(Boolean).join(`
1261
- `);i(new Error(h?`${a.message}
1262
- ${h}`:a.message))}else o()})})}async function Co(e){if(!Le("pnpm"))return D.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await $e("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let n=t instanceof Error?t.message:String(t);return D.log.warn(`Lockfile regeneration failed: ${n}`),D.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function No(e){if(!Le("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 $e("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(n){t.stop("Dependency installation failed.");let r=n instanceof Error?n.message:String(n);return D.log.warn(`pnpm install failed: ${r}`),D.log.warn("You can run it manually later."),!1}}async function $o(e){if(!Le("pnpm"))return!1;let t=D.spinner();t.start("Generating baseline database migration...");try{return await $e("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(n){t.stop("Baseline migration generation failed.");let r=n instanceof Error?n.message:String(n);return D.log.warn(`Could not generate baseline migration: ${r}`),D.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Lo(e){try{return await Do(Cn(e,".git")),D.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Le("git"))return D.log.warn("git not found. Skipping repository initialization."),!1;let t=D.spinner();t.start("Initializing git repository...");try{return await $e("git",["init"],e),await $e("git",["add","-A"],e),await $e("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 jo(e){if(!Le("pnpm"))return!1;try{await Do(Cn(e,".git"))}catch{return!1}try{let t=JSON.parse(await $s(Cn(e,"package.json"),"utf-8")),n=!!t.devDependencies?.["simple-git-hooks"],r=!!t["simple-git-hooks"];if(!n||!r)return!1}catch{return!1}try{return await $e("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 tt from"@clack/prompts";import X from"picocolors";function Uo(e,t){t.dockerComposeGenerated&&!t.dockerAvailable&&tt.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];if(n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),t.dockerComposeGenerated){let i=e.dockerServices.map(a=>Be[a].label).join(", ");n.push(`pnpm infra ${X.dim(`# ${i}`)}`)}if(n.push(`pnpm dev ${X.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(X.dim("Fill in remaining TODO values in .env"))),tt.note(n.join(`
1263
- `),X.yellow("Start Development")),t.dockerComposeGenerated){let i=[];i.push(`App ${X.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${X.cyan("http://localhost:3010")}`),e.dockerServices.includes("mailpit")&&i.push(`Mailpit ${X.cyan("http://localhost:8025")}`),e.dockerServices.includes("inngest")&&i.push(`Inngest ${X.cyan("http://localhost:8288")}`),tt.note(i.join(`
1264
- `),X.yellow("Dev Tools"))}let r=[],o=Ls(e);o.length>0&&r.push(`Set in production: ${X.dim(o.join(", "))}`),r.push("pnpm db:setup # Apply the database schema"),r.push(js(e)),tt.note(r.join(`
1265
- `),X.yellow("Deployment"))}function Ls(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET"];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 js(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 nt(e){let n=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function je(e,t){let n=nt(e),r=nt(t);if(!n||!r)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function Xt(e,t){return e.versions.find(n=>n.version===t)?.cli}function Mo(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:nt(e)===null}function Zt(e,t,n="2.2.0"){if(Mo(n))return{ok:!0};let r=Xt(e,e.latest);return!r||nt(r)===null?{ok:!0}:je(n,r)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${n}) is too old for template v${e.latest}, which needs CLI v${r} 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 Fo(e,t,n="2.2.0"){if(Mo(n))return{ok:!0};let r=Xt(e,t);return!r||nt(r)===null?{ok:!0}:je(n,r)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${r} exactly (the CLI whose generators produced that release). Run npx generatesaas@${r} init.`}}import Gs from"picocolors";var Ks="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Hs(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),n=[...new Uint8Array(t).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}function Vo(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 Z("--frontend <type>","frontend framework").choices([...Re])).addOption(new Z("--architecture <type>","fullstack or separate").choices([...Ge])).addOption(new Z("--payment <provider>","payment provider").choices([...Ke])).addOption(new Z("--email <provider>","email provider").choices([...He])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").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, schedules, integrations); unlocks the companion").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - a daemon your users install to run their own AI subscriptions for this app (shared repo or vendored)").option("--no-companion","exclude the backend companion feature").addOption(new Z("--companion-source <source>","companion source: point at an existing shared companion repo, or vendor your own branded daemon").choices([...Pe])).option("--companion-repo-url <url>","GitHub URL of the shared companion repo (with --companion-source shared; default: OpenCompanion)").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)").option("--docker <services>","comma-separated: postgres,redis,inngest,mailpit").option("--ai-tools <tools>","comma-separated: claude-code,cursor,codex,gemini-cli,windsurf").addOption(new Z("--currency <code>","default currency for billing").choices([...se])).addOption(new Z("--deploy <target>","deployment target").choices([...ce])).addOption(new Z("--database <provider>","database provider").choices([...pe])).addOption(new Z("--cache <provider>","cache provider").choices([...le])).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 Z("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new Z("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await zs(t?{...n,apiKey:t}:n)})}async function zs(e){let t=performance.now();Gn("2.2.0");let n;try{n=or(e)}catch(y){k.cancel(I(y)),process.exit(1)}let r=k.spinner(),o;try{o=await We({apiKey:e.apiKey,prompt:!e.yes})}catch(y){k.cancel(I(y)),process.exit(1)}e.demo&&Tn(o)!==Ks&&(k.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=fe(o),a,s=async()=>{a=await be(i);let y=Zt(a,"init");if(!y.ok)throw new Error(y.message);return{latestVersion:a.latest,selectedVersion:a.latest,desktopAllowed:a.entitlements?.desktopAllowed??!0,companionAllowed:a.entitlements?.companionAllowed??!0}};r.start("Verifying access...");let u,g,l=!0,h=!0;try{({latestVersion:u,selectedVersion:g,desktopAllowed:l,companionAllowed:h}=await s()),r.stop("Access verified."),xe(o)}catch(y){if(r.stop("Access verification failed."),y instanceof $&&y.status===401){e.yes&&(k.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),k.log.warning("Invalid API key."),o=await gt(),i=fe(o),r.start("Verifying access...");try{({latestVersion:u,selectedVersion:g,desktopAllowed:l,companionAllowed:h}=await s()),r.stop("Access verified."),xe(o)}catch(O){r.stop("Access verification failed."),k.cancel(O instanceof $&&O.status===401?"Invalid API key.":I(O)),process.exit(1)}}else k.cancel(I(y)),process.exit(1)}k.log.success(`Latest version: ${u}`),n.desktop===!0&&!l&&(k.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),n.companion===!0&&!h&&(k.cancel("The companion is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let S;e.yes?S=ir({...n,...l?{}:{desktop:!1},...h?{}:{companion:!1}}):S=await ar(n,{desktopAllowed:l,companionAllowed:h});let C;r.start("Activating license...");try{let y=e.demo&&S.baseUrl?await Hs(S.baseUrl):crypto.randomUUID(),O=()=>({frontend:S.frontend,version:g,installId:y,projectName:S.projectName,options:dr(S)}),j;try{j=await ln(i,O())}catch(Y){let w=Ut(Y);if(!w?.lastAllowedVersion||!a)throw Y;r.stop("License activation failed.");let M=Fo(a,w.lastAllowedVersion);if(M.ok||(k.cancel(`${w.message} ${M.message}`),process.exit(1)),e.yes){let ot=Xt(a,w.lastAllowedVersion);k.cancel(`${w.message} Re-run ${ot?`npx generatesaas@${ot} init`:"init"} without --yes to continue with v${w.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let Ae=await k.confirm({message:`Your update window has ended. Continue with v${w.lastAllowedVersion} (the last version your license covers)?`});(k.isCancel(Ae)||!Ae)&&(k.cancel("Setup cancelled."),process.exit(0)),g=w.lastAllowedVersion,r.start(`Activating license for v${g}...`),j=await ln(i,O())}C={token:j.token,keyHash:Tn(o),installId:j.installId??y},r.stop("License activated.")}catch(y){r.stop("License activation failed."),k.cancel(I(y)),process.exit(1)}let E=Bs(S.projectDir);if(Us(E)&&Ms(E).length>0)if(e.yes)k.log.info(`Directory ${E} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let O=await k.select({message:`Directory ${E} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(k.isCancel(O)||O==="cancel")&&(k.cancel("Setup cancelled."),process.exit(0)),O==="overwrite"&&Fs(E,{recursive:!0,force:!0})}let N={...S,projectDir:E,version:g,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await Mt(i,g,E),r.stop("Template downloaded.")}catch(y){r.stop("Download failed."),k.cancel(I(y)),process.exit(1)}let te;r.start("Generating project files...");try{if({dockerComposeGenerated:te}=await qt(N),!e.demo){let y=await Ne(E);await p(Vs(E,Lt),JSON.stringify(y,null," ")+`
1266
- `),await To(E,E)}await Oo(E,N.aiTools),await Ro(N,C),r.stop("Project files generated.")}catch(y){r.stop("Generation failed."),k.cancel(I(y)),process.exit(1)}!await Co(E)&&N.demo===!0&&(k.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let ae=await No(E);ae&&N.demo!==!0&&e.dbMigration!==!1&&await $o(E),await Lo(E),ae&&await jo(E);let Ee=Le("docker"),he=cn(N).map(y=>y.key).filter(y=>!N.credentials?.[y]);Uo(N,{pnpmInstalled:ae,dockerComposeGenerated:te,dockerAvailable:Ee,skippedCredentials:he}),Kn(),k.log.info(Gs.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Ln}from"fs";import{readFile as jn}from"fs/promises";import{join as rt,resolve as tc}from"path";import*as v from"@clack/prompts";import L from"picocolors";import{mkdtemp as Js,rm as Ys}from"fs/promises";import{tmpdir as qs}from"os";import{join as Ws}from"path";async function Nn(e,t,n,r){let o=await Js(Ws(qs(),"generatesaas-stage-"));try{await Mt(e,t,o),await qt({...n,projectDir:o}),await _n(o,r)}finally{await Ys(o,{recursive:!0,force:!0})}}function Bo(e){return e?"ON":"OFF"}var Pt="packages/config/src/index.ts",Xs=[{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, but it is now a plain config value generated as `user`. Applying this update as-is bills the individual member instead of the organization: new checkouts create member-scoped subscriptions and org-level entitlements stop resolving. Put it back with `billingScope: "organization"` in `packages/config/src/tenancy-flags.mjs`. 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 ${Pt} 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 ${Pt} 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 ${Pt}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===ut(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Bo(e.aiBuiltin)}, but it is now a plain config value generated ${Bo(ut(e))} for a project ${ut(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${Pt} 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 ${Pt} to keep it off.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local companion checkout at ${e.companionLocalPath}. The option is gone; point the \`GENERATESAAS_COMPANION_BRAND_JSON\` env var at that checkout's \`brand.json\` instead.`}];function Go(e){let t=[];for(let n of Xs){if(n.normalize?.(e),e[n.key]===void 0)continue;(!n.applies||n.applies(e))&&!n.preserved(e)&&t.push({key:n.key,message:n.describe(e),severity:n.severity}),delete e[n.key]}return t}import{readFile as Zs,rm as Qs}from"fs/promises";import{join as $n}from"path";var Ko=$n(V,"companion-release.json"),ec=["apps/companion/","packages/companion-protocol/","packages/agent-core-types/","packages/agent-core/","scripts/companion-export/"];async function Ho(e){let t;try{t=await Zs($n(e,Ko),"utf-8")}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&r.code==="ENOENT")return null;throw r}let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"version"in n&&typeof n.version=="string"&&n.version.length>0?{version:n.version}:null}async function zo(e){try{return await Qs($n(e,Ko)),!0}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function Jo(e){return e.some(t=>ec.some(n=>t.startsWith(n)))}function qo(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,n)=>{let r=t==="auto"?"auto":void 0,o=tc(n.cwd??process.cwd()),i=rt(o,we),a;try{a=JSON.parse(await jn(i,"utf-8"))}catch{v.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s;try{s=await We()}catch(l){v.cancel(I(l)),process.exit(1)}let u=fe(s),g=v.spinner();try{g.start("Verifying access...");let l;try{l=await be(u)}catch(w){throw w instanceof $&&w.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):w}let h=Zt(l,"update");if(!h.ok)throw new Error(h.message);g.stop("Access verified."),xe(s),g.start("Fetching latest skill files...");let S=await lr(u,l.latest);await Dn(o,S.skillMd,S.scripts,a.aiTools);let C=On(a.aiTools);if(g.stop("Skills updated."),v.log.success(`Skill files installed to ${L.cyan(C.length.toString())} locations.`),a.version===l.latest){v.log.info(`Already on the latest version (${a.version}).`);return}let E=JSON.stringify(a);nr(a),await nc(a,rr(a),r),await oc(Go(a),r);let N=Yn(a),te=qn(a),Fe=JSON.stringify(te)!==E;if(a=te,a.licenseToken)try{let w=await ur(u,{currentToken:a.licenseToken,newVersion:l.latest});a.licenseToken=w.token,w.licenseKeyHash&&(a.licenseKeyHash=w.licenseKeyHash),await p(i,JSON.stringify(a,null," ")+`
1267
- `),Fe=!1,v.log.success("License refreshed.")}catch(w){let M=Ut(w);M&&(v.cancel(M.message),process.exit(1)),v.log.warn("License refresh skipped.")}Fe&&await p(i,JSON.stringify(a,null," ")+`
1268
- `);let ae=Io(a,o),Ee=rt(o,cr);g.start(`Staging v${l.latest} (shaped for your config)...`),await Nn(u,l.latest,ae,Ee),g.stop("Template staged.");let{text:Ve,title:he}=await ac(u,l,a.version);Ve&&v.note(Ve,he);let y=rt(o,Lt),O=rt(o,jt),j=!Ln(O),Y=!Ln(y);if(j){if(g.start("Building baseline template (one-time migration)..."),await Nn(u,a.version,ae,O),Y){let w=await Ne(O);await p(y,JSON.stringify(w,null," ")+`
1269
- `)}if(g.stop("Baseline template stored."),!Y){let w=await cc(y,O);w>0&&v.log.warn(`Rebuilt baseline differs from the original for ${w} 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(Y){g.start("Computing baseline template hashes...");let w=await Ne(O);await p(y,JSON.stringify(w,null," ")+`
1270
- `),g.stop("Baseline hashes computed.")}if(await p(rt(o,pr),JSON.stringify({currentVersion:a.version,targetVersion:l.latest,changelog:Ve,stagedAt:new Date().toISOString(),...N.length>0?{newOptions:N}:{},...r?{mode:r}:{}},null," ")+`
1271
- `),v.log.info(`Update staged: ${L.cyan(a.version)} \u2192 ${L.cyan(l.latest)}`),a.aiTools&&a.aiTools.length>0){let w=a.aiTools[0],M=pt[w].label;v.log.info(`Open your project in ${L.cyan(M)} and ask: ${L.cyan("'update my GenerateSaaS project'")}`)}else v.log.info(`Ask your AI coding assistant to ${L.cyan("'update my GenerateSaaS project'")}.`);if(a.companion===!0)try{if(de(a)==="vendored"){let w=await Ho(o);if(w){let M=await sc(y,Ee);Jo(M)&&v.log.warn(`Companion: vendored daemon changed since your published v${w.version} - run pnpm companion:publish (your users auto-update once tagged)`)}}else await zo(o)&&v.log.info("Companion: removed the stale vendored publish state (.generatesaas/companion-release.json) - this project points at a shared companion.")}catch(w){v.log.warn(`Companion re-release check skipped: ${I(w)}`)}a.desktop===!0&&Ln(rt(o,"apps/tauri"))&&v.log.warn(`Desktop: the app moved to an Electron shell (${L.cyan("apps/electron")}). Your project still has the old Tauri shell (${L.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${L.cyan("/desktop/updates")}.`)}catch(l){g.stop("Failed."),v.cancel(`Update failed: ${I(l)}`),process.exit(1)}})}async function nc(e,t,n){if(t.kind==="none")return;if(t.kind==="daemon-materialized"){v.log.info(`Desktop: your app now bundles its own companion daemon. This update adds its source to your repo (${L.cyan("apps/companion")}, branded ${L.cyan(e.companionName??"")}) and about 106MB to each packaged build. Nothing to publish - it ships inside the app.`);return}let r=ic[t.kind];n==="auto"&&(v.cancel(`${r.message}
1272
-
1273
- This is a decision only you can make, so an unattended update will not guess it. Run ${L.cyan("generatesaas update")} without ${L.cyan("auto")} and answer it.`),process.exit(1));let o=await v.select({message:r.message,options:r.options});v.isCancel(o)&&(v.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e),sn(e)}var rc={billingScope:[{value:"stage",label:"Stage it - I will put the scope back myself",hint:'set `billingScope: "organization"` in packages/config/src/tenancy-flags.mjs before taking new checkouts'},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/tenancy-flags.mjs first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}],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 oc(e,t){let n=[];for(let r of e){let o=r.severity==="ask"?rc[r.key]:void 0;if(!o){v.log.warn(r.message);continue}n.push({notice:r,answers:o})}for(let{notice:r,answers:o}of n){t==="auto"&&(v.cancel(`${r.message}
1274
-
1275
- This is a decision only you can make, so an unattended update will not guess it. Run ${L.cyan("generatesaas update")} without ${L.cyan("auto")} and answer it.`),process.exit(1));let i=await v.select({message:r.message,options:o});(v.isCancel(i)||i==="stop")&&(v.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function Yo(e){e.desktop=!1}var ic={"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 adds the companion daemon's source to your repo (apps/companion, ~106MB per packaged build) and 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, no bundled daemon"}]},"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 and bundles a companion daemon. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack, the Terminal, and the bundled companion daemon (apps/companion, ~106MB per packaged build)"},{value:{apply:e=>{e.ai=!1,e.companion=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion - it requires AI"},{value:{apply:Yo},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]},"shared-source-contradiction":{message:"Your desktop app bundles a companion daemon, but your project points its web install flow at a shared companion. A bundled app needs its own daemon. How should this resolve?",options:[{value:{apply:e=>{e.companionSource="vendored"}},label:"Vendor your own companion",hint:"its source moves into your repo (apps/companion) and your web install UI switches to it - your users install yours, not the shared one"},{value:{apply:Yo},label:"Drop the desktop app",hint:"your website keeps its AI surface and its shared companion exactly as they are today"}]}};async function ac(e,t,n){let r=t.latest,o=t.versions.filter(a=>je(a.version,n)>0&&je(a.version,r)<=0).sort((a,s)=>je(a.version,s.version));if(o.length<=1)return{text:await pn(e,r),title:`Changelog v${r}`};let i=[];for(let a of o){let s=null;try{s=await pn(e,a.version)}catch{s=null}let u=a.date?` (${a.date.slice(0,10)})`:"",g=a.breaking?" [BREAKING]":"";i.push(`# v${a.version}${u}${g}
1276
-
1277
- ${s??"_No changelog available for this release._"}`)}return{text:i.join(`
1278
-
1279
- `),title:`Changelog v${n} \u2192 v${r}`}}async function sc(e,t){let n=JSON.parse(await jn(e,"utf-8")),r=await Ne(t),o=[];for(let[i,a]of Object.entries(r))n[i]!==a&&o.push(i);for(let i of Object.keys(n))i in r||o.push(i);return o}async function cc(e,t){let n=JSON.parse(await jn(e,"utf-8")),r=await Ne(t),o=0;for(let[i,a]of Object.entries(n))Xe(i)||r[i]!==a&&o++;for(let i of Object.keys(r))i in n||o++;return o}import*as J from"@clack/prompts";import Q from"picocolors";import{readFile as pc}from"fs/promises";import{join as lc,resolve as dc}from"path";function Wo(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let n=dc(t.cwd??process.cwd()),r=lc(n,we),o;try{o=JSON.parse(await pc(r,"utf-8"))}catch{J.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let i=[`Version: ${Q.cyan(o.version)}`,`Frontend: ${Q.cyan(o.frontend)}`,o.deploymentTarget?`Deploy target: ${Q.cyan(o.deploymentTarget)}`:null,o.databaseProvider?`Database: ${Q.cyan(o.databaseProvider)}`:null,o.cacheProvider?`Cache: ${Q.cyan(o.cacheProvider)}`:null,o.aiTools&&o.aiTools.length>0?`AI tools: ${Q.cyan(o.aiTools.join(", "))}`:null].filter(Boolean).join(`
1280
- `);J.note(i,Q.bold("Project Status"));let a=J.spinner();a.start("Checking for updates...");try{let s=await We(),u=fe(s),l=(await be(u)).latest;o.version===l?(a.stop("Up to date."),J.log.success(`Already on the latest version (${Q.green(l)})`)):(a.stop("Update available."),J.log.warning(`Update available: ${Q.yellow(o.version)} \u2192 ${Q.green(l)}`),J.log.info(`Open this project in your AI coding agent and ask it to ${Q.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(s){a.stop("Check failed."),s instanceof $&&s.status===401?J.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):J.log.warning(`Could not check for updates: ${I(s)}`)}})}import{readFile as uc}from"fs/promises";import*as x from"@clack/prompts";import _ from"picocolors";function mc(){return process.env.GENERATESAAS_API_KEY??ft()}function fc(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 gc(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function hc(e){switch(e.verdict){case"licensed":return x.log.success(`${_.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return x.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 x.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 x.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 x.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 x.log.warn(`${_.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Xo(e,t){let n=process.env.GENERATESAAS_API_URL??mt,r=mc();e.start("Cross-referencing license records...");try{let o=r?fc(await mr(n,r,{lkh:t.lkh,nid:t.nid,domain:t.domain})):gc(await dn(n,{token:t.token,domain:t.domain}));return e.stop(`${_.green("Checked")} - records cross-referenced`),hc(o)}catch(o){return e.stop(`${_.yellow("Skipped")} - ${I(o)}`),null}}function yc(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let n=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(n)}function Un(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Zo(e){x.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: ${Un(e.pat)}`,`Last updated: ${Un(e.uat)}`,`Expires: ${Un(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1281
- `),_.yellow("License Details"))}function wc(e){let n=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(n.endsWith("/api"))return[`${n}/license`];try{if(new URL(n).pathname!=="/")return[`${n}/license`]}catch{return[`${n}/license`]}return[`${n}/api/license`,`${n}/license`]}async function Qo(e){let t=x.spinner(),n=null,r="no candidates";for(let a of wc(e)){t.start(`Checking ${a}...`);try{let s=await fetch(a);if(!s.ok){r=`${a} returned ${s.status}`,t.stop(`${_.yellow("Not here")} - ${r}`);continue}let u=(await s.text()).trim();if(!u||u.split(".").length!==3){r=`${a} did not return a JWT`,t.stop(`${_.yellow("Not here")} - ${r}`);continue}n=u,t.stop(`${_.green("Found")} - license endpoint responded`);break}catch(s){r=`${a}: ${I(s)}`,t.stop(`${_.yellow("Unreachable")} - ${r}`)}}if(n===null){x.log.warn(`No license endpoint found (last: ${r}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let a=ei(e);return a?await Xo(t,{domain:a})??!1:!1}let o;try{o=yc(n)}catch{return x.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let a=process.env.GENERATESAAS_API_URL??mt,s=await dn(a,{token:n});if(s.valid)t.stop(`${_.green("Valid")} - signature verified`);else return t.stop(`${_.red("Invalid")} - ${s.reason}`),!1}catch{return t.stop(`${_.yellow("Skipped")} - could not reach verification service`),x.log.warn("Signature not verified. Displaying unverified claims:"),Zo(o),!1}return Zo(o),await Xo(t,{token:n,lkh:typeof o.lkh=="string"?o.lkh:void 0,nid:typeof o.nid=="string"?o.nid:void 0,domain:ei(e)})??!0}function ei(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ti(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,n)=>{if(!t&&!n.file&&(x.cancel("Provide a URL or --file <path>."),process.exit(1)),n.file){let o=(await uc(n.file,"utf-8")).split(`
1282
- `).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));o.length===0&&(x.cancel("No URLs found in file."),process.exit(1));let i=0;for(let a of o)await Qo(a)&&i++,x.log.info("");x.log.success(`${i}/${o.length} sites verified.`)}else await Qo(t)||process.exit(1)})}import{existsSync as vc,rmSync as kc}from"fs";import*as ee from"@clack/prompts";function ni(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){vc(me)?(kc(me),ee.log.success("API key removed.")):ee.log.info("No API key configured.");return}let n=ft();n?ee.log.info(`Current API key: ****${n.slice(-4)}`):ee.log.info("No API key configured.");let r=await gt(),o=fe(r),i=ee.spinner();i.start("Verifying API key...");try{await be(o),i.stop("API key verified."),xe(r),ee.log.success("API key saved.")}catch(a){i.stop("Verification failed."),a instanceof $&&a.status===401?ee.cancel("Invalid API key."):ee.cancel(I(a)),process.exit(1)}})}import{existsSync as Qt,rmSync as bc,readFileSync as Fn,writeFileSync as ri}from"fs";import{join as Ue}from"path";import*as U from"@clack/prompts";var Sc=["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"],Ec=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1130
+ export { ops } from "./${r}/index";
1131
+ `;await c(Mt(t,"providers/index.ts"),n),await c(Mt(t,"index.ts"),await Sa(t,r))}async function Sa(e,t){let r=Mt(e,"index.ts");if(!ka(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await va(r,"utf-8"),o=ba.filter(s=>s!==t);return n.split(`
1132
+ `).filter(s=>!o.some(a=>s.includes(`./providers/${a}/`))).join(`
1133
+ `)}import{access as Ea,readFile as Vt,rm as Ut}from"fs/promises";import{join as Y}from"path";var go=["sentry","posthog"],fr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Ft={sentry:"tests/sentry-load-guard.test.ts",posthog:"tests/posthog-load-guard.test.ts"},Ra=["tests/resolution.test.ts","tests/export-isolation.test.ts"],Pa=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],Ia=["./desktop-main","./desktop-renderer"],Ta=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1134
+ `,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
1135
+ `],Aa=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],eo=`
1136
+ });
1137
+ `,Oa=" ";async function ho(e){let t=Y(e.projectDir,"packages/observability");await to(t,"packages/observability");let r=e.errorTracking;if(!B.includes(r))throw new Error(`errorTracking is ${JSON.stringify(r)}, which names no reporting provider. Set it to one of: ${B.join(", ")}. Shaping stops here so the project is not left half-stripped.`);r!=="none"&&await to(Y(t,fr[r]),`packages/observability/${fr[r]}`);let n=e.desktop?[...fo,...wc]:fo,o=new Map;for(let i of n)o.set(i.file,await Vt(Y(t,i.file),"utf-8"));for(let i of Ua(r,e.desktop))await Fa(t,i);for(let i of go)i!==r&&(await Ut(Y(t,fr[i]),{recursive:!0,force:!0}),await Ut(Y(t,Ft[i]),{force:!0}));for(let i of Ra)await Ut(Y(t,i),{force:!0});e.desktop||await xa(t,r);for(let i of n){let s=o.get(i.file);s!==void 0&&await c(Y(t,i.file),Na(s,i,r))}}async function to(e,t){try{await Ea(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function xa(e,t){for(let o of Pa)await Ut(Y(e,o),{force:!0});t==="sentry"&&await Da(e);let r=Y(e,"package.json"),n=JSON.parse(await Vt(r,"utf-8"));for(let o of Ia){if(!n.exports?.[o])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${o} export`);delete n.exports[o]}await c(r,JSON.stringify(n,null," ")+`
1138
+ `)}async function Da(e){let t=Y(e,Ft.sentry),r=await Vt(t,"utf-8");r=yr(r,Ta.map(n=>({find:n,replace:""})),Ft.sentry);for(let n of Aa)r=_a(r,n,Ft.sentry);await c(t,r)}function _a(e,t,r){let n=e.indexOf(t),o=n===-1?-1:e.indexOf(eo,n);if(n===-1||o===-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 i=e.slice(n+t.length,o).split(`
1139
+ `).find(a=>a.trim().length>0&&!a.startsWith(`${Oa} `));if(i!==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: ${i.trim()}`);let s=o+eo.length;return e[s]===`
1140
+ `&&(s+=1),e.slice(0,n)+e.slice(s)}function Na(e,t,r){let n=go.filter(s=>s!==r),o=e,i=[];for(let s of n){let a=Ca(o,s);o=a.source,i.push(...a.bindings)}o=yr(o,[{find:ja,replace:La(r)}],t.file),o=yr(o,t.edits(r),t.file);for(let s of n)if(o.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of i)if(new RegExp(String.raw`\b${s}\b`).test(o))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return o}function yr(e,t,r){let n=e;for(let o of t){if(!n.includes(o.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${o.find.split(`
1141
+ `)[0]}`);n=n.replace(o.find,o.replace)}return n}function Ca(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,i=>(n.push(...$a(i)),"")),bindings:n}}function $a(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let o=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),i=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(o);return i?.[1]?r.push(i[1]):/^[A-Za-z_$][\w$]*$/.test(o)&&r.push(o),r}var ja=" * 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 La(e){return`${e==="none"?` * Your project was generated with error tracking OFF, so no provider adapter and no reporting
1142
+ * SDK were shipped: this file is the whole layer, and every call is a no-op that loads nothing.`:` * Your project reports errors to ${e==="sentry"?"Sentry":"PostHog"}. No other provider's adapter or SDK was generated, so
1143
+ * there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
1144
+ *
1145
+ * To change providers, set \`errorTracking\` in \`.generatesaas/manifest.json\` to the one you want and
1146
+ * run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
1147
+ * update stages nothing while you are already on the latest version, so the switch lands with the
1148
+ * next release. Editing \`config.observability.errorTracking.provider\` on its own cannot: the code
1149
+ * it names is not here.`}function Bt(e){return` remedy: "Set errorTracking in .generatesaas/manifest.json to ${e==="none"?"a provider":"the provider you want"}, then run generatesaas update - it stages nothing until a newer version is out."`}var Kt=' reason: "was never generated - this project was built with error tracking off",',yo=' reason: "has no adapter in this package",',ro={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Ma={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Ua(e,t){return e==="sentry"?[]:t?[ro,Ma]:[ro]}async function Fa(e,t){let r=await Vt(Y(e,t.source),"utf-8"),n=`export interface ${t.name} {
1150
+ `,o=r.indexOf(n),i=r.indexOf(`
1151
+ }
1152
+ `,o);if(o===-1||i===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let s=r.slice(o+n.length,i).split(`
1153
+ `).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(s.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${s.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var wo=" * @param _options - Unused here, and kept so switching providers later costs you no call-site edit.",Va=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Ba=' * Reachable from a hand-edited config, from a manifest written with a typo, and from a provider\n * added to the union before its adapter lands. All three used to fall through to Sentry, which\n * reported nothing (the Sentry gate refuses a config that names another provider) while\n * `resolveServerOps().id` still claimed `"sentry"`.',no=` if (errorTracking.provider === "sentry") return sentryServerOps;
1154
+ `,oo=` if (errorTracking.provider === "posthog") return posthogServerOps;
1155
+ `,io=` if (errorTracking.provider === "sentry") {
1156
+ await initSentryServer();
1157
+ return;
1158
+ }
1159
+ `,so=` if (errorTracking.provider === "posthog") return;
1160
+ `,gr=" * Call this at module scope. A crash during boot is never reported if the SDK waits for the first\n * captured request error, and it is `init()` that installs the `uncaughtException` and\n * `unhandledRejection` handlers. Safe to call unconditionally: the gate short-circuits before any\n * `import()`, so a project with reporting off still loads nothing.\n *\n * PostHog needs no equivalent. `posthog-node` installs no process-level handlers and builds its\n * client on the first capture, so there is nothing an early call could arm.",Ka=' * Resolution reads `enabled` and `provider` only. Whether the selected provider is USABLE - a\n * non-empty DSN or key - stays the adapter\'s own gate, which every runtime shares, so a provider\n * that is selected but unconfigured still resolves to itself and then reports nothing. Splitting it\n * that way keeps one answer to "which provider did the buyer pick" and one answer to "can it send".',ao=` * Every provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1161
+ * warning above - the same direction both desktop runtimes already failed in. A default that picked
1162
+ * a real provider would hand a buyer's errors, and the user ids and request context attached to
1163
+ * them, to a service they never selected the moment that provider's own gate got any looser.`,Ga=` * Your provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1164
+ * warning above. Falling back to a real provider instead would hand your errors, and the user ids
1165
+ * and request context attached to them, to a service your config no longer names.`;function vo(e){return e==="none"?" * Reachable from a hand-edited config: your project ships no provider adapter at all, so whatever\n * `config.observability.errorTracking.provider` names has nothing here to resolve to.":" * Reachable from a hand-edited config: your project ships one provider's adapter, so naming any\n * other in `config.observability.errorTracking.provider` leaves nothing here to resolve to."}function Ha(e){let t=[{find:Va,replace:" into every browser bundle."},{find:Ba,replace:vo(e)},{find:ko,replace:Bt(e)},e==="none"?{find:`
1166
+ *
1167
+ ${ao}`,replace:""}:{find:ao,replace:Ga}];return e==="sentry"?[...t,{find:oo,replace:""},{find:so,replace:""},{find:gr,replace:" * Call this at module scope. A crash during boot is never reported if the SDK waits for the first\n * captured request error, and it is `init()` that installs the `uncaughtException` and\n * `unhandledRejection` handlers. Safe to call unconditionally: the gate short-circuits before any\n * `import()`, so a project with reporting off still loads nothing."}]:e==="posthog"?[...t,{find:no,replace:""},{find:io,replace:""},{find:gr,replace:" * There is nothing to arm in your project: `posthog-node` installs no process-level handlers and\n * builds its client on the first capture, so this settles immediately. The call site is kept so\n * your boot sequence is the same whichever provider you later move to."}]:[...t,{find:yo,replace:Kt},{find:Ka,replace:` * Always the no-op reporter: your project ships no provider adapter at all. Reporting left switched
1168
+ * on in config is announced once rather than ignored, so it can never fail silently.`},{find:no,replace:""},{find:oo,replace:""},{find:gr,replace:` * There is nothing to arm in your project, so this settles immediately after announcing the gap
1169
+ * once. The call site is kept so turning reporting on later needs no change outside config.`},{find:io,replace:""},{find:so,replace:""}]}var ko=` remedy: 'Set observability.errorTracking.provider to "sentry" or "posthog".'`,Ya=' * Reachable from a hand-edited config, from a manifest written with a typo, and from a provider\n * added to the union before its adapter lands. All three used to fall through to Sentry, which\n * reported nothing (the Sentry gate refuses a config that names another provider) while\n * `resolveBrowserOps().id` still claimed `"sentry"`.',co=` if (errorTracking.provider === "sentry") return sentryBrowserOps;
1170
+ `,po=` if (errorTracking.provider === "posthog") return posthogBrowserOps;
1171
+ `,lo=` if (errorTracking.provider === "sentry") {
1172
+ await initSentryBrowser(options);
1173
+ return;
1174
+ }
1175
+ `,uo=` if (errorTracking.provider === "posthog") return;
1176
+ `,Ja="export async function initBrowserReporting(options: BrowserReportingOptions): Promise<void> {",za=" * @param options - How the client tags the events it sends.",Wa="export type BrowserReportingOptions = SentryBrowserInitOptions;",qa='export interface BrowserReportingOptions {\n /** The environment tag, usually `"development"` or `"production"`. */\n environment: string;\n}',hr=" * Call this on boot rather than lazily from an error boundary: it is `init()` that installs the\n * `window.onerror` and `unhandledrejection` handlers and starts recording breadcrumbs, so deferring\n * it would capture only render errors, with no breadcrumbs and no coverage of plain async failures.\n *\n * PostHog has nothing to call here. Its browser client is built on the first capture, which is also\n * when `capture_exceptions` arms the global handlers, so a PostHog project reports every error it\n * is explicitly handed from the start but only starts catching UNHANDLED ones once the first such\n * report has been made. Sentry has no such window.",Xa=' * Resolution reads `enabled` and `provider` only. Whether the selected provider is USABLE - a\n * non-empty DSN or key - stays the adapter\'s own gate, which every runtime shares, so a provider\n * that is selected but unconfigured still resolves to itself and then reports nothing. Splitting it\n * that way keeps one answer to "which provider did the buyer pick" and one to "can it send".',mo=` * Every provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1177
+ * warning above - the same direction both desktop runtimes already failed in. A default that picked
1178
+ * a real provider would hand a buyer's errors, and the user ids attached to them, to a service they
1179
+ * never selected the moment that provider's own gate got any looser.`,Za=` * Your provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1180
+ * warning above. Falling back to a real provider instead would hand your errors, and the user ids
1181
+ * attached to them, to a service your config no longer names.`;function Qa(e){let t=[{find:Ya,replace:vo(e)},{find:ko,replace:Bt(e)},e==="none"?{find:`
1182
+ *
1183
+ ${mo}`,replace:""}:{find:mo,replace:Za}];if(e==="sentry")return[...t,{find:po,replace:""},{find:uo,replace:""},{find:hr,replace:" * Call this on boot rather than lazily from an error boundary: it is `init()` that installs the\n * `window.onerror` and `unhandledrejection` handlers and starts recording breadcrumbs, so deferring\n * it would capture only render errors, with no breadcrumbs and no coverage of plain async failures."}];let r=[{find:Wa,replace:qa},{find:Ja,replace:"export async function initBrowserReporting(_options: BrowserReportingOptions): Promise<void> {"},{find:za,replace:wo}];return e==="posthog"?[...t,...r,{find:co,replace:""},{find:lo,replace:""},{find:hr,replace:` * There is nothing to start in your project. PostHog's browser client is built on the FIRST
1184
+ * capture, which is also when \`capture_exceptions\` arms the global handlers: your app reports every
1185
+ * error it is explicitly handed from the start, and only starts catching UNHANDLED ones once the
1186
+ * first such report has been made. The call site is kept so your boot sequence is the same
1187
+ * whichever provider you later move to.`}]:[...t,...r,{find:yo,replace:Kt},{find:Xa,replace:` * Always the no-op reporter: your project ships no provider adapter at all. Reporting left switched
1188
+ * on in config is announced once rather than ignored, so it can never fail silently.`},{find:co,replace:""},{find:po,replace:""},{find:hr,replace:` * There is nothing to start in your project, so this settles immediately after announcing the gap
1189
+ * once. The call site is kept so turning reporting on later needs no change outside config.`},{find:lo,replace:""},{find:uo,replace:""}]}var ec=` if (errorTracking.provider !== "sentry") {
1190
+ announceMissingDesktopSdk(errorTracking.provider);
1191
+ return noneOps;
1192
+ }
1193
+ return sentryDesktopMainOps;`,tc=` if (errorTracking.provider !== "sentry") {
1194
+ announceMissingDesktopSdk(errorTracking.provider);
1195
+ return;
1196
+ }
1197
+ await initSentryDesktopMain(options);`,rc=" options: DesktopMainReportingOptions",nc=" * @param options - The Electron facts only the app can answer.",oc="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",ic='export interface DesktopMainReportingOptions {\n /** The environment tag, usually `app.isPackaged ? "production" : "development"`. */\n environment: string;\n /** Whether Electron has already fired `ready`, usually `app.isReady()`. */\n appIsReady: boolean;\n}',sc=` * Anything other than Sentry falls back to the no-op reporter, rather than PostHog specifically, so
1198
+ * a provider added to the union later fails safe with the warning instead of quietly shipping a
1199
+ * desktop build that reports nothing.
1200
+ *
1201
+ * Whether Sentry is USABLE - a non-empty DSN - stays the adapter's own gate, which every runtime
1202
+ * shares, so a selected but unconfigured provider still resolves to itself and then reports nothing.`,ac=" * `init()` is what installs the `uncaughtException` and `unhandledRejection` handlers, arms the\n * native crash reporter, and opens the channel renderer events are routed through, so waiting for\n * the first error would lose every crash before it. Safe to call unconditionally: the gate\n * short-circuits before any `import()`, so a build with reporting off still loads nothing.\n *\n * The gate is the config expression ITSELF, inline, exactly as {@link resolveDesktopMainOps} reads\n * it and exactly as the renderer and browser resolvers do. Gating on `resolveDesktopMainOps().id`\n * instead would put a function call between the flag and the `import()`, and a bundler folds a\n * branch away only when the member expression it tests sits in the same function as the import it\n * guards - measured against Rollup, no `treeshake` setting rescues the call form, and a desktop\n * build with reporting off still emitted the whole Sentry chunk. Calling this is still what\n * surfaces the missing-SDK warning at startup.",cc=` * There is nothing to arm in your project, so this settles immediately after announcing the gap
1203
+ * once. The call site is kept so the app's boot sequence is the same whichever provider you later
1204
+ * move to.`,pc=" * Call this on boot rather than lazily from an error boundary: it is `init()` that installs the\n * `window.onerror` and `unhandledrejection` handlers and starts recording breadcrumbs. Safe to call\n * unconditionally: the gate short-circuits before any `import()`, so a build with reporting off\n * still loads nothing.\n *\n * The gate is the config expression ITSELF, inline, exactly as {@link resolveDesktopRendererOps}\n * reads it and exactly as every other runtime does. Gating on `resolveDesktopRendererOps().id`\n * instead would put a function call between the flag and the `import()`, and a bundler folds a\n * branch away only when the member expression it tests sits in the same function as the import it\n * guards - measured against Rollup, no `treeshake` setting rescues the call form. Calling this is\n * still what surfaces the missing-SDK warning at startup.",lc=` * There is nothing to start in your project, so this settles immediately after announcing the gap
1205
+ * once. The call site is kept so the renderer's boot sequence is the same whichever provider you
1206
+ * later move to.`,bo=' remedy: "Select sentry to report errors from the desktop app."',So=' reason: "ships no Electron SDK",';function dc(e){if(e==="sentry")return[];let t=[{find:oc,replace:ic},{find:bo,replace:Bt(e)},{find:sc,replace:Eo(e)},{find:ec,replace:` announceMissingDesktopSdk(errorTracking.provider);
1207
+ return noneOps;`},{find:ac,replace:cc},{find:nc,replace:wo},{find:rc,replace:" _options: DesktopMainReportingOptions"},{find:tc,replace:" announceMissingDesktopSdk(errorTracking.provider);"}];return e==="none"&&t.push({find:So,replace:Kt},hc),t}var uc=` if (errorTracking.provider !== "sentry") {
1208
+ announceMissingDesktopSdk(errorTracking.provider);
1209
+ return noneOps;
1210
+ }
1211
+ return sentryDesktopRendererOps;`,mc=` if (errorTracking.provider !== "sentry") {
1212
+ announceMissingDesktopSdk(errorTracking.provider);
1213
+ return;
1214
+ }
1215
+ await initSentryDesktopRenderer();`,fc=` * Anything other than Sentry falls back to the no-op reporter, rather than PostHog specifically, so
1216
+ * a provider added to the union later fails safe with the warning instead of quietly shipping a
1217
+ * desktop build that reports nothing.`;function gc(e){if(e==="sentry")return[];let t=[{find:bo,replace:Bt(e)},{find:fc,replace:Eo(e)},{find:uc,replace:` announceMissingDesktopSdk(errorTracking.provider);
1218
+ return noneOps;`},{find:pc,replace:lc},{find:mc,replace:" announceMissingDesktopSdk(errorTracking.provider);"}];return e==="none"&&t.push({find:So,replace:Kt},yc),t}function Eo(e){return e==="posthog"?` * Always the no-op reporter, and never in silence. PostHog ships no Electron SDK, so your desktop
1219
+ * build reports nothing and says so once at startup; your web and server reporting is unaffected.`:` * Always the no-op reporter, and never in silence. Your project was generated with error tracking
1220
+ * off, so there is no adapter and no SDK for the desktop app to reach.`}var hc={find:` * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
1221
+ * web must not be blocked from shipping a desktop build over it. Silence would be worse, because
1222
+ * the desktop app would simply never report with nothing to explain why, so the gap is surfaced
1223
+ * here and again in the observability docs.`,replace:` * A WARNING and never an error: your project must still be able to ship whatever you edited, and a
1224
+ * failure to REPORT errors must never itself become an error. Silence would be worse, because the
1225
+ * desktop app would simply never report with nothing to explain why.`},yc={find:` * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
1226
+ * web must not be blocked from shipping a desktop build over it. Main and the renderer are separate`,replace:` * A WARNING and never an error: your project must still be able to ship whatever you edited, and a
1227
+ * failure to REPORT errors must never itself become an error. Main and the renderer are separate`},fo=[{file:"src/resolve-server.ts",edits:Ha},{file:"src/resolve-browser.ts",edits:Qa}],wc=[{file:"src/resolve-desktop-main.ts",edits:dc},{file:"src/resolve-desktop-renderer.ts",edits:gc}];import{readdir as vc,readFile as kc}from"fs/promises";import{join as Ro}from"path";async function Po(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ro(e.projectDir,"packages/i18n/translations"),o;try{o=await vc(n)}catch{return}for(let i of o){let s=Ro(n,i,"web.json"),a;try{a=await kc(s,"utf-8")}catch{continue}let l=a.replaceAll("GenerateSaaS",r);l!==a&&await c(s,l)}}import{readFile as bc}from"fs/promises";import{join as Io}from"path";var Sc=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],Ec=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function Ao(e){let r=e.frontend==="nuxt"?Ec:Sc;await To(Io(e.projectDir,".gitignore"),r),await To(Io(e.projectDir,".dockerignore"),r)}async function To(e,t){let r;try{r=await bc(e,"utf-8")}catch{return}let n=new Set(t),o=r.split(`
1228
+ `).filter(i=>!n.has(i.trim()));o.length!==r.split(`
1229
+ `).length&&await c(e,o.join(`
1230
+ `))}async function Gt(e){let t=e.projectDir;e.demo||(await tn(t),await nn(t),await on(t),await sn(t),e.desktop&&await rn(t)),await an(t,e.frontend),await pn(e),await ln(e),await dn(e),e.demo||await un(e),await gn(e),await hn(e),await yn(e),await wn(e),await vn(e),await kn(e),await Sn(e),await En(e),await Tn(e),await An(e),await Dn(e),await Cn(e),await Mn(e),await Wn(e),await Un(e),await Fn(e),await Vn(e),await Bn(e),await Kn(e),await Gn(e),await Hn(e),await Yn(e),await zn(e),await ur(e),await Zn(e),await Qn(e),await ho(e),await Po(e),await Ao(e)}import{basename as xo,join as Do,relative as Pc}from"path";import{createHash as Oo}from"crypto";import{readFile as Rc}from"fs/promises";async function Ht(e){let t=await Rc(e);return Oo("sha256").update(t).digest("hex")}function wr(e){return Oo("sha256").update(e).digest("hex")}var Ic=new Set(["data",H]);function Tc(e){let t=e.split("/");for(let r of t)if(rr.has(r)||nr.has(r)||Ic.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function _o(e,t){return{projectName:e.projectName??xo(t),appName:e.appName??e.projectName??xo(t),projectDir:t,frontend:e.frontend==="nextjs"?"nextjs":"nuxt",architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,companion:e.companion??!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",errorTracking:e.errorTracking??"none",version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Ac(e,t){return{version:e.version,initialVersion:e.version,repo:"AlexChelan/GenerateSaaS",appName:e.appName,projectName:e.projectName,frontend:e.frontend,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,ai:e.ai,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,errorTracking:e.errorTracking,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function No(e,t){let n=(await Te(e.projectDir,e.projectDir,Tc)).sort(),o=await Promise.all(n.map(async a=>[Ie(Pc(e.projectDir,a)),await Ht(a)])),i=Object.fromEntries(o),s=Ac(e,t);await c(Do(e.projectDir,me),JSON.stringify(s,null," ")+`
1231
+ `),await c(Do(e.projectDir,Kr),JSON.stringify(i,null," ")+`
1232
+ `)}import{relative as Oc}from"path";async function ze(e){let r=(await Te(e,e,Ge)).sort(),n=await Promise.all(r.map(async o=>[Ie(Oc(e,o)),await Ht(o)]));return Object.fromEntries(n)}import{copyFile as xc,mkdir as Dc,rm as _c}from"fs/promises";import{dirname as Nc,join as Co,relative as Cc}from"path";import{existsSync as $c}from"fs";async function vr(e,t){$c(t)&&await _c(t,{recursive:!0,force:!0});let r=await Te(e,e,Ge);for(let n of r){let o=Ie(Cc(e,n)),i=Co(t,o);await Dc(Nc(i),{recursive:!0}),await xc(n,i)}}async function $o(e,t){await vr(e,Co(t,It))}import{existsSync as jc}from"fs";import{readFile as jo,readdir as Lc}from"fs/promises";import{join as X,dirname as Mc,resolve as Uc,sep as Fc}from"path";import{fileURLToPath as Vc}from"url";var Bc={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},De=Object.values(Bc),kr="generatesaas-update",Lo=Mc(Vc(import.meta.url));function Kc(){let e=X(Lo,"skill","content");return jc(e)?e:X(Lo,"content")}async function br(e,t,r){for(let n of De){let o=X(e,n,kr),i=X(o,"scripts"),s=X(o,"references");await xt(i),await xt(s),await c(X(o,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await c(X(s,".gitkeep"),"");for(let[a,l]of Object.entries(r)){let u=Uc(i,a);u.startsWith(i+Fc)&&await c(u,l)}}}async function Mo(e){let t=Kc(),r=await jo(X(t,"SKILL.md"),"utf-8"),n=X(t,"scripts"),o=await Lc(n),i={};for(let s of o)s!==".gitkeep"&&(i[s]=await jo(X(n,s),"utf-8"));await br(e,r,i)}import{execFile as Gc,execFileSync as Hc}from"child_process";import{access as Uo,readFile as Yc}from"fs/promises";import{join as Sr}from"path";import*as _ from"@clack/prompts";function Ne(e){try{let t=process.platform==="win32"?"where":"which";return Hc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function _e(e,t,r,n=3e5){return new Promise((o,i)=>{Gc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,l)=>{if(s){let u=String(a||"").trim(),f=[String(l||"").trim(),u].filter(Boolean).join(`
1233
+ `);i(new Error(f?`${s.message}
1234
+ ${f}`:s.message))}else o()})})}async function Fo(e){if(!Ne("pnpm"))return _.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await _e("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return _.log.warn(`Lockfile regeneration failed: ${r}`),_.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Vo(e){if(!Ne("pnpm"))return _.log.warn("pnpm not found. Skipping dependency installation."),_.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=_.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await _e("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 _.log.warn(`pnpm install failed: ${n}`),_.log.warn("You can run it manually later."),!1}}async function Bo(e){if(!Ne("pnpm"))return!1;let t=_.spinner();t.start("Generating baseline database migration...");try{return await _e("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 _.log.warn(`Could not generate baseline migration: ${n}`),_.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Ko(e){try{return await Uo(Sr(e,".git")),_.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ne("git"))return _.log.warn("git not found. Skipping repository initialization."),!1;let t=_.spinner();t.start("Initializing git repository...");try{return await _e("git",["init"],e),await _e("git",["add","-A"],e),await _e("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),_.log.warn("You can run git init manually later."),!1}}async function Go(e){if(!Ne("pnpm"))return!1;try{await Uo(Sr(e,".git"))}catch{return!1}try{let t=JSON.parse(await Yc(Sr(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 _e("pnpm",["exec","simple-git-hooks"],e),!0}catch{return _.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as We from"@clack/prompts";import J from"picocolors";function Ho(e,t){let r=Me(e);t.dockerAvailable||We.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${J.dim(`# ${r.map(a=>Nr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${J.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(J.dim("Fill in remaining TODO values in .env"))),We.note(n.join(`
1235
+ `),J.yellow("Start Development"));let o=[];o.push(`App ${J.cyan("http://localhost:3000")}`),e.architecture==="separate"&&o.push(`API ${J.cyan("http://localhost:3010")}`),r.includes("mailpit")&&o.push(`Mailpit ${J.cyan("http://localhost:8025")}`),r.includes("inngest")&&o.push(`Inngest ${J.cyan("http://localhost:8288")}`),We.note(o.join(`
1236
+ `),J.yellow("Dev Tools"));let i=[],s=Jc(e);s.length>0&&i.push(`Set in production: ${J.dim(s.join(", "))}`),i.push("pnpm db:setup # Apply the database schema"),i.push(zc(e)),We.note(i.join(`
1237
+ `),J.yellow("Deployment"))}function Jc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET"];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 zc(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 qe(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 Ce(e,t){let r=qe(e),n=qe(t);if(!r||!n)return 0;for(let o=0;o<3;o++)if(r[o]!==n[o])return r[o]-n[o];return 0}function Yt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Yo(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:qe(e)===null}function Jt(e,t,r="2.4.0"){if(Yo(r))return{ok:!0};let n=Yt(e,e.latest);return!n||qe(n)===null?{ok:!0}:Ce(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 Jo(e,t,r="2.4.0"){if(Yo(r))return{ok:!0};let n=Yt(e,t);return!n||qe(n)===null?{ok:!0}:Ce(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 ep from"picocolors";var tp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function rp(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 zo(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 z("--frontend <type>","frontend framework").choices([...Ee])).addOption(new z("--architecture <type>","fullstack or separate").choices([...Ue])).addOption(new z("--payment <provider>","payment provider").choices([...Fe])).addOption(new z("--email <provider>","email provider").choices([...Ve])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").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, schedules, integrations); unlocks the companion").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-companion","exclude the backend companion 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 z("--currency <code>","default currency for billing").choices([...oe])).addOption(new z("--deploy <target>","deployment target").choices([...ie])).addOption(new z("--database <provider>","database provider").choices([...se])).addOption(new z("--cache <provider>","cache provider").choices([...ae])).addOption(new z("--error-tracking <provider>","error reporting provider (anything unselected ships no SDK)").choices([...B])).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 z("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new z("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await np(t?{...r,apiKey:t}:r)})}async function np(e){let t=performance.now();Dr("2.4.0");let r;try{r=Fr(e)}catch(w){v.cancel(D(w)),process.exit(1)}let n=v.spinner(),o;try{o=await Ke({apiKey:e.apiKey,prompt:!e.yes})}catch(w){v.cancel(D(w)),process.exit(1)}e.demo&&wr(o)!==tp&&(v.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=pe(o),s,a=async()=>{s=await he(i);let w=Jt(s,"init");if(!w.ok)throw new Error(w.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,companionAllowed:s.entitlements?.companionAllowed??!0}};n.start("Verifying access...");let l,u,y=!0,f=!0;try{({latestVersion:l,selectedVersion:u,desktopAllowed:y,companionAllowed:f}=await a()),n.stop("Access verified."),Pe(o)}catch(w){if(n.stop("Access verification failed."),w instanceof C&&w.status===401){e.yes&&(v.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),v.log.warning("Invalid API key."),o=await st(),i=pe(o),n.start("Verifying access...");try{({latestVersion:l,selectedVersion:u,desktopAllowed:y,companionAllowed:f}=await a()),n.stop("Access verified."),Pe(o)}catch(N){n.stop("Access verification failed."),v.cancel(N instanceof C&&N.status===401?"Invalid API key.":D(N)),process.exit(1)}}else v.cancel(D(w)),process.exit(1)}v.log.success(`Latest version: ${l}`),r.desktop===!0&&!y&&(v.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.companion===!0&&!f&&(v.cancel("The companion is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let h;e.yes?h=Vr({...r,...y?{}:{desktop:!1},...f?{}:{companion:!1}}):h=await Br(r,{desktopAllowed:y,companionAllowed:f});let $;n.start("Activating license...");try{let w=e.demo&&h.baseUrl?await rp(h.baseUrl):crypto.randomUUID(),N=()=>({frontend:h.frontend,version:u,installId:w,projectName:h.projectName,options:Jr(h)}),de;try{de=await er(i,N())}catch(q){let A=Tt(q);if(!A?.lastAllowedVersion||!s)throw q;n.stop("License activation failed.");let Le=Jo(s,A.lastAllowedVersion);if(Le.ok||(v.cancel(`${A.message} ${Le.message}`),process.exit(1)),e.yes){let P=Yt(s,A.lastAllowedVersion);v.cancel(`${A.message} Re-run ${P?`npx generatesaas@${P} init`:"init"} without --yes to continue with v${A.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let te=await v.confirm({message:`Your update window has ended. Continue with v${A.lastAllowedVersion} (the last version your license covers)?`});(v.isCancel(te)||!te)&&(v.cancel("Setup cancelled."),process.exit(0)),u=A.lastAllowedVersion,n.start(`Activating license for v${u}...`),de=await er(i,N())}$={token:de.token,keyHash:wr(o),installId:de.installId??w},n.stop("License activated.")}catch(w){n.stop("License activation failed."),v.cancel(D(w)),process.exit(1)}let b=Qc(h.projectDir);if(Wc(b)&&qc(b).length>0)if(e.yes)v.log.info(`Directory ${b} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let N=await v.select({message:`Directory ${b} 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"}]});(v.isCancel(N)||N==="cancel")&&(v.cancel("Setup cancelled."),process.exit(0)),N==="overwrite"&&Xc(b,{recursive:!0,force:!0})}let U={...h,projectDir:b,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await At(i,u,b),n.stop("Template downloaded.")}catch(w){n.stop("Download failed."),v.cancel(D(w)),process.exit(1)}n.start("Generating project files...");try{if(await Gt(U),!e.demo){let w=await ze(b);await c(Zc(b,Pt),JSON.stringify(w,null," ")+`
1238
+ `),await $o(b,b)}await Mo(b),await No(U,$),n.stop("Project files generated.")}catch(w){n.stop("Generation failed."),v.cancel(D(w)),process.exit(1)}!await Fo(b)&&U.demo===!0&&(v.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let ee=await Vo(b);ee&&U.demo!==!0&&e.dbMigration!==!1&&await Bo(b),await Ko(b),ee&&await Go(b);let le=Ne("docker"),ke=Zt(U).map(w=>w.key).filter(w=>!U.credentials?.[w]);Ho(U,{pnpmInstalled:ee,dockerAvailable:le,skippedCredentials:ke}),_r(),v.log.info(ep.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Pr}from"fs";import{readFile as ri}from"fs/promises";import{join as Xe,resolve as up}from"path";import*as k from"@clack/prompts";import V from"picocolors";import{mkdtemp as op,rm as ip}from"fs/promises";import{tmpdir as sp}from"os";import{join as ap}from"path";async function Er(e,t,r,n){let o=await op(ap(sp(),"generatesaas-stage-"));try{await At(e,t,o),await Gt({...r,projectDir:o}),await vr(o,n)}finally{await ip(o,{recursive:!0,force:!0})}}function ht(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Rr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ee,adoptable:!1,impact:"structural",shapesTree:!0},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ue,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:ie,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:se,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Fe,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:Ve,adoptable:!1,impact:"config",shapesTree:!1},{key:"errorTracking",label:"Error tracking",hint:"Which service receives your app's errors: Sentry, PostHog, or none. Anything you do not pick costs nothing - its SDK and its adapter are never generated.",category:"Features",kind:"enum",default:"none",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:!0},{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:!0},{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 companion 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.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"companion",label:"Companion 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 OpenCompanion, the daemon we publish and keep updated - your project ships the pairing, dispatch and Companions 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&&ne({...e,companion:!0})===void 0,requiresLabel:"requires AI features 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=>ht(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 cp(e,t){return e[t]!==void 0}function Wo(e){return Rr.filter(t=>t.adoptable&&!cp(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 pp(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"text":return typeof t=="string";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 lp(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"text":return"a string";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function qo(e){let t=[];for(let r of Rr){let n=e[r.key];n!==void 0&&(pp(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${lp(r)}.`))}return t}function Xo(e){let t={};for(let r of Rr)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 Zo(e){return e?"ON":"OFF"}var yt="packages/config/src/index.ts";function Qo(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 ei(e){return[...Me({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var dp=[{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, but it is now a plain config value generated as `user`. Applying this update as-is bills the individual member instead of the organization: new checkouts create member-scoped subscriptions and org-level entitlements stop resolving. Put it back with `billingScope: "organization"` in `packages/config/src/tenancy-flags.mjs`. 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 ${yt} 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 ${yt} 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 ${yt}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===ht(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Zo(e.aiBuiltin)}, but it is now a plain config value generated ${Zo(ht(e))} for a project ${ht(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${yt} 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 ${yt} to keep it off.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local companion checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one companion daemon (OpenCompanion) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` companion source. There is now one companion daemon - OpenCompanion - which we publish and your users install from its own releases. Your project keeps the companion feature and its own pairing, dispatch and Companions 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 OpenCompanion, 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 OpenCompanion, the one daemon we publish.`},{key:"dockerServices",severity:"warn",preserved:e=>Qo(e).join(",")===ei(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Qo(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 ${ei(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===$r.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 (${De.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.`}];function ti(e){let t=[];for(let r of dp){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 ni(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,o=up(r.cwd??process.cwd()),i=Xe(o,me),s;try{s=JSON.parse(await ri(i,"utf-8"))}catch{k.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let a=qo(s);a.length>0&&(k.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1239
+
1240
+ ${a.map(h=>` - ${h}`).join(`
1241
+ `)}
1242
+
1243
+ Correct it there, then run ${V.cyan("generatesaas update")} again.`),process.exit(1));let l=ne(s);l&&(k.cancel(`.generatesaas/manifest.json turns \`${l.feature}\` on with \`deploymentTarget: "${l.target}"\`, which cannot run it.
1244
+
1245
+ ${l.reason}
1246
+
1247
+ Correct it there, then run ${V.cyan("generatesaas update")} again.`),process.exit(1));let u;try{u=await Ke()}catch(h){k.cancel(D(h)),process.exit(1)}let y=pe(u),f=k.spinner();try{f.start("Verifying access...");let h;try{h=await he(y)}catch(P){throw P instanceof C&&P.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):P}let $=Jt(h,"update");if(!$.ok)throw new Error($.message);f.stop("Access verified."),Pe(u),f.start("Fetching latest skill files...");let b=await Yr(y,h.latest);await br(o,b.skillMd,b.scripts);let U=De;if(f.stop("Skills updated."),k.log.success(`Skill files installed to ${V.cyan(U.length.toString())} locations.`),s.version===h.latest){k.log.info(`Already on the latest version (${s.version}).`);return}let Q=JSON.stringify(s);Mr(s),await mp(s,Ur(s),n),await gp(ti(s),n);let ee=Wo(s),le=Xo(s),ve=JSON.stringify(le)!==Q;if(s=le,s.licenseToken)try{let P=await zr(y,{currentToken:s.licenseToken,newVersion:h.latest});s.licenseToken=P.token,P.licenseKeyHash&&(s.licenseKeyHash=P.licenseKeyHash),await c(i,JSON.stringify(s,null," ")+`
1248
+ `),ve=!1,k.log.success("License refreshed.")}catch(P){let Ze=Tt(P);Ze&&(k.cancel(Ze.message),process.exit(1)),k.log.warn("License refresh skipped.")}ve&&await c(i,JSON.stringify(s,null," ")+`
1249
+ `);let ke=_o(s,o),w=Xe(o,Gr);f.start(`Staging v${h.latest} (shaped for your config)...`),await Er(y,h.latest,ke,w),f.stop("Template staged.");let{text:N,title:de}=await wp(y,h,s.version);N&&k.note(N,de);let q=Xe(o,Pt),A=Xe(o,It),Le=!Pr(A),te=!Pr(q);if(Le){if(f.start("Building baseline template (one-time migration)..."),await Er(y,s.version,ke,A),te){let P=await ze(A);await c(q,JSON.stringify(P,null," ")+`
1250
+ `)}if(f.stop("Baseline template stored."),!te){let P=await vp(q,A);P>0&&k.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(te){f.start("Computing baseline template hashes...");let P=await ze(A);await c(q,JSON.stringify(P,null," ")+`
1251
+ `),f.stop("Baseline hashes computed.")}await c(Xe(o,Hr),JSON.stringify({currentVersion:s.version,targetVersion:h.latest,changelog:N,stagedAt:new Date().toISOString(),...ee.length>0?{newOptions:ee}:{},...n?{mode:n}:{}},null," ")+`
1252
+ `),k.log.info(`Update staged: ${V.cyan(s.version)} \u2192 ${V.cyan(h.latest)}`),k.log.info(`Ask your AI coding assistant to ${V.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&Pr(Xe(o,"apps/tauri"))&&k.log.warn(`Desktop: the app moved to an Electron shell (${V.cyan("apps/electron")}). Your project still has the old Tauri shell (${V.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${V.cyan("/desktop/updates")}.`)}catch(h){f.stop("Failed."),k.cancel(`Update failed: ${D(h)}`),process.exit(1)}})}async function mp(e,t,r){if(t.kind==="none")return;let n=yp[t.kind];r==="auto"&&(k.cancel(`${n.message}
1253
+
1254
+ This is a decision only you can make, so an unattended update will not guess it. Run ${V.cyan("generatesaas update")} without ${V.cyan("auto")} and answer it.`),process.exit(1));let o=await k.select({message:n.message,options:n.options});k.isCancel(o)&&(k.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e)}var fp={billingScope:[{value:"stage",label:"Stage it - I will put the scope back myself",hint:'set `billingScope: "organization"` in packages/config/src/tenancy-flags.mjs before taking new checkouts'},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/tenancy-flags.mjs first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}],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 gp(e,t){let r=[];for(let n of e){let o=n.severity==="ask"?fp[n.key]:void 0;if(!o){k.log.warn(n.message);continue}r.push({notice:n,answers:o})}for(let{notice:n,answers:o}of r){t==="auto"&&(k.cancel(`${n.message}
1255
+
1256
+ This is a decision only you can make, so an unattended update will not guess it. Run ${V.cyan("generatesaas update")} without ${V.cyan("auto")} and answer it.`),process.exit(1));let i=await k.select({message:n.message,options:o});(k.isCancel(i)||i==="stop")&&(k.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function hp(e){e.desktop=!1}var yp={"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.companion=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion - it requires AI"},{value:{apply:hp},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function wp(e,t,r){let n=t.latest,o=t.versions.filter(s=>Ce(s.version,r)>0&&Ce(s.version,n)<=0).sort((s,a)=>Ce(s.version,a.version));if(o.length<=1)return{text:await Qt(e,n),title:`Changelog v${n}`};let i=[];for(let s of o){let a=null;try{a=await Qt(e,s.version)}catch{a=null}let l=s.date?` (${s.date.slice(0,10)})`:"",u=s.breaking?" [BREAKING]":"";i.push(`# v${s.version}${l}${u}
1257
+
1258
+ ${a??"_No changelog available for this release._"}`)}return{text:i.join(`
1259
+
1260
+ `),title:`Changelog v${r} \u2192 v${n}`}}async function vp(e,t){let r=JSON.parse(await ri(e,"utf-8")),n=await ze(t),o=0;for(let[i,s]of Object.entries(r))Ge(i)||n[i]!==s&&o++;for(let i of Object.keys(n))i in r||o++;return o}import*as K from"@clack/prompts";import Z from"picocolors";import{readFile as kp}from"fs/promises";import{join as bp,resolve as Sp}from"path";function oi(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=Sp(t.cwd??process.cwd()),n=bp(r,me),o;try{o=JSON.parse(await kp(n,"utf-8"))}catch{K.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let i=[`Version: ${Z.cyan(o.version)}`,`Frontend: ${Z.cyan(o.frontend)}`,o.deploymentTarget?`Deploy target: ${Z.cyan(o.deploymentTarget)}`:null,o.databaseProvider?`Database: ${Z.cyan(o.databaseProvider)}`:null,o.cacheProvider?`Cache: ${Z.cyan(o.cacheProvider)}`:null].filter(Boolean).join(`
1261
+ `);K.note(i,Z.bold("Project Status"));let s=K.spinner();s.start("Checking for updates...");try{let a=await Ke(),l=pe(a),y=(await he(l)).latest;o.version===y?(s.stop("Up to date."),K.log.success(`Already on the latest version (${Z.green(y)})`)):(s.stop("Update available."),K.log.warning(`Update available: ${Z.yellow(o.version)} \u2192 ${Z.green(y)}`),K.log.info(`Open this project in your AI coding agent and ask it to ${Z.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof C&&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: ${D(a)}`)}})}import{readFile as Ep}from"fs/promises";import*as x from"@clack/prompts";import O from"picocolors";function Rp(){return process.env.GENERATESAAS_API_KEY??it()}function Pp(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 Ip(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Tp(e){switch(e.verdict){case"licensed":return x.log.success(`${O.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return x.log.success(`${O.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return x.log.error(`${O.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return x.log.error(`${O.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${O.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return x.log.error(`${O.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return x.log.warn(`${O.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function ii(e,t){let r=process.env.GENERATESAAS_API_URL??ot,n=Rp();e.start("Cross-referencing license records...");try{let o=n?Pp(await Wr(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Ip(await tr(r,{token:t.token,domain:t.domain}));return e.stop(`${O.green("Checked")} - records cross-referenced`),Tp(o)}catch(o){return e.stop(`${O.yellow("Skipped")} - ${D(o)}`),null}}function Ap(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 Ir(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function si(e){x.note([`License ID: ${O.cyan(String(e.lid??"unknown"))}`,`Version: ${O.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Ir(e.pat)}`,`Last updated: ${Ir(e.uat)}`,`Expires: ${Ir(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1262
+ `),O.yellow("License Details"))}function Op(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 ai(e){let t=x.spinner(),r=null,n="no candidates";for(let s of Op(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}let l=(await a.text()).trim();if(!l||l.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}r=l,t.stop(`${O.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${D(a)}`,t.stop(`${O.yellow("Unreachable")} - ${n}`)}}if(r===null){x.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=ci(e);return s?await ii(t,{domain:s})??!1:!1}let o;try{o=Ap(r)}catch{return x.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??ot,a=await tr(s,{token:r});if(a.valid)t.stop(`${O.green("Valid")} - signature verified`);else return t.stop(`${O.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${O.yellow("Skipped")} - could not reach verification service`),x.log.warn("Signature not verified. Displaying unverified claims:"),si(o),!1}return si(o),await ii(t,{token:r,lkh:typeof o.lkh=="string"?o.lkh:void 0,nid:typeof o.nid=="string"?o.nid:void 0,domain:ci(e)})??!0}function ci(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function pi(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(x.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let o=(await Ep(r.file,"utf-8")).split(`
1263
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));o.length===0&&(x.cancel("No URLs found in file."),process.exit(1));let i=0;for(let s of o)await ai(s)&&i++,x.log.info("");x.log.success(`${i}/${o.length} sites verified.`)}else await ai(t)||process.exit(1)})}import{existsSync as xp,rmSync as Dp}from"fs";import*as W from"@clack/prompts";function li(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){xp(ce)?(Dp(ce),W.log.success("API key removed.")):W.log.info("No API key configured.");return}let r=it();r?W.log.info(`Current API key: ****${r.slice(-4)}`):W.log.info("No API key configured.");let n=await st(),o=pe(n),i=W.spinner();i.start("Verifying API key...");try{await he(o),i.stop("API key verified."),Pe(n),W.log.success("API key saved.")}catch(s){i.stop("Verification failed."),s instanceof C&&s.status===401?W.cancel("Invalid API key."):W.cancel(D(s)),process.exit(1)}})}import{existsSync as zt,rmSync as _p,readFileSync as Ar,writeFileSync as di}from"fs";import{join as $e}from"path";import*as M from"@clack/prompts";var Np=["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"],Cp=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1283
1264
  `,` licenseHeartbeatFunction,
1284
1265
  `]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
1285
1266
  `,` .route("/license", licenseRoutes)
1286
- `]}];function Ac(e){return(e&&e.length>0?e.map(n=>Rt[n]):Object.values(Rt)).map(n=>Ue(n,xn))}function Mn(e){return Qt(e)?(bc(e,{recursive:!0}),!0):!1}function Ic(e,t){if(!Qt(e))return!1;let n=Fn(e,"utf-8"),r=n;for(let o of t)r=r.replace(o,"");return r===n?!1:(ri(e,r,"utf-8"),!0)}function Rc(e){let t=Ue(e,".gitignore");if(!Qt(t))return!1;let n=Fn(t,"utf-8"),r=n.split(`
1267
+ `]}];function $p(){return De.map(e=>$e(e,kr))}function Tr(e){return zt(e)?(_p(e,{recursive:!0}),!0):!1}function jp(e,t){if(!zt(e))return!1;let r=Ar(e,"utf-8"),n=r;for(let o of t)n=n.replace(o,"");return n===r?!1:(di(e,n,"utf-8"),!0)}function Lp(e){let t=$e(e,".gitignore");if(!zt(t))return!1;let r=Ar(t,"utf-8"),n=r.split(`
1287
1268
  `).filter(o=>!o.includes(".generatesaas")).join(`
1288
- `);return r===n?!1:(ri(t,r,"utf-8"),!0)}function oi(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),n=Ue(t,we),r;try{r=JSON.parse(Fn(n,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let o=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:s=>{if(s!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(o)&&(U.cancel("Eject cancelled."),process.exit(0)),r.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.licenseToken}`},body:JSON.stringify({event:"eject",version:r.version,frontend:r.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let i=[],a=[];for(let s of Ac(r.aiTools))Mn(Ue(t,s))&&i.push(s);for(let s of Sc)Mn(Ue(t,s))&&i.push(s);Mn(Ue(t,V))&&i.push(V+"/");for(let s of Ec){let u=Ue(t,s.file);Ic(u,s.removals)?a.push(s.file):Qt(u)&&U.log.warn(`Could not auto-modify ${s.file} - manually remove license/heartbeat references.`)}Rc(t)&&a.push(".gitignore");for(let s of i)U.log.info(`Deleted ${s}`);for(let s of a)U.log.info(`Modified ${s}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var Me=new Pc().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.2.0").addHelpText("after",`
1269
+ `);return n===r?!1:(di(t,n,"utf-8"),!0)}function ui(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=$e(t,me),n;try{n=JSON.parse(Ar(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let o=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(o)&&(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 i=[],s=[];for(let a of $p())Tr($e(t,a))&&i.push(a);for(let a of Np)Tr($e(t,a))&&i.push(a);Tr($e(t,H))&&i.push(H+"/");for(let a of Cp){let l=$e(t,a.file);jp(l,a.removals)?s.push(a.file):zt(l)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Lp(t)&&s.push(".gitignore");for(let a of i)M.log.info(`Deleted ${a}`);for(let a of s)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var je=new Mp().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.4.0").addHelpText("after",`
1289
1270
  Examples:
1290
1271
  $ generatesaas init Interactive setup
1291
1272
  $ generatesaas init -n my-app -y Quick setup with defaults
1292
1273
  $ generatesaas status Check for updates
1293
1274
  $ generatesaas auth Set or update API key
1294
- `);Vo(Me);qo(Me);Wo(Me);ti(Me);ni(Me);oi(Me);Me.parseAsync().catch(e=>{ii.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
1275
+ `);zo(je);ni(je);oi(je);pi(je);li(je);ui(je);je.parseAsync().catch(e=>{mi.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});