generatesaas 2.0.1 → 2.1.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 +130 -130
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as Jc}from"commander";import*as Ti from"@clack/prompts";import{existsSync as sc,readdirSync as cc,rmSync as pc}from"fs";import{join as lc,resolve as dc}from"path";import{Option as X}from"commander";import*as A from"@clack/prompts";import*as Nt from"@clack/prompts";import yn from"picocolors";function dr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Nt.intro(yn.bgYellow(yn.black(t)))}function ur(){Nt.outro(yn.yellow("Happy building!"))}import*as f from"@clack/prompts";import h from"picocolors";var ht={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},yt={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)"}},$t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Lt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Ut={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},qe={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}},wt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var De={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 ie={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}},Y={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"}]}},ae={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"}]}},vt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],kt=[{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)."}],mr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function jt(e){let t=Y[e.databaseProvider].managed,n=ae[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var ue={google:{label:"Google",envVars:[{name:"GOOGLE_CLIENT_ID",secret:!1},{name:"GOOGLE_CLIENT_SECRET",secret:!0}]},github:{label:"GitHub",envVars:[{name:"GITHUB_CLIENT_ID",secret:!1},{name:"GITHUB_CLIENT_SECRET",secret:!0}]},facebook:{label:"Facebook",envVars:[{name:"FACEBOOK_CLIENT_ID",secret:!1},{name:"FACEBOOK_CLIENT_SECRET",secret:!0}]},discord:{label:"Discord",envVars:[{name:"DISCORD_CLIENT_ID",secret:!1},{name:"DISCORD_CLIENT_SECRET",secret:!0}]},x:{label:"X",envVars:[{name:"TWITTER_CLIENT_ID",secret:!1},{name:"TWITTER_CLIENT_SECRET",secret:!0}]}};var Ne=["nextjs","nuxt"],Ye=["fullstack","separate"],We=["stripe","polar","none"],Xe=["smtp","ses","resend"],Ze=["postgres","redis","inngest","mailpit"],Qe=["claude-code","cursor","codex","gemini-cli","windsurf"],et=["user","organization"],me=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],fe=["node","vercel"],ge=["postgres","neon","supabase"],he=["redis","upstash"],tt=["google","github","facebook","discord","x"],$e=["shared","vendored"];function Mt(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function nt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Vt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function T(e){return e instanceof Error?e.message:String(e)}function ee(e){let t=e?.trim();return t?`${nt(t)} Companion`:"My Companion"}var Le="https://github.com/Duzbee/OpenCompanion";function se(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function fr(e){return e.desktop===!0&&e.ai===!0}function W(e){if(fr(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 se(e)}function ye(e){return fr(e)?!0:e.companion===!0&&se(e)==="vendored"}function Ft(e){return e.demo===!0&&e.companion===!0?!0:ye(e)}function Ie(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var gr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ne,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:Ye,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:fe,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ge,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:he,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:We,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:me,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Xe,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:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:et,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{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:"emailTracking",label:"Email analytics",hint:"Tracks opens and clicks of marketing emails and adds an admin analytics page.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config"},{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:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, and BYOK options. On a desktop project it also ships the app's local AI stack and bundles a companion daemon 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=>W(e),choices:$e,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:()=>Le,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionLocalPath",label:"Companion local checkout",hint:"Optional path to your local checkout of the shared companion, if you develop it alongside this project. Leave empty otherwise.",category:"Features",kind:"text",default:()=>"",adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(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=>ee(e.projectName),adoptable:!0,impact:"config",requires:e=>ye(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{key:"mcpServer",label:"Outward MCP server",hint:"Exposes the app's capability layer to external agents as an authenticated MCP OAuth server.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"aiBuiltin",label:"Built-in AI (credits)",hint:"Your app offers models under its own name via OpenRouter, billed from user credits (which need a payment provider to buy). The only setup is OPENROUTER_API_KEY.",category:"Features",kind:"boolean",default:e=>Ie(e),adoptable:!1,impact:"config",requires:e=>e.ai===!0&&Ie(e),requiresLabel:"requires AI features and a payment provider"},{key:"aiByok",label:"User API keys (BYOK)",hint:"Let end-users connect their own provider API keys; runs on their key never use credits.",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{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=>Ie(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:"socialProviders",label:"Social login providers",hint:"Which social sign-in buttons the auth screen shows.",category:"Features",kind:"multiselect",default:[],choices:tt,adoptable:!1,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:Qe,adoptable:!1,impact:"config"}];function Oi(e,t){return e[t]!==void 0}function hr(e){return gr.filter(t=>t.adoptable&&!Oi(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 yr(e){let t={};for(let n of gr)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 vn}from"fs/promises";import{join as wr}from"path";var wn="GENERATESAAS_COMPANION_BRAND_JSON",Bt=["daemon/brand.json","apps/companion/brand.json"];function ce(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 vr(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function Gt(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}}async function Ci(e,t){let n=wr(e,"apps/companion/brand.json"),r;try{r=await vn(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=ce(o)}catch{return null}return vr(i,t)?Gt(r,`the template (${n})`):null}async function Di(e,t){for(let n of Bt){let r=wr(e,n),o;try{o=await vn(r,"utf8")}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;throw s}let i=Gt(o,r),a=JSON.parse(o).repoUrl;if(typeof a=="string"&&a.trim()!==""){let s;try{s=ce(a)}catch{throw new Error(`The companion checkout at ${r} names an unusable repoUrl ("${a}"), so it cannot be verified against ${t.canonicalUrl}. Fix the checkout's brand.json, or drop --companion-local-path to fetch the identity from GitHub.`)}if(!vr(s,t))throw new Error(`The companion checkout at ${e} belongs to ${s.canonicalUrl}, but the project points at ${t.canonicalUrl}. Point --companion-repo-url and --companion-local-path at the same companion, or drop --companion-local-path to fetch the identity from GitHub.`)}return i}throw new Error(`No brand.json found in ${e} (checked ${Bt.join(" and ")}). Point --companion-local-path at a checkout of the companion repo, or remove it to fetch the identity from GitHub.`)}async function Ni(e){for(let t of Bt){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}): ${T(o)}. Check your network, or pass --companion-local-path to a local checkout of the companion.`)}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 Gt(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Bt.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function kr(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=ce(t),r=await Ci(e.projectDir,n);if(r)return r;let o=e.companionLocalPath?.trim();if(o)return await Di(o,n);let i=process.env[wn]?.trim();if(i){let a;try{a=await vn(i,"utf8")}catch(s){throw new Error(`Could not read ${wn} (${i}): ${T(s)}.`)}return Gt(a,`${wn} (${i})`)}return await Ni(n)}var br=["companion","mcpServer"];function bn(e){if(!br.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Sr(e){if(e.ai!==!0)return!0;let t=e.aiBuiltin===!0&&Ie(e),n=e.desktop===!0;return t||e.aiByok===!0||e.companion===!0||n}function Sn(e){if(!Sr(e))throw new Error("AI features have no usable model source: built-in AI needs a payment provider (it bills from user credits), user API keys (BYOK) are off, and there is no companion. Enable one - add a payment provider, keep user API keys (drop --no-ai-byok), or add the companion (--companion).")}function Er(e){return br.some(n=>e[n]===!0)&&(e.ai=!0),e}function Ir(e){return e.ai!==!0||(e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1),Ie(e)||(e.aiBuiltin=!1),Sr(e)||(e.aiByok=!0)),e}function Ar(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=$i(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&En(e),n}function En(e){return ye(e)&&(e.companionSource=W(e),e.companionName===void 0&&(e.companionName=ee(e.projectName))),e}function $i(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 Pr(e){let t={};if(e.name!==void 0){if(!Vt(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(!Ne.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ne.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.billingScope!==void 0){if(e.org!==!0)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(e.blog!==void 0&&(t.blog=e.blog),e.emailTracking!==void 0&&(t.emailTracking=e.emailTracking),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!$e.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${$e.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=ce(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(e.companionLocalPath!==void 0){if(e.companion===!1)throw new Error("--companion-local-path requires the companion; remove --no-companion.");let n=e.companionLocalPath.trim();n!==""&&(t.companionLocalPath=n,t.companion===void 0&&(t.companion=!0))}if(t.companionSource==="vendored"&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path apply to a shared companion; remove them or use --companion-source shared.");if(e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiBuiltin!==void 0){if(e.aiBuiltin===!0&&e.payment==="none")throw new Error("--ai-builtin requires a payment provider (got --payment none). Built-in AI bills from user credits.");t.aiBuiltin=e.aiBuiltin}if(e.aiByok!==void 0&&(t.aiByok=e.aiByok),bn(t),e.desktop===!0&&t.ai===!0&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path point at a SHARED companion, but a desktop app with AI bundles its own; remove them, 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=kn(e.docker,Ze,"docker service")),e.aiTools!==void 0&&(t.aiTools=kn(e.aiTools,Qe,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=kn(e.socialProviders,tt,"social provider")),e.currency!==void 0){if(!me.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${me.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!fe.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${fe.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ge.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ge.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!he.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${he.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 pe={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,emailTracking:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,ai:!1,companion:!1,mcpServer:!1,aiBuiltin:!0,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function Rr(e){let t=e.projectName??pe.projectName,n=e.projectDir??`./${t}`,r=e.appName??nt(t),o=e.deploymentTarget??pe.deploymentTarget,i=ie[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":pe.databaseProvider),s=e.cacheProvider??(i?"upstash":pe.cacheProvider),u=e.emailProvider??(i?"resend":pe.emailProvider),g=e.dockerServices??(i?pe.dockerServices.filter(m=>m!=="postgres"&&m!=="redis"):pe.dockerServices),l={...pe,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.multiTenancy||(l.billingScope="user"),l.ai||(l.aiBuiltin=pe.aiBuiltin,l.aiByok=pe.aiByok),l.paymentProvider==="none"&&(l.aiBuiltin=!1),l.desktop&&l.ai&&(l.companionSource=W(l)),ye(l)&&l.companionName===void 0&&(l.companionName=ee(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=se(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=ee(l.projectName)):(l.companionRepoUrl===void 0&&(l.companionRepoUrl=Le),l.companionLocalPath===void 0&&(l.companionLocalPath=""))),Sn(l);for(let m of vt){if(l.deploymentTarget!==m.target)continue;let w=l.databaseProvider===m.provider?"database":"cache";if(l.databaseProvider===m.provider||l.cacheProvider===m.provider)throw new Error(`Incompatible: --deploy ${m.target} + --${w} ${m.provider}. ${m.reason}`)}for(let m of kt)if(l.architecture===m.architecture&&l.deploymentTarget===m.target)throw new Error(`Incompatible: --architecture ${m.architecture} + --deploy ${m.target}. ${m.reason}`);return l}function kn(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 S(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function In(e){let t=[];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}));for(let n of e.socialProviders){let r=ue[n];for(let o of r.envVars)t.push({key:o.name,message:`${o.name} (${r.label}, optional):`,secret:o.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function xr(e,t){let n=!1;e&&bn(e),f.log.info(h.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Vt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await f.text({message:"App name:",initialValue:nt(r),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await f.text({message:"Project location:",initialValue:`./${r}`});return S(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(ht),d=await f.select({message:"Frontend framework:",options:c.map(b=>({value:b,label:ht[b].label,hint:ht[b].hint}))});return S(d),d})();f.log.info(h.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await f.select({message:"Deployment target:",options:fe.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint}))});S(c),s=c}let u=e?.architecture?kt.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(kt.filter(c=>c.target===s).map(c=>c.architecture)),l=Ye.filter(c=>!g.has(c)),m=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return f.log.info(`Auto-selected ${yt[d].label} architecture (only compatible option for ${ie[s].label}).`),d}n=!0;let c=await f.select({message:"Architecture:",options:l.map(d=>({value:d,label:yt[d].label,hint:yt[d].hint}))});return S(c),c})(),w=e?.databaseProvider??await(async()=>{n=!0;let c=ge.filter(b=>!vt.some(K=>K.target===s&&K.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${Y[b].label} (only compatible option for ${ie[s].label}).`),b}let d=await f.select({message:"Database provider:",options:c.map(b=>({value:b,label:Y[b].label,hint:Y[b].hint}))});return S(d),d})(),v=e?.cacheProvider??await(async()=>{n=!0;let c=he.filter(b=>!vt.some(K=>K.target===s&&K.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${ae[b].label} (only compatible option for ${ie[s].label}).`),b}let d=await f.select({message:"Cache provider:",options:c.map(b=>({value:b,label:ae[b].label,hint:ae[b].hint}))});return S(d),d})();if(ie[s]?.edgeRuntime){let c=mr.map(d=>` - ${d}`).join(`
|
|
3
|
-
`);
|
|
4
|
-
`),d=[` Deploy target: ${
|
|
5
|
-
`),
|
|
6
|
-
`),K=[
|
|
7
|
-
`);K.push("",
|
|
8
|
-
`),"Summary");let H=await
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`,scripts:{}}:await(await
|
|
11
|
-
|
|
12
|
-
`)}async function I(e,t,n,r,o){let i=await
|
|
13
|
-
`)}function
|
|
14
|
-
`,"",`${t} meta.json ${n} nav entry`,o),await
|
|
2
|
+
import{Command as qc}from"commander";import*as _i from"@clack/prompts";import{existsSync as cc,readdirSync as pc,rmSync as lc}from"fs";import{join as dc,resolve as uc}from"path";import{Option as W}from"commander";import*as A from"@clack/prompts";import*as $t from"@clack/prompts";import wn from"picocolors";function ur(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";$t.intro(wn.bgYellow(wn.black(t)))}function mr(){$t.outro(wn.yellow("Happy building!"))}import*as m from"@clack/prompts";import f from"picocolors";var yt={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},wt={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)"}},Lt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ut={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},jt={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},Ye={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}},vt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Ne={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 ie={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}},q={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"}]}},ae={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"}]}},kt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],bt=[{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)."}],fr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Mt(e){let t=q[e.databaseProvider].managed,n=ae[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var me={google:{label:"Google",envVars:[{name:"GOOGLE_CLIENT_ID",secret:!1},{name:"GOOGLE_CLIENT_SECRET",secret:!0}]},github:{label:"GitHub",envVars:[{name:"GITHUB_CLIENT_ID",secret:!1},{name:"GITHUB_CLIENT_SECRET",secret:!0}]},facebook:{label:"Facebook",envVars:[{name:"FACEBOOK_CLIENT_ID",secret:!1},{name:"FACEBOOK_CLIENT_SECRET",secret:!0}]},discord:{label:"Discord",envVars:[{name:"DISCORD_CLIENT_ID",secret:!1},{name:"DISCORD_CLIENT_SECRET",secret:!0}]},x:{label:"X",envVars:[{name:"TWITTER_CLIENT_ID",secret:!1},{name:"TWITTER_CLIENT_SECRET",secret:!0}]}};var $e=["nextjs","nuxt"],We=["fullstack","separate"],Xe=["stripe","polar","none"],Ze=["smtp","ses","resend"],Qe=["postgres","redis","inngest","mailpit"],et=["claude-code","cursor","codex","gemini-cli","windsurf"],tt=["user","organization"],fe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ge=["node","vercel"],he=["postgres","neon","supabase"],ye=["redis","upstash"],nt=["google","github","facebook","discord","x"],Le=["shared","vendored"];function Vt(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function rt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ft(e){return/^[a-z][a-z0-9-]*$/.test(e)}function T(e){return e instanceof Error?e.message:String(e)}function Z(e){let t=e?.trim();return t?`${rt(t)} Companion`:"My Companion"}var Ue="https://github.com/Duzbee/OpenCompanion";function se(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function gr(e){return e.desktop===!0&&e.ai===!0}function Y(e){if(gr(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 se(e)}function we(e){return gr(e)?!0:e.companion===!0&&se(e)==="vendored"}function Bt(e){return e.demo===!0&&e.companion===!0?!0:we(e)}function Ee(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var hr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:$e,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:We,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ge,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:he,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ye,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Xe,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:fe,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ze,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:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:tt,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{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:"emailTracking",label:"Email analytics",hint:"Tracks opens and clicks of marketing emails and adds an admin analytics page.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config"},{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:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, and BYOK options. On a desktop project it also ships the app's local AI stack and bundles a companion daemon 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=>Y(e),choices:Le,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:()=>Ue,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionLocalPath",label:"Companion local checkout",hint:"Optional path to your local checkout of the shared companion, if you develop it alongside this project. Leave empty otherwise.",category:"Features",kind:"text",default:()=>"",adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(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=>Z(e.projectName),adoptable:!0,impact:"config",requires:e=>we(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{key:"mcpServer",label:"Outward MCP server",hint:"Exposes the app's capability layer to external agents as an authenticated MCP OAuth server.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"aiBuiltin",label:"Built-in AI (credits)",hint:"Your app offers models under its own name via OpenRouter, billed from user credits (which need a payment provider to buy). The only setup is OPENROUTER_API_KEY.",category:"Features",kind:"boolean",default:e=>Ee(e),adoptable:!1,impact:"config",requires:e=>e.ai===!0&&Ee(e),requiresLabel:"requires AI features and a payment provider"},{key:"aiByok",label:"User API keys (BYOK)",hint:"Let end-users connect their own provider API keys; runs on their key never use credits.",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{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=>Ee(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:"socialProviders",label:"Social login providers",hint:"Which social sign-in buttons the auth screen shows.",category:"Features",kind:"multiselect",default:[],choices:nt,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Qe,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:et,adoptable:!1,impact:"config"}];function Ci(e,t){return e[t]!==void 0}function yr(e){return hr.filter(t=>t.adoptable&&!Ci(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 wr(e){let t={};for(let n of hr)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 kn}from"fs/promises";import{join as vr}from"path";var vn="GENERATESAAS_COMPANION_BRAND_JSON",Gt=["daemon/brand.json","apps/companion/brand.json"];function ce(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 kr(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function Kt(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}}async function Di(e,t){let n=vr(e,"apps/companion/brand.json"),r;try{r=await kn(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=ce(o)}catch{return null}return kr(i,t)?Kt(r,`the template (${n})`):null}async function Ni(e,t){for(let n of Gt){let r=vr(e,n),o;try{o=await kn(r,"utf8")}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;throw s}let i=Kt(o,r),a=JSON.parse(o).repoUrl;if(typeof a=="string"&&a.trim()!==""){let s;try{s=ce(a)}catch{throw new Error(`The companion checkout at ${r} names an unusable repoUrl ("${a}"), so it cannot be verified against ${t.canonicalUrl}. Fix the checkout's brand.json, or drop --companion-local-path to fetch the identity from GitHub.`)}if(!kr(s,t))throw new Error(`The companion checkout at ${e} belongs to ${s.canonicalUrl}, but the project points at ${t.canonicalUrl}. Point --companion-repo-url and --companion-local-path at the same companion, or drop --companion-local-path to fetch the identity from GitHub.`)}return i}throw new Error(`No brand.json found in ${e} (checked ${Gt.join(" and ")}). Point --companion-local-path at a checkout of the companion repo, or remove it to fetch the identity from GitHub.`)}async function $i(e){for(let t of Gt){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}): ${T(o)}. Check your network, or pass --companion-local-path to a local checkout of the companion.`)}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 Kt(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Gt.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function br(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=ce(t),r=await Di(e.projectDir,n);if(r)return r;let o=e.companionLocalPath?.trim();if(o)return await Ni(o,n);let i=process.env[vn]?.trim();if(i){let a;try{a=await kn(i,"utf8")}catch(s){throw new Error(`Could not read ${vn} (${i}): ${T(s)}.`)}return Kt(a,`${vn} (${i})`)}return await $i(n)}var Sr=["companion","mcpServer"];function Sn(e){if(!Sr.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Er(e){if(e.ai!==!0)return!0;let t=e.aiBuiltin===!0&&Ee(e),n=e.desktop===!0;return t||e.aiByok===!0||e.companion===!0||n}function En(e){if(!Er(e))throw new Error("AI features have no usable model source: built-in AI needs a payment provider (it bills from user credits), user API keys (BYOK) are off, and there is no companion. Enable one - add a payment provider, keep user API keys (drop --no-ai-byok), or add the companion (--companion).")}function Ir(e){return Sr.some(n=>e[n]===!0)&&(e.ai=!0),e}function Ar(e){return e.ai!==!0||(e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1),Ee(e)||(e.aiBuiltin=!1),Er(e)||(e.aiByok=!0)),e}function Pr(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=Li(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&In(e),n}function In(e){return we(e)&&(e.companionSource=Y(e),e.companionName===void 0&&(e.companionName=Z(e.projectName))),e}function Li(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 Rr(e){let t={};if(e.name!==void 0){if(!Ft(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(!$e.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${$e.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.billingScope!==void 0){if(e.org!==!0)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(e.blog!==void 0&&(t.blog=e.blog),e.emailTracking!==void 0&&(t.emailTracking=e.emailTracking),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!Le.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${Le.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=ce(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(e.companionLocalPath!==void 0){if(e.companion===!1)throw new Error("--companion-local-path requires the companion; remove --no-companion.");let n=e.companionLocalPath.trim();n!==""&&(t.companionLocalPath=n,t.companion===void 0&&(t.companion=!0))}if(t.companionSource==="vendored"&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path apply to a shared companion; remove them or use --companion-source shared.");if(e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiBuiltin!==void 0){if(e.aiBuiltin===!0&&e.payment==="none")throw new Error("--ai-builtin requires a payment provider (got --payment none). Built-in AI bills from user credits.");t.aiBuiltin=e.aiBuiltin}if(e.aiByok!==void 0&&(t.aiByok=e.aiByok),Sn(t),e.desktop===!0&&t.ai===!0&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path point at a SHARED companion, but a desktop app with AI bundles its own; remove them, 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=bn(e.docker,Qe,"docker service")),e.aiTools!==void 0&&(t.aiTools=bn(e.aiTools,et,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=bn(e.socialProviders,nt,"social provider")),e.currency!==void 0){if(!fe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${fe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ge.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ge.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!he.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${he.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ye.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ye.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 pe={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,emailTracking:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,ai:!1,companion:!1,mcpServer:!1,aiBuiltin:!0,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function xr(e){let t=e.projectName??pe.projectName,n=e.projectDir??`./${t}`,r=e.appName??rt(t),o=e.deploymentTarget??pe.deploymentTarget,i=ie[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":pe.databaseProvider),s=e.cacheProvider??(i?"upstash":pe.cacheProvider),u=e.emailProvider??(i?"resend":pe.emailProvider),g=e.dockerServices??(i?pe.dockerServices.filter(h=>h!=="postgres"&&h!=="redis"):pe.dockerServices),l={...pe,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.multiTenancy||(l.billingScope="user"),l.ai||(l.aiBuiltin=pe.aiBuiltin,l.aiByok=pe.aiByok),l.paymentProvider==="none"&&(l.aiBuiltin=!1),l.desktop&&l.ai&&(l.companionSource=Y(l)),we(l)&&l.companionName===void 0&&(l.companionName=Z(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=se(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=Z(l.projectName)):(l.companionRepoUrl===void 0&&(l.companionRepoUrl=Ue),l.companionLocalPath===void 0&&(l.companionLocalPath=""))),En(l);for(let h of kt){if(l.deploymentTarget!==h.target)continue;let y=l.databaseProvider===h.provider?"database":"cache";if(l.databaseProvider===h.provider||l.cacheProvider===h.provider)throw new Error(`Incompatible: --deploy ${h.target} + --${y} ${h.provider}. ${h.reason}`)}for(let h of bt)if(l.architecture===h.architecture&&l.deploymentTarget===h.target)throw new Error(`Incompatible: --architecture ${h.architecture} + --deploy ${h.target}. ${h.reason}`);return l}function bn(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 E(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function An(e){let t=[];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}));for(let n of e.socialProviders){let r=me[n];for(let o of r.envVars)t.push({key:o.name,message:`${o.name} (${r.label}, optional):`,secret:o.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Tr(e,t){let n=!1;e&&Sn(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(!Ft(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return E(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await m.text({message:"App name:",initialValue:rt(r),validate:d=>{if(!d?.trim())return"App name is required."}});return E(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await m.text({message:"Project location:",initialValue:`./${r}`});return E(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(yt),d=await m.select({message:"Frontend framework:",options:c.map(S=>({value:S,label:yt[S].label,hint:yt[S].hint}))});return E(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:ge.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint}))});E(c),s=c}let u=e?.architecture?bt.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(bt.filter(c=>c.target===s).map(c=>c.architecture)),l=We.filter(c=>!g.has(c)),h=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return m.log.info(`Auto-selected ${wt[d].label} architecture (only compatible option for ${ie[s].label}).`),d}n=!0;let c=await m.select({message:"Architecture:",options:l.map(d=>({value:d,label:wt[d].label,hint:wt[d].hint}))});return E(c),c})(),y=e?.databaseProvider??await(async()=>{n=!0;let c=he.filter(S=>!kt.some(K=>K.target===s&&K.provider===S));if(c.length===1){let S=c[0];return m.log.info(`Auto-selected ${q[S].label} (only compatible option for ${ie[s].label}).`),S}let d=await m.select({message:"Database provider:",options:c.map(S=>({value:S,label:q[S].label,hint:q[S].hint}))});return E(d),d})(),_=e?.cacheProvider??await(async()=>{n=!0;let c=ye.filter(S=>!kt.some(K=>K.target===s&&K.provider===S));if(c.length===1){let S=c[0];return m.log.info(`Auto-selected ${ae[S].label} (only compatible option for ${ie[s].label}).`),S}let d=await m.select({message:"Cache provider:",options:c.map(S=>({value:S,label:ae[S].label,hint:ae[S].hint}))});return E(d),d})();if(ie[s]?.edgeRuntime){let c=fr.map(d=>` - ${d}`).join(`
|
|
3
|
+
`);m.note(c,"Unavailable on edge runtime")}m.log.info(f.bold("Features"));let v=e?.paymentProvider??await(async()=>{n=!0;let c=await m.select({message:"Payment provider:",options:Xe.map(d=>({value:d,label:Lt[d].label,hint:Lt[d].hint}))});return E(c),c})(),$=e?.defaultCurrency??await(async()=>{if(v==="none")return"USD";n=!0;let c=await m.select({message:"Default currency:",options:fe.map(d=>({value:d,label:d,hint:Ne[d].name}))});return E(c),c})(),ne=e?.emailProvider??await(async()=>{n=!0;let c=await m.select({message:"Email provider:",options:Ze.map(d=>({value:d,label:Ut[d].label,hint:Ut[d].hint}))});return E(c),c})(),Se=e?.multiTenancy??await(async()=>{n=!0;let c=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return E(c),c})(),re=Se?e?.billingScope??"user":"user";if(Se&&e?.billingScope===void 0){n=!0;let c=await m.select({message:"Billing scope:",options:tt.map(d=>({value:d,label:jt[d].label,hint:jt[d].hint}))});E(c),re=c}let _e=e?.blog??await(async()=>{n=!0;let c=await m.confirm({message:"Enable blog?",initialValue:!0});return E(c),c})(),Oe=e?.emailTracking??await(async()=>{n=!0;let c=await m.confirm({message:"Enable email analytics? (open/click tracking + admin analytics page)",initialValue:!0});return E(c),c})(),qe=e?.docs??await(async()=>{n=!0;let c=await m.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return E(c),c})(),k=t?.desktopAllowed!==!1,x=e?.desktop??(k?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 E(c),c})():(m.log.info(f.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),ue=x?e?.desktopAutoRelease??await(async()=>{n=!0;let c=await m.select({message:"Desktop release trigger:",options:[{value:!1,label:"Manual only",hint:"run from the Actions tab (saves CI minutes)"},{value:!0,label:"Automatic",hint:"release on every CI success on main"}],initialValue:!1});return E(c),c})():!1,M=e?.ai??await(async()=>{n=!0;let c=await m.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion + MCP server)",initialValue:!1});return E(c),c})(),b=t?.companionAllowed!==!1,L=M?e?.companion??(b?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 E(c),c})():(m.log.info(f.dim("Companion: available on the Pro plan and up - skipped.")),!1)):!1,Ce=x&&M,oe=Ce?Y({desktop:x,ai:M,companion:L,companionSource:e?.companionSource,companionName:e?.companionName}):L?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 E(c),c})():void 0;Ce&&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 un=oe!=="shared"?void 0:e?.companionRepoUrl??await(async()=>{n=!0;let c=await m.text({message:"Companion repo URL (GitHub):",initialValue:Ue,validate:d=>{if(!d?.trim())return"A companion repo URL is required for a shared companion.";try{ce(d)}catch(S){return T(S)}}});return E(c),ce(c).canonicalUrl})(),sr=oe!=="shared"?void 0:e?.companionLocalPath??await(async()=>{n=!0;let c=await m.text({message:"Path to your local checkout of this companion (leave empty otherwise):",placeholder:"only if you develop the companion alongside this project",defaultValue:""});return E(c),c.trim()})(),Ct=oe!=="vendored"?void 0:e?.companionName??await(async()=>{n=!0;let c=await m.text({message:Ce&&!L?"Companion name (your app's bundled daemon - names its binary, service and data folder):":"Companion name (what your users install):",initialValue:Z(r),validate:d=>{if(!d?.trim())return"Companion name is required."}});return E(c),c})(),cr=M?e?.mcpServer??await(async()=>{n=!0;let c=await m.confirm({message:"Add the outward MCP server? Lets external agents (Claude Code, Codex, Hermes, OpenClaw) control the app on a user's behalf over an authenticated MCP endpoint.",initialValue:!1});return E(c),c})():!1,mn=v==="none"?!1:M?e?.aiBuiltin??await(async()=>{n=!0;let c=await m.confirm({message:"Built-in AI? (models under your app's name via OpenRouter, billed from user credits)",initialValue:!0});return E(c),c})():!0,fn=M?e?.aiByok??await(async()=>{n=!0;let c=await m.confirm({message:"Allow users to bring their own API keys? (their runs never use credits)",initialValue:!0});return E(c),c})():!0;En({ai:M,aiBuiltin:mn,aiByok:fn,companion:L,desktop:x,paymentProvider:v});let pr=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 E(c),c})(),lr=v==="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 E(c),c})(),Dt=e?.socialProviders??await(async()=>{n=!0;let c=nt.map(S=>({value:S,label:me[S].label,hint:`requires ${me[S].envVars.map(K=>K.name).join(" / ")}`})),d=await m.multiselect({message:"Which social login providers should the sign-in screen show?",options:c,initialValues:[],required:!1});return E(d),d})();m.log.info(f.bold("Tooling"));let gn=e?.dockerServices??await(async()=>{n=!0;let c=[...Qe].filter(H=>H!=="mailpit");ne==="smtp"&&c.push("mailpit");let d=c.map(H=>({value:H,label:Ye[H].label,hint:Ye[H].hint})),S=d.map(H=>H.value).filter(H=>!(H==="postgres"&&(y==="neon"||y==="supabase")||H==="redis"&&_==="upstash")),K=await m.multiselect({message:"Which services should we set up in Docker for you?",options:d,initialValues:S,required:!1});return E(K),K})(),hn=e?.aiTools??await(async()=>{n=!0;let c=et.map(S=>({value:S,label:vt[S].label})),d=await m.multiselect({message:"Which AI coding tools do you use?",options:c,initialValues:[],required:!1});return E(d),d})(),yn=e?.demo,Nt=An({databaseProvider:y,cacheProvider:_,paymentProvider:v,emailProvider:ne,socialProviders:Dt,demo:yn}),ht={};if(Nt.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 Nt)if(n=!0,c.secret){let d=await m.password({message:c.message,mask:"*"});E(d),typeof d=="string"&&d.trim()&&(ht[c.key]=d.trim())}else{let d=await m.text({message:c.message,placeholder:c.placeholder});E(d),typeof d=="string"&&d.trim()&&(ht[c.key]=d.trim())}}if(n){let c=[` Name: ${f.cyan(r)}`,` App name: ${f.cyan(o)}`,` Location: ${f.cyan(i)}`,` Frontend: ${f.cyan(yt[a].label)}`,` Architecture: ${f.cyan(wt[h].label)}`].join(`
|
|
4
|
+
`),d=[` Deploy target: ${f.cyan(ie[s]?.label??"Node.js / Docker")}`,` Database: ${f.cyan(q[y].label)}`,` Cache: ${f.cyan(ae[_].label)}`,gn.length>0?` Docker: ${f.cyan(gn.map(De=>Ye[De].label).join(", "))}`:` Docker: ${f.dim("none")}`].filter(Boolean).join(`
|
|
5
|
+
`),S=[v!=="none"?` Payment: ${f.cyan(Lt[v].label)} (${$})`:` Payment: ${f.dim("none")}`,` Credits: ${lr?f.cyan("Yes"):f.dim("No")}`,` AI features: ${M?f.cyan("Yes"):f.dim("No")}`,...M?[` AI sources: ${f.cyan([mn?"Built-in (credits)":null,fn?"User keys":null].filter(Boolean).join(" + ")||"none")}`,` Companion: ${L?f.cyan("Yes"):f.dim("No")}`,...L?[` Comp. source: ${f.cyan(oe==="shared"?"Shared":"Vendored")}`,oe==="shared"?` Comp. repo: ${f.cyan(un??"")}`:` Comp. name: ${f.cyan(Ct??"")}`]:[],` MCP server: ${cr?f.cyan("Yes"):f.dim("No")}`]:[],` Email: ${f.cyan(Ut[ne].label)}`,` Email stats: ${Oe?f.cyan("Yes"):f.dim("No")}`,` Multi-tenancy: ${Se?f.cyan("Yes")+` (billing: ${jt[re].label})`:f.dim("No")}`,` Blog: ${_e?f.cyan("Yes"):f.dim("No")}`,` Docs app: ${qe?f.cyan("Yes"):f.dim("No")}`,` Desktop app: ${x?f.cyan("Yes"):f.dim("No")}`,...x?[` Releases: ${f.cyan(ue?"Automatic on CI":"Manual only")}`]:[],...Ce&&!L?[` Desktop AI: ${f.cyan("Yes")} (bundles ${Ct??""})`]:[],` Rev. sharing: ${pr?f.cyan("Yes"):f.dim("No")}`,Dt.length>0?` Social login: ${f.cyan(Dt.map(De=>me[De].label).join(", "))}`:` Social login: ${f.dim("none")}`,hn.length>0?` AI tools: ${f.cyan(hn.map(De=>vt[De].label).join(", "))}`:` AI tools: ${f.dim("none")}`].join(`
|
|
6
|
+
`),K=[f.bold("Project"),c,"",f.bold("Infrastructure"),d,"",f.bold("Features"),S];if(Nt.length>0){let De=Nt.map(dr=>{let Oi=ht[dr.key]?f.green("provided"):f.dim("skipped");return` ${dr.key}: ${Oi}`}).join(`
|
|
7
|
+
`);K.push("",f.bold("Credentials"),De)}m.note(K.join(`
|
|
8
|
+
`),"Summary");let H=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(H)||!H)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:r,appName:o,projectDir:i,frontend:a,architecture:h,deploymentTarget:s,databaseProvider:y,cacheProvider:_,paymentProvider:v,emailProvider:ne,multiTenancy:Se,billingScope:re,blog:_e,emailTracking:Oe,docs:qe,desktop:x,desktopAutoRelease:ue,ai:M,companion:L,...Ct!==void 0?{companionName:Ct}:{},...oe!==void 0?{companionSource:oe}:{},...un!==void 0?{companionRepoUrl:un}:{},...sr!==void 0?{companionLocalPath:sr}:{},mcpServer:cr,aiBuiltin:mn,aiByok:fn,revenueSharing:pr,credits:lr,dockerServices:gn,aiTools:hn,socialProviders:Dt,defaultCurrency:$,...Object.keys(ht).length>0?{credentials:ht}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...yn!==void 0?{demo:yn}:{}}}import{createReadStream as Ur,existsSync as qi}from"fs";import{mkdir as Yi}from"fs/promises";import{join as Wi}from"path";import{Readable as Xi}from"stream";import{pipeline as Cn}from"stream/promises";import{extract as Zi}from"tar";import{join as je}from"path";import{homedir as Ui}from"os";var St=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",z=".generatesaas",Ie=je(z,"manifest.json"),_r=je(z,"hashes.json"),Ht=je(z,"template-hashes.json"),zt=je(z,"template"),Or=je(z,"staging"),Cr=je(z,"staging.json"),ve=je(Ui(),".generatesaas");var F=class extends Error{constructor(n,r,o){super(r);this.status=n;this.body=o}status;body;name="ApiError"};function ke(e){return{apiKey:e,baseUrl:St}}async function Ae(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.1.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 F(o.status,i,a)}return o}import{existsSync as ji,readFileSync as Mi,writeFileSync as Vi,mkdirSync as Fi}from"fs";import{dirname as Bi}from"path";import*as Pe from"@clack/prompts";function Et(){if(!ji(ve))return null;try{let e=JSON.parse(Mi(ve,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Pe.log.warning(`Found old GitHub token in ${ve}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Me(e){Fi(Bi(ve),{recursive:!0}),Vi(ve,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function ot(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=Et();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 It()}async function It(){let e=await Pe.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Pe.isCancel(e)&&(Pe.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Gi}from"fs/promises";async function Re(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Gi(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 Ae(e,"/versions")).json()}async function Pn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Ae(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(n){if(n instanceof F&&n.status===404)return null;throw n}}async function Dr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await Ae(e,`/skill/${encodeURIComponent(t)}`)).json()}function Jt(e){if(!(e instanceof F)||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 Nr(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,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,socialProviders:e.socialProviders,aiTools:e.aiTools,currency:e.defaultCurrency}}async function Rn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Ae(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function $r(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Ae(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function xn(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 Lr(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 Tn=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),_n=new Set(["pnpm-lock.yaml"]);function it(e){if(On(e))return!0;for(let t of e.split("/"))if(_n.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"]),Hi=["scripts/docs-lint.ts"],zi=["scripts/companion-export/"],Ji=["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 On(e){let t=e.split("/");for(let n of t)if(Tn.has(n))return!0;if(Hi.includes(e))return!1;for(let n of zi)if(e.startsWith(n)||`${e}/`===n)return!1;if(Ki.has(t[0]))return!0;for(let n of Ji)if(e===n||e.startsWith(n+"/"))return!0;return!1}async function qt(e,t,n){await Yi(n,{recursive:!0});let r=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(r){let s=Wi(r,`v${t}.tar.gz`);if(!qi(s))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${s} does not exist.`);await Cn(Ur(s),Dn(n));return}let o=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(o){await Cn(Ur(o),Dn(n));return}let i=await Ae(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let a=Xi.fromWeb(i.body);await Cn(a,Dn(n))}function Dn(e){return Zi({cwd:e,strip:1,filter:t=>{let n=t.replace(/^[^/]+\//,"");return n?!On(n):!0},sync:!1})}import{readdir as ca,readFile as Pt,rm as $n,writeFile as Rt}from"fs/promises";import{join as be}from"path";import{readFile as At,rm as jr}from"fs/promises";import{join as xe}from"path";import{mkdir as Qi,readdir as ea,rm as ta,rmdir as na,writeFile as ra}from"fs/promises";import{dirname as Yt,join as oa,relative as ia,sep as aa}from"path";function Ve(e){return e.split(aa).join("/")}async function Wt(e){await Qi(e,{recursive:!0})}async function p(e,t){await Wt(Yt(e)),await ra(e,t,"utf-8")}async function Nn(e,t){await ta(e,{force:!0});let n=Yt(e);for(;n!==t&&n!==Yt(n);){try{await na(n)}catch{return}n=Yt(n)}}async function Fe(e,t,n){let r=[],o=await ea(e,{withFileTypes:!0});for(let i of o){let a=oa(e,i.name),s=Ve(ia(t,a));n(s)||(i.isDirectory()?r.push(...await Fe(a,t,n)):i.isFile()&&r.push(a))}return r}function sa(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function C(e,t,n="ai",r="stripDesktopAi"){let o=sa(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 I(e,t,n,r,o){let i=await At(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 Xt(e,t,n,r){let o=/\n([\t ]+)"/.exec(await At(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 Zt(e,t,n,r){if(!(t in e))throw new Error(`${r}: expected ${n} (boilerplate drift).`);delete e[t]}function at(e){return e.frontend==="nextjs"?"next":"nuxt"}async function Mr(e,t,n,r,o,i){let a=xe(e,"docs",t);await jr(xe(a,`${n}.mdx`)),await I(xe(a,"meta.json"),` "${n}",
|
|
14
|
+
`,"",`${t} meta.json ${n} nav entry`,o),await Vr(a,t,r,o),i!==void 0&&await Fr(a,t,i,o)}async function Vr(e,t,n,r){let o=xe(e,"ai.mdx"),a=(await At(o,"utf-8")).split(`
|
|
15
15
|
`).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 I(o,`${a}
|
|
16
|
-
`,"",`${t} ai.mdx ${n} card`,r)}async function
|
|
16
|
+
`,"",`${t} ai.mdx ${n} card`,r)}async function Fr(e,t,n,r){let o=xe(e,"ai.mdx"),i=`| **${n}** |`,s=(await At(o,"utf-8")).split(`
|
|
17
17
|
`).find(u=>u.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${n}" hub-table row (boilerplate drift).`);await I(o,`${s}
|
|
18
|
-
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function
|
|
19
|
-
`,"",`${t} meta.json ${n} nav entry`,o);for(let s of r)await
|
|
20
|
-
`,n=await
|
|
21
|
-
`))}}var
|
|
22
|
-
`)}function
|
|
23
|
-
- **Payments:** ${
|
|
24
|
-
- \`apps/companion\` - the source of **${e.companionName??
|
|
25
|
-
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\`. A local checkout lives at \`${e.companionLocalPath}\` - edit and commit device-side behavior THERE, not in this repo (clone from the repo URL if the checkout is missing).`:
|
|
26
|
-
- **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
|
|
18
|
+
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function Br(e,t,n,r,o,i){let a=xe(e,"docs",t);await jr(xe(a,n),{recursive:!0}),await I(xe(a,"meta.json"),` "${n}",
|
|
19
|
+
`,"",`${t} meta.json ${n} nav entry`,o);for(let s of r)await Vr(a,t,s,o);i!==void 0&&await Fr(a,t,i,o)}async function Qt(e){let t=`import { config } from "@repo/config";
|
|
20
|
+
`,n=await At(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 pa=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function Kr(e){await Promise.all(pa.map(t=>$n(be(e,t),{recursive:!0,force:!0})))}var la=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function Hr(e){let t="removeDesktopDemoScreen";await $n(be(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let n of la){let r=be(e,n);await Rt(r,C(await Pt(r,"utf-8"),n,"demo",t))}}var da="packages/config/src/blog.ts";async function zr(e){let t=be(e,da),n=await Pt(t,"utf-8"),r=Gr(Gr(n,"blogCategories",t),"blogAuthors",t);await Rt(t,r)}function Gr(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 Jr(e){let t=be(e,"packages/i18n/translations"),n;try{n=await ca(t)}catch{return}for(let r of n){let o=be(t,r,"web.json"),i;try{i=await Pt(o,"utf-8")}catch{continue}let a=JSON.parse(i);!a.blog||a.blog.categories===void 0||(a.blog.categories={},await Rt(o,JSON.stringify(a,null," ")+`
|
|
21
|
+
`))}}var ua="packages/config/src/ai/tasks.ts";async function qr(e){let t=be(e,ua),n=await Pt(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 Rt(t,r)}async function Yr(e,t){t.includes("claude-code")||await $n(be(e,".claude"),{recursive:!0,force:!0})}async function Wr(e,t){let n=be(e,".claude","settings.json"),r;try{r=await Pt(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=>ma(i,t))),await Rt(n,JSON.stringify(o,null," ")+`
|
|
22
|
+
`)}function ma(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as Xr}from"path";var fa={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},ga={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},ha={redis:"Redis",upstash:"Upstash Redis"},ya={node:"Node.js / Docker",vercel:"Vercel"},wa={stripe:"Stripe",polar:"Polar"};function va(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=ha[e.cacheProvider],g=ya[e.deploymentTarget],l=e.paymentProvider==="none"?"":`
|
|
23
|
+
- **Payments:** ${wa[e.paymentProvider]}`,h=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",y="";e.companion&&(se(e)==="vendored"?y=`
|
|
24
|
+
- \`apps/companion\` - the source of **${e.companionName??Z(e.projectName)}**, the branded companion daemon your users install. Publish releases with \`pnpm companion:publish\`; \`generatesaas update\` flags when a re-release is due.`:e.companionLocalPath?y=`
|
|
25
|
+
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\`. A local checkout lives at \`${e.companionLocalPath}\` - edit and commit device-side behavior THERE, not in this repo (clone from the repo URL if the checkout is missing).`:y=`
|
|
26
|
+
- **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 _=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`.",v=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
|
|
27
27
|
|
|
28
28
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
29
29
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -51,10 +51,10 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
51
51
|
|
|
52
52
|
- **Frontend:** ${n} ${a}
|
|
53
53
|
- **API:** Hono, RPC-typed. ${s}
|
|
54
|
-
- **Database:** Drizzle ORM + ${
|
|
54
|
+
- **Database:** Drizzle ORM + ${fa[e.databaseProvider]}
|
|
55
55
|
- **Cache + jobs:** ${u} + Inngest
|
|
56
56
|
- **Auth:** Better Auth${l}
|
|
57
|
-
- **Email:** ${
|
|
57
|
+
- **Email:** ${ga[e.emailProvider]}
|
|
58
58
|
- **Deploy:** ${g}
|
|
59
59
|
|
|
60
60
|
## Where things live (extend these - don't reinvent)
|
|
@@ -65,8 +65,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
65
65
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
66
66
|
- \`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\`.
|
|
67
67
|
- \`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.
|
|
68
|
-
- \`${r}\` - the ${n} app (${o}).${
|
|
69
|
-
- \`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/\`${
|
|
68
|
+
- \`${r}\` - the ${n} app (${o}).${y}
|
|
69
|
+
- \`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}.
|
|
70
70
|
|
|
71
71
|
## Code style
|
|
72
72
|
|
|
@@ -83,8 +83,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
83
83
|
|
|
84
84
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
85
85
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
86
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${
|
|
87
|
-
- ${
|
|
86
|
+
- **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.
|
|
87
|
+
- ${v}
|
|
88
88
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
89
89
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
90
90
|
|
|
@@ -95,14 +95,14 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
95
95
|
## This project
|
|
96
96
|
|
|
97
97
|
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\`.
|
|
98
|
-
`}async function
|
|
99
|
-
`)}import{join as
|
|
98
|
+
`}async function Zr(e){await p(Xr(e.projectDir,"AGENTS.md"),va(e)),await p(Xr(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
99
|
+
`)}import{join as ka}from"path";var ba={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function Sa(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=ba[e.databaseProvider],a=Mt(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
|
|
100
100
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
101
101
|
- API: http://localhost:3010
|
|
102
102
|
- Inngest dev server: http://127.0.0.1:8288`,g=a?`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
103
103
|
`:"",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
|
|
104
104
|
|
|
105
|
-
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).":""}`,
|
|
105
|
+
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}
|
|
106
106
|
|
|
107
107
|
${s}
|
|
108
108
|
|
|
@@ -158,19 +158,19 @@ pnpm dlx generatesaas eject
|
|
|
158
158
|
|
|
159
159
|
## Updates
|
|
160
160
|
|
|
161
|
-
${
|
|
162
|
-
`}async function
|
|
163
|
-
`)}async function
|
|
161
|
+
${h}
|
|
162
|
+
`}async function Qr(e){await p(ka(e.projectDir,"README.md"),Sa(e))}import{access as Ia,readFile as Aa}from"fs/promises";import{join as st}from"path";import{join as Ea}from"path";function Ln(e,t){let n=Vt(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 eo(e){if(!we(e)||e.demo||Y(e)==="shared")return;if(!e.companionName)throw new Error("generateCompanionBrand: this project ships a companion daemon but options.companionName is missing.");let t=Ln(e.companionName,e.baseUrl);await p(Ea(e.projectDir,"apps/companion/brand.json"),JSON.stringify(t,null,2)+`
|
|
163
|
+
`)}async function Pa(e,t,n){let r=st(e,"apps/electron/dev-app-update.yml");try{await Ia(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await p(r,`provider: generic
|
|
164
164
|
url: ${t}
|
|
165
165
|
updaterCacheDirName: ${n}
|
|
166
|
-
`)}function
|
|
167
|
-
`)}async function
|
|
166
|
+
`)}function Ra(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function xa(e,t){let n=Vt(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${n.replace(/-/g,"")}`,productName:e,protocol:n}}async function Ta(e){if(!e.companion&&!we(e))return'{ enabled: false, clientId: "companion" }';let t;if(e.demo)t=JSON.parse(await Aa(st(e.projectDir,"apps/companion/brand.json"),"utf8"));else if(Y(e)==="shared"){let r=await br(e),o=ce(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=Ln(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(`
|
|
167
|
+
`)}async function to(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=Ra(o),a=e.demo?"false":"true",s=e.demo?`{
|
|
168
168
|
enableInDev: true,
|
|
169
169
|
chatwoot: {
|
|
170
170
|
baseUrl: "https://support.alexchelan.com",
|
|
171
171
|
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
172
172
|
}
|
|
173
|
-
}`:"{}",u=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",g=
|
|
173
|
+
}`:"{}",u=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",g=xa(t,i),l=`https://cdn.${i}/desktop`,h=await Ta(e),y=`{ enabled: ${e.mcpServer} }`,_=`import type { AppConfig } from "@repo/config/types";
|
|
174
174
|
import { desktopConfig } from "./desktop.mjs";
|
|
175
175
|
import { supportConfig } from "./support.mjs";
|
|
176
176
|
import { tenancyConfig } from "./tenancy-flags.mjs";
|
|
@@ -283,7 +283,7 @@ export const config: AppConfig = {
|
|
|
283
283
|
}`:`{
|
|
284
284
|
base: "${e.defaultCurrency}",
|
|
285
285
|
list: [
|
|
286
|
-
{ symbol: "${
|
|
286
|
+
{ symbol: "${Ne[e.defaultCurrency].symbol}", name: "${Ne[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Ne[e.defaultCurrency].place}", space: ${Ne[e.defaultCurrency].space} }
|
|
287
287
|
],
|
|
288
288
|
countryMap: {
|
|
289
289
|
default: "${e.defaultCurrency}"
|
|
@@ -331,9 +331,9 @@ export const config: AppConfig = {
|
|
|
331
331
|
},
|
|
332
332
|
desktop: desktopConfig,
|
|
333
333
|
// Companion: your vendored companion daemon (apps/companion) that your users install to run their own subscription CLIs. Off by default.
|
|
334
|
-
companion: ${
|
|
334
|
+
companion: ${h},
|
|
335
335
|
// Outward MCP server exposing the capability layer to external agents. Off by default.
|
|
336
|
-
mcpServer: ${
|
|
336
|
+
mcpServer: ${y},
|
|
337
337
|
seo: {
|
|
338
338
|
description: "Production-ready SaaS application",
|
|
339
339
|
foundingDate: "${new Date().getFullYear()}-01-01"
|
|
@@ -374,7 +374,7 @@ export * from "./pricing";
|
|
|
374
374
|
export * from "./roles";
|
|
375
375
|
export * from "./section-tabs";
|
|
376
376
|
export * from "./tenancy";
|
|
377
|
-
`,
|
|
377
|
+
`,v=st(e.projectDir,"packages/config/src/index.ts");await p(v,_),await p(st(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
378
378
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
379
379
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
380
380
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -421,7 +421,7 @@ export const desktopConfig = {
|
|
|
421
421
|
connectionLock: false
|
|
422
422
|
}
|
|
423
423
|
};
|
|
424
|
-
`),await p(
|
|
424
|
+
`),await p(st(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
|
|
425
425
|
// TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
|
|
426
426
|
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
427
427
|
|
|
@@ -430,14 +430,14 @@ export const tenancyConfig = ${e.multiTenancy?`{
|
|
|
430
430
|
organizationLimit: 5,
|
|
431
431
|
billingScope: "${e.billingScope}"
|
|
432
432
|
}`:"{ multiTenant: false }"};
|
|
433
|
-
`),await p(
|
|
433
|
+
`),await p(st(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
|
|
434
434
|
// the TypeScript config index reads it directly (the Electron main + renderer and
|
|
435
435
|
// the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
|
|
436
436
|
// index re-exports this as config.support.
|
|
437
437
|
|
|
438
438
|
export const supportConfig = ${s};
|
|
439
|
-
`),e.desktop&&await
|
|
440
|
-
`)}async function
|
|
439
|
+
`),e.desktop&&await Pa(e.projectDir,l,`${g.protocol}-updater`)}import{join as _a}from"path";function Oa(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function Un(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(`
|
|
440
|
+
`)}async function no(e){let t=_a(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let _=`import type { PricingConfig } from "@repo/config/types";
|
|
441
441
|
|
|
442
442
|
export const pricingConfig: PricingConfig = {
|
|
443
443
|
defaultPlan: "free",
|
|
@@ -466,7 +466,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
466
466
|
credits: { enabled: false },
|
|
467
467
|
products: { enabled: false, items: [] }
|
|
468
468
|
};
|
|
469
|
-
`;await p(t,
|
|
469
|
+
`;await p(t,_);return}let r=e.paymentProvider,o=Oa(r),i=e.credits,a=!!e.ai,s=Un({credits:5,rateLimit:100,withCredits:i,...a&&{maxSchedules:3}}),u=Un({credits:10,rateLimit:1e3,withCredits:i,...a&&{maxSchedules:10}}),g=Un({credits:50,rateLimit:5e3,withCredits:i}),l=n==="USD"?"":` // !! ${n} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
470
470
|
// !! USD), but your plan prices and credit purchases are denominated in ${n}. Verify that the
|
|
471
471
|
// !! ${n} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
472
472
|
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
@@ -475,12 +475,12 @@ export const pricingConfig: PricingConfig = {
|
|
|
475
475
|
!! plan prices and credit purchases are denominated in ${n}. At the shipped economics 1 credit
|
|
476
476
|
!! carries ~0.42 USD of AI cost - verify every ${n} price still covers it (see the comment on the
|
|
477
477
|
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
478
|
-
`);let
|
|
478
|
+
`);let h=i?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
479
479
|
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
480
480
|
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
481
481
|
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
482
482
|
// full utilization runs you at a loss.
|
|
483
|
-
${l} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",
|
|
483
|
+
${l} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",y=`import type { PricingConfig } from "@repo/config/types";
|
|
484
484
|
|
|
485
485
|
export const pricingConfig: PricingConfig = {
|
|
486
486
|
defaultPlan: "free",
|
|
@@ -564,17 +564,17 @@ ${o}
|
|
|
564
564
|
${g}
|
|
565
565
|
}
|
|
566
566
|
],
|
|
567
|
-
${
|
|
567
|
+
${h},
|
|
568
568
|
products: {
|
|
569
569
|
enabled: false,
|
|
570
570
|
items: []
|
|
571
571
|
}
|
|
572
572
|
};
|
|
573
|
-
`;await p(t,
|
|
574
|
-
`)}function
|
|
575
|
-
`)}async function
|
|
576
|
-
`+
|
|
577
|
-
`+
|
|
573
|
+
`;await p(t,y)}var Ca={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"}]};function Da(e){let t=me[e];return t.envVars.map((n,r)=>({key:n.name,...r===0?{comment:`# TODO: Add your ${t.label} OAuth credentials`}:{}}))}var Na={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 ct(e,t){return t?e.map(n=>{let r=t[n.key];return r?{...n,defaultValue:r,comment:void 0}:n}):e}function pt(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 jn(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function oo(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function $a(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 en(e,t,n,r){e.push(r==="example"?`${t}=`:`${t}=${n}`)}function ro(e,t){let n=t==="example"?void 0:e.credentials,{apiUrl:r,baseUrl:o}=oo(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"),pt(ct(q[e.databaseProvider].envVars,n),i),i.push("","# Cache"),pt(ct(ae[e.cacheProvider].envVars,n),i),i.push("","# Authentication"),t==="example"&&i.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),en(i,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),i.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),en(i,"CONTENT_API_KEY",jn(32),t),i.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),en(i,"INNGEST_EVENT_KEY",jn(32),t),en(i,"INNGEST_SIGNING_KEY",jn(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=Ca[e.emailProvider];if(a&&(i.push("","# Email"),pt(ct(a,n),i)),e.paymentProvider!=="none"){let s=Na[e.paymentProvider];s&&(i.push("","# Payment"),pt(ct(s,n),i))}if(e.socialProviders.length>0){i.push("","# Social auth");for(let s of e.socialProviders)pt(ct(Da(s),n),i)}return e.demo&&(i.push("","# Captcha (Cloudflare Turnstile)"),pt(ct([{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(`
|
|
574
|
+
`)}function La(e){let{apiUrl:t}=oo(e),n=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",r=["# API Configuration",`${n}=${t}`],o=$a(e);return o&&e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${n}=${o.backend}`),r.push(""),r.join(`
|
|
575
|
+
`)}async function io(e){let t=La(e);await p(`${e.projectDir}/.env`,t+`
|
|
576
|
+
`+ro(e,"env")),await p(`${e.projectDir}/.env.example`,t+`
|
|
577
|
+
`+ro(e,"example"))}import{join as Ua}from"path";async function ao(e){let t=[...e.dockerServices];if(q[e.databaseProvider].managed&&(t=t.filter(i=>i!=="postgres")),ae[e.cacheProvider].managed&&(t=t.filter(i=>i!=="redis")),t.length===0)return!1;let n=[],r=[];t.includes("postgres")&&(n.push(` postgres:
|
|
578
578
|
image: postgres:18-alpine
|
|
579
579
|
ports:
|
|
580
580
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -618,8 +618,8 @@ ${n.join(`
|
|
|
618
618
|
volumes:
|
|
619
619
|
${r.join(`
|
|
620
620
|
`)}
|
|
621
|
-
`),await p(
|
|
622
|
-
`)}import{join as
|
|
621
|
+
`),await p(Ua(e.projectDir,"infra/docker-compose.yml"),o),!0}import{join as ja}from"path";function Ma(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 Va(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 so(e){let t={version:"0.2.0",configurations:Ma(e),compounds:Va(e)};await p(ja(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
622
|
+
`)}import{join as Fa}from"path";async function co(e){if(e.architecture!=="separate")return;await p(Fa(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
|
|
623
623
|
import app from "@repo/api";
|
|
624
624
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
625
625
|
|
|
@@ -650,12 +650,12 @@ bootstrap().catch((error) => {
|
|
|
650
650
|
logger.error("[Backend] Fatal error", error);
|
|
651
651
|
process.exit(1);
|
|
652
652
|
});
|
|
653
|
-
`)}import{readFile as
|
|
654
|
-
export const pool = db.$client;`,
|
|
653
|
+
`)}import{readFile as Ba}from"fs/promises";import{join as Ga}from"path";var Mn='import { drizzle } from "drizzle-orm/node-postgres";',Vn=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
654
|
+
export const pool = db.$client;`,Ka={postgres:{importLine:Mn,instantiation:Vn},neon:{importLine:`import { neon } from "@neondatabase/serverless";
|
|
655
655
|
import { drizzle } from "drizzle-orm/neon-http";`,instantiation:`const sql = neon(parsed.data.DATABASE_URL);
|
|
656
656
|
export const db = drizzle(sql, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
657
657
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
658
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
658
|
+
export const db = drizzle(client, { schema });`}};async function po(e){let t=Ga(e.projectDir,"packages/database/src/index.ts"),n=await Ba(t,"utf-8");if(!n.includes(Mn)||!n.includes(Vn))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=Ka[e.databaseProvider],o=n.replace(Mn,r.importLine).replace(Vn,r.instantiation);await p(t,o)}import{join as tn}from"path";async function lo(e){switch(e.cacheProvider){case"redis":await Ha(e),await za(e);break;case"upstash":await Ja(e),await qa(e);break}}async function Ha(e){await p(tn(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
659
659
|
import { Redis } from "ioredis";
|
|
660
660
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
661
661
|
import { env } from "./env";
|
|
@@ -784,7 +784,7 @@ export async function closeRedis() {
|
|
|
784
784
|
closed = true;
|
|
785
785
|
}
|
|
786
786
|
}
|
|
787
|
-
`)}async function
|
|
787
|
+
`)}async function za(e){await p(tn(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
788
788
|
import { redis } from "./redis";
|
|
789
789
|
|
|
790
790
|
export class MutexTimeoutError extends Error {
|
|
@@ -821,7 +821,7 @@ export async function withMutex<T>(
|
|
|
821
821
|
await mutex.release();
|
|
822
822
|
}
|
|
823
823
|
}
|
|
824
|
-
`)}async function
|
|
824
|
+
`)}async function Ja(e){await p(tn(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
825
825
|
import type { Store } from "hono-rate-limiter";
|
|
826
826
|
import { env } from "./env";
|
|
827
827
|
|
|
@@ -939,7 +939,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
939
939
|
|
|
940
940
|
/** No persistent connection to close with Upstash REST. */
|
|
941
941
|
export async function closeRedis(): Promise<void> {}
|
|
942
|
-
`)}async function
|
|
942
|
+
`)}async function qa(e){await p(tn(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
943
943
|
import { redis } from "./redis";
|
|
944
944
|
|
|
945
945
|
export class MutexTimeoutError extends Error {
|
|
@@ -984,7 +984,7 @@ export async function withMutex<T>(
|
|
|
984
984
|
await lock.release();
|
|
985
985
|
}
|
|
986
986
|
}
|
|
987
|
-
`)}async function
|
|
987
|
+
`)}async function uo(e){await p(`${e.projectDir}/packages/runtime/src/env.ts`,Ya(e))}function Ya(e){return`import { z } from "zod";
|
|
988
988
|
|
|
989
989
|
const EnvSchema = z.object({
|
|
990
990
|
NODE_ENV: z.enum(["development", "production"]).default("development"),
|
|
@@ -1108,13 +1108,13 @@ export const env = (() => {
|
|
|
1108
1108
|
const parsedApiUrl = new URL(env.API_URL);
|
|
1109
1109
|
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1110
1110
|
export const apiOrigin = parsedApiUrl.origin;
|
|
1111
|
-
`}import{readFile as
|
|
1112
|
-
`)}function
|
|
1113
|
-
`)}var
|
|
1114
|
-
`))}}import{readFile as
|
|
1115
|
-
`);let i=
|
|
1111
|
+
`}import{readFile as Wa}from"fs/promises";import{join as le}from"path";var nn={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function dt(e){let t=await Wa(e,"utf-8");return JSON.parse(t)}async function ut(e,t){await p(e,JSON.stringify(t,null," ")+`
|
|
1112
|
+
`)}function xt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function lt(e,t,n,r=!1){let o=r?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=n}async function mo(e){await Xa(e),await Za(e),await Qa(e),await es(e),e.frontend==="nextjs"?await ns(e):await ts(e)}async function Xa(e){let t=le(e.projectDir,"packages/api/package.json"),n=await dt(t);xt(n,["sharp","@types/sharp"]),await ut(t,n)}async function Za(e){let t=le(e.projectDir,"packages/runtime/package.json"),n=await dt(t);e.cacheProvider==="upstash"&&(xt(n,["ioredis","rate-limit-redis","redis-semaphore"]),lt(n,"@upstash/redis",nn["@upstash/redis"]),lt(n,"@upstash/lock",nn["@upstash/lock"])),await ut(t,n)}async function Qa(e){let t=le(e.projectDir,"packages/database/package.json"),n=await dt(t);e.databaseProvider==="neon"?(xt(n,["pg","@types/pg"]),lt(n,"@neondatabase/serverless",nn["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(xt(n,["pg","@types/pg"]),lt(n,"postgres",nn.postgres)),await ut(t,n)}async function es(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/backend/package.json"),n=await dt(t);e.deploymentTarget!=="node"&&xt(n,["@hono/node-server"]),await ut(t,n)}async function ts(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/web-nuxt");await Nn(le(t,"server/api/[...paths].ts"),t);let n=le(t,"package.json"),r=await dt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],lt(r,"@repo/api",o,!0)),await ut(n,r)}async function ns(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/web-next");await Nn(le(t,"app/api/[[...rest]]/route.ts"),t);let n=le(t,"package.json"),r=await dt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],lt(r,"@repo/api",o,!0)),await ut(n,r)}import{readFile as go}from"fs/promises";import{join as ho}from"path";async function yo(e){let t=ho(e.projectDir,"turbo.json"),n;try{n=await go(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," ")+`
|
|
1113
|
+
`)}var rs=["base.json","node.json","next.json"],fo="GenerateSaaS ";async function wo(e){if(!e.demo)for(let t of rs){let n=ho(e.projectDir,"tooling/typescript",t),r;try{r=await go(n,"utf-8")}catch{continue}let o=JSON.parse(r);typeof o.display!="string"||!o.display.startsWith(fo)||(o.display=o.display.slice(fo.length),await p(n,JSON.stringify(o,null," ")+`
|
|
1114
|
+
`))}}import{readFile as os,rm as is}from"fs/promises";import{existsSync as vo}from"fs";import{join as ko}from"path";async function bo(e){if(e.frontend==="nuxt")return;let t=ko(e.projectDir,"packages/i18n/package.json");if(!vo(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await os(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," ")+`
|
|
1115
|
+
`);let i=ko(e.projectDir,"packages/i18n/nuxt");if(r&&!vo(i))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${i} is missing - did the i18n Nuxt module move?`);await is(i,{recursive:!0,force:!0})}import{readFile as Eo,rm as as}from"fs/promises";import{join as rn}from"path";async function Io(e){e.cacheProvider==="upstash"&&await Promise.all([So(rn(e.projectDir,"packages/runtime/tests/setup.ts")),So(rn(e.projectDir,"packages/mail/tests/setup.ts")),ss(e.projectDir),as(rn(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function So(e){let t;try{t=await Eo(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",
|
|
1116
1116
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1117
|
-
`);n!==t&&await p(e,n)}async function
|
|
1117
|
+
`);n!==t&&await p(e,n)}async function ss(e){let t=rn(e,"packages/api/tests/setup.ts"),n;try{n=await Eo(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",
|
|
1118
1118
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1119
1119
|
`),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",
|
|
1120
1120
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1135,8 +1135,8 @@ vi.mock("@upstash/lock", () => {
|
|
|
1135
1135
|
return { Lock };
|
|
1136
1136
|
});
|
|
1137
1137
|
|
|
1138
|
-
$1`),r!==n&&await p(t,r)}import{readdir as
|
|
1139
|
-
`,"","internal router mcp import",n),await I(i,'\n// Outward MCP server: the protected `/mcp` JSON-RPC endpoint, gated on `config.mcpServer`. Off by\n// default, so the route is absent entirely when disabled. Its OAuth `.well-known` discovery is NOT\n// here: agents resolve those documents against the site origin, so they mount at the app root (see\n// `mcpDiscoveryRoutes` in `src/index.ts`). It is not chained into the typed router above: external\n// agents (not the typed RPC client) call it, so it needs no `AppType` inference, and gating it\n// keeps the feature truly inert when off.\nif (config.mcpServer?.enabled) {\n app.route("/", mcpRoutes);\n}\n',"","internal router mcp mount",n),await
|
|
1138
|
+
$1`),r!==n&&await p(t,r)}import{readdir as zn,readFile as V,rm as U}from"fs/promises";import{join as w}from"path";import{readFile as Ao,readdir as cs,rm as Te}from"fs/promises";import{join as B}from"path";async function Fn(e){if(e.mcpServer)return;let t=e.projectDir,n="stripMcpServer";await Te(B(t,"packages/api/src/routes/internal/ai/mcp.ts")),await Te(B(t,"packages/api/tests/routes/mcp.test.ts")),await Te(B(t,"packages/auth/src/mcp.ts"));let r=e.frontend==="nextjs",o=B(t,r?"apps/web-next/app/.well-known":"apps/web-nuxt/server/routes/.well-known");await Te(B(o,"oauth-authorization-server"),{recursive:!0}),await Te(B(o,"oauth-protected-resource"),{recursive:!0}),r||(await Te(B(o,"oauth-authorization-server.ts")),await Te(B(o,"oauth-protected-resource.ts"))),(await cs(o)).length===0&&await Te(o,{recursive:!0});let i=B(t,"packages/api/src/routes/internal/index.ts");await I(i,`import mcpRoutes from "./ai/mcp";
|
|
1139
|
+
`,"","internal router mcp import",n),await I(i,'\n// Outward MCP server: the protected `/mcp` JSON-RPC endpoint, gated on `config.mcpServer`. Off by\n// default, so the route is absent entirely when disabled. Its OAuth `.well-known` discovery is NOT\n// here: agents resolve those documents against the site origin, so they mount at the app root (see\n// `mcpDiscoveryRoutes` in `src/index.ts`). It is not chained into the typed router above: external\n// agents (not the typed RPC client) call it, so it needs no `AppType` inference, and gating it\n// keeps the feature truly inert when off.\nif (config.mcpServer?.enabled) {\n app.route("/", mcpRoutes);\n}\n',"","internal router mcp mount",n),await Qt(i);let a=B(t,"packages/api/src/index.ts");await I(a,`import { mcpDiscoveryRoutes } from "./routes/internal/ai/mcp";
|
|
1140
1140
|
`,"","api index mcp discovery import",n),await I(a,`
|
|
1141
1141
|
// The outward MCP server's OAuth discovery documents, mounted at the APP ROOT (not under the API
|
|
1142
1142
|
// base path): an MCP agent resolves \`/.well-known/oauth-*\` against the site origin (RFC 8414 /
|
|
@@ -1146,7 +1146,7 @@ $1`),r!==n&&await p(t,r)}import{readdir as Hn,readFile as M,rm as U}from"fs/prom
|
|
|
1146
1146
|
if (config.mcpServer?.enabled) {
|
|
1147
1147
|
app.route("/", mcpDiscoveryRoutes);
|
|
1148
1148
|
}
|
|
1149
|
-
`,"","api index mcp discovery mount",n);let s=
|
|
1149
|
+
`,"","api index mcp discovery mount",n);let s=B(t,"packages/auth/src/config.ts");await I(s,` magicLink,
|
|
1150
1150
|
mcp,
|
|
1151
1151
|
organization,`,` magicLink,
|
|
1152
1152
|
organization,`,"auth config mcp plugin import",n),await I(s,` // Outward MCP server: turns Better Auth into an OAuth 2.1 provider so an
|
|
@@ -1156,35 +1156,35 @@ if (config.mcpServer?.enabled) {
|
|
|
1156
1156
|
...(config.mcpServer?.enabled
|
|
1157
1157
|
? [mcp({ loginPage: \`\${config.baseUrl}\${config.routes.auth}/login\` })]
|
|
1158
1158
|
: []),
|
|
1159
|
-
`,"","auth config mcp plugin block",n);let u=
|
|
1160
|
-
`);let l=
|
|
1161
|
-
`);let
|
|
1162
|
-
`,"","configuration.mdx mcpServer config-table row",n),e.companion){let
|
|
1159
|
+
`,"","auth config mcp plugin block",n);let u=B(t,"packages/auth/package.json"),g=JSON.parse(await Ao(u,"utf-8"));if(!g.exports)throw new Error(`${n}: expected an exports map in packages/auth/package.json (boilerplate drift).`);Zt(g.exports,"./mcp",'the "./mcp" export in packages/auth/package.json',n),await p(u,JSON.stringify(g,null," ")+`
|
|
1160
|
+
`);let l=B(t,"packages/api/package.json"),h=JSON.parse(await Ao(l,"utf-8"));if(!h.dependencies)throw new Error(`${n}: expected dependencies in packages/api/package.json (boilerplate drift).`);Zt(h.dependencies,"@mastra/mcp","@mastra/mcp in packages/api dependencies",n),Zt(h.dependencies,"@modelcontextprotocol/sdk","@modelcontextprotocol/sdk in packages/api dependencies",n),await p(l,JSON.stringify(h,null," ")+`
|
|
1161
|
+
`);let y=at(e);if(await Mr(t,y,"companion-agent-mcp",`/${y}/companion-agent-mcp`,n,"MCP"),await I(B(t,`docs/${y}/configuration.mdx`),`| \`mcpServer.enabled\` | \`false\` (requires \`ai\`) | Outward MCP server URL + the **MCP** settings tab - see [external agent (MCP)](/${y}/companion-agent-mcp) |
|
|
1162
|
+
`,"","configuration.mdx mcpServer config-table row",n),e.companion){let _=B(t,`docs/${y}/companion/index.mdx`);await I(_,`It is the user-owned counterpart to the [external agent (MCP)](/${y}/companion-agent-mcp): the MCP server lets a third-party agent reach into your app, while the companion daemon runs on the user's own hardware and reaches out to your app over authenticated HTTP.
|
|
1163
1163
|
|
|
1164
|
-
`,"","companion index.mdx MCP counterpart paragraph",n),await I(
|
|
1165
|
-
`,"","companion index.mdx MCP card",n)}}import{readFile as
|
|
1164
|
+
`,"","companion index.mdx MCP counterpart paragraph",n),await I(_,` <Card title="External Agent (MCP)" href="/${y}/companion-agent-mcp" description="The other side - expose your app's capabilities to an external always-on agent over MCP." />
|
|
1165
|
+
`,"","companion index.mdx MCP card",n)}}import{readFile as Ro,rm as O}from"fs/promises";import{join as R}from"path";import{readFile as on}from"fs/promises";import{join as Tt}from"path";async function Po(e,t){let n=Tt(e,"packages/api/src/routes/internal/index.ts");await p(n,C(await on(n,"utf-8"),"internal router","companion",t)),await Qt(n);let r=Tt(e,"packages/api/src/ai/schedule-runner.ts");await p(r,C(await on(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=Tt(e,a);await p(s,C(await on(s,"utf-8"),a,"companion",t))}let o=Tt(e,"packages/api/src/ai/settings-store.ts");await I(o,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1166
1166
|
|
|
1167
1167
|
`,"","settings-store.ts relay import",t),await I(o," * - COMPANION (when `config.companion.enabled`): a well-formed companion key\n * `<connectionId>@<deviceId>[@<modelId>]` persists as-is (the run path resolves it, and the\n * daemon handles an offline device).\n","","settings-store.ts COMPANION docstring bullet",t),await I(o,` if (config.companion?.enabled === true && parseCompanionKey(key) !== null) {
|
|
1168
1168
|
return key;
|
|
1169
1169
|
}
|
|
1170
|
-
`,"","settings-store.ts companion-key branch",t);let i=
|
|
1171
|
-
`,"","configuration.mdx companion config-table row",n)}async function
|
|
1172
|
-
`),await I(
|
|
1173
|
-
`,"","desktop index companion card",n)}async function
|
|
1174
|
-
`),o}async function
|
|
1175
|
-
`))}async function
|
|
1176
|
-
`)}await
|
|
1170
|
+
`,"","settings-store.ts companion-key branch",t);let i=Tt(e,"packages/api/tests/ai/settings-store.test.ts");await p(i,C(await on(i,"utf-8"),"settings-store.test.ts","companion",t))}var ps=["companion:export","companion:verify","companion:publish"];async function Bn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await O(R(t,"packages/api/src/relay"),{recursive:!0}),await O(R(t,"packages/api/src/companion"),{recursive:!0}),await O(R(t,"packages/api/src/ai/companion-model.ts")),await O(R(t,"packages/api/tests/relay"),{recursive:!0}),await O(R(t,"packages/api/tests/companion"),{recursive:!0}),await O(R(t,"packages/api/src/routes/internal/companion.ts")),await O(R(t,"packages/api/src/routes/internal/companion-transport.ts")),await O(R(t,"packages/api/tests/routes/companion.test.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-harness.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-poll.test.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await O(R(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await O(R(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await O(R(t,"packages/api/tests/ai/companion-model.test.ts")),await O(R(t,"packages/api/tests/ai/companion-chat.test.ts")),await O(R(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await O(R(t,"packages/api/tests/helpers/redis-mock.ts"));let r=R(t,"packages/api/package.json"),o=JSON.parse(await Ro(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 Xt(r,o," ",n),await Po(t,n);let i=at(e);await Br(t,i,"companion",[`/${i}/companion`,`/${i}/companion/publishing`],n,"Companions"),await I(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),await I(R(t,`docs/${i}/configuration.mdx`),`| \`companion.enabled\` | \`false\` (requires \`ai\`) | Companion daemon pairing + the **Companions** settings tab - see [companion](/${i}/companion) |
|
|
1171
|
+
`,"","configuration.mdx companion config-table row",n)}async function Gn(e){if(Bt(e))return;let t=e.projectDir;await O(R(t,"apps/companion"),{recursive:!0}),await O(R(t,"scripts/companion-export"),{recursive:!0}),await ls(t)}async function Kn(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="stripDesktopCompanionDoc";await O(R(t,"docs/desktop/companion.mdx"));let r=R(t,"docs/desktop/meta.json"),o=JSON.parse(await Ro(r,"utf-8"));if(!o.pages.includes("companion"))throw new Error(`${n}: expected the desktop meta.json companion nav entry, but it was missing (boilerplate drift).`);o.pages=o.pages.filter(i=>i!=="companion"),await p(r,`${JSON.stringify(o,null,2)}
|
|
1172
|
+
`),await I(R(t,"docs/desktop/index.mdx"),` <Card href="/desktop/companion" title="Companion setup" description="The companion ships inside the app and runs as a local daemon, consent-first - no separate install, and pairing is optional." />
|
|
1173
|
+
`,"","desktop index companion card",n)}async function ls(e){await Hn(e,ps)}var ds=new Set(["ci.yml","desktop-release.yml"]),us={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"]},ms=["@repo/ai","@repo/agent-core","@repo/agent-core-types","ai","@ai-sdk/react","@homebridge/node-pty-prebuilt-multiarch","@xterm/xterm","@xterm/addon-fit"],fs=["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 xo(e){let t=w(e.projectDir,".github/workflows"),n=await zn(t).catch(()=>[]);for(let r of n)ds.has(r)||await U(w(t,r),{recursive:!0,force:!0})}async function Hn(e,t){let n=w(e,"package.json"),r=JSON.parse(await V(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," ")+`
|
|
1174
|
+
`),o}async function To(e){let t=[...fs];Mt(e)||t.push("infra","infra:stop"),await Hn(e.projectDir,t)}async function _o(e){let t=w(e.projectDir,"package.json"),n=await V(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," ")+`
|
|
1175
|
+
`))}async function Oo(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await U(w(e.projectDir,t),{recursive:!0,force:!0})}async function Co(e){e.docs||await U(w(e.projectDir,"apps/docs"),{recursive:!0})}async function Do(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await U(w(e.projectDir,t),{recursive:!0,force:!0}),await U(w(e.projectDir,"docs/index.mdx")),!e.desktop)await U(w(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!(e.desktop&&e.ai)){await U(w(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=w(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await V(n,"utf-8"));r.pages=r.pages.filter(o=>o!=="ai"),await p(n,`${JSON.stringify(r,null,2)}
|
|
1176
|
+
`)}await gs(e)}async function gs(e){let t=e.projectDir,n="stripUnusedDocsSilo",r=at(e),o=w(t,`docs/${r}/configuration.mdx`),i=e.desktop&&e.ai;e.desktop||(await I(o,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",n),await I(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 I(w(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 I(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) - see [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",n),e.companion&&(await I(w(t,`docs/${r}/companion/index.mdx`),`## Set up from the desktop app
|
|
1177
1177
|
|
|
1178
1178
|
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).
|
|
1179
1179
|
|
|
1180
|
-
`,"","companion index.mdx desktop-setup section",n),await I(
|
|
1180
|
+
`,"","companion index.mdx desktop-setup section",n),await I(w(t,`docs/${r}/companion/terminal.mdx`),`## In the desktop app
|
|
1181
1181
|
|
|
1182
1182
|
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).
|
|
1183
1183
|
|
|
1184
|
-
`,"","companion terminal.mdx desktop-panel section",n))),e.desktop&&!e.ai&&await I(
|
|
1185
|
-
`,"","desktop index.mdx AI card",n)}async function
|
|
1186
|
-
`),await
|
|
1187
|
-
`)}}function
|
|
1184
|
+
`,"","companion terminal.mdx desktop-panel section",n))),e.desktop&&!e.ai&&await I(w(t,"docs/desktop/index.mdx"),` <Card href="/desktop/ai" title="AI agents" description="Turn the user's own AI subscription or API key into a workspace-scoped agent." />
|
|
1185
|
+
`,"","desktop index.mdx AI card",n)}async function No(e){if(e.desktop)return;await U(w(e.projectDir,"apps/electron"),{recursive:!0});let t=w(e.projectDir,"packages/i18n/translations");for(let o of await zn(t,{withFileTypes:!0}))o.isDirectory()&&await U(w(t,o.name,"desktop.json"),{force:!0});await U(w(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of us[e.frontend])await U(w(e.projectDir,o),{recursive:!0});await U(w(e.projectDir,"packages/utils/src/desktop-download.ts")),await U(w(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=w(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await V(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 Xt(n,r," ","stripDesktopApp")}async function $o(e){Bt(e)||await U(w(e.projectDir,"packages/agent-core"),{recursive:!0})}function _t(e,t,n,r){let o=e.indexOf(t);if(o===-1)throw new Error(`stripDesktopAi: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(e.indexOf(t,o+t.length)!==-1)throw new Error(`stripDesktopAi: the ${r} seam appears more than once (boilerplate drift).`);return e.slice(0,o)+n+e.slice(o+t.length)}async function Lo(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="apps/electron";for(let a of[`${n}/src/renderer/screens/agents`,`${n}/src/renderer/screens/chat.tsx`,`${n}/src/renderer/screens/schedules.tsx`,`${n}/src/renderer/screens/settings/models.tsx`,`${n}/src/renderer/screens/settings/tasks.tsx`,`${n}/src/renderer/screens/settings/mcp.tsx`,`${n}/src/renderer/screens/settings/integrations.tsx`,`${n}/src/renderer/screens/settings/integration-add-dialog.tsx`,`${n}/src/renderer/screens/settings/integration-types.ts`,`${n}/src/renderer/screens/settings/settings-tabs.tsx`,`${n}/src/renderer/screens/settings/settings-tab-ids.ts`,`${n}/src/renderer/screens/settings/connected-cache.ts`,`${n}/src/renderer/components/section-tabs.tsx`,`${n}/src/renderer/hooks/use-ai-terminal.ts`,`${n}/src/renderer/hooks/use-xterm.ts`,`${n}/src/renderer/hooks/use-automation-lifecycle.ts`,`${n}/src/renderer/lib/companion`,`${n}/src/renderer/hooks/use-chat-controller.ts`,`${n}/src/renderer/hooks/use-local-run.ts`,`${n}/src/renderer/hooks/use-local-model-options.ts`,`${n}/src/renderer/lib/drive-chat-store.ts`,`${n}/src/renderer/lib/local-drive.ts`,`${n}/src/renderer/hooks/use-mounted.ts`,`${n}/src/renderer/lib/ai`,`${n}/src/renderer/lib/side-panel-state.ts`,`${n}/src/renderer/components/side-panel-dock.tsx`,`${n}/src/renderer/components/side-panel.tsx`,`${n}/src/renderer/config/side-panels.tsx`,`${n}/src/renderer/components/command-palette/command-palette-ai-commands.tsx`])await U(w(t,a),{recursive:!0});for(let a of[`${n}/src/preload/api-contract.ts`,`${n}/src/main/drive-transport.ts`,`${n}/src/main/companion.ts`,`${n}/src/main/companion-state.ts`,`${n}/src/main/companion-parsers.ts`,`${n}/src/main/companion-paths.ts`,`${n}/src/main/companion-drive.ts`,`${n}/src/main/companion-staging.ts`,`${n}/src/main/companion-stderr-tail.ts`,`${n}/src/main/companion-commands-pure.ts`,`${n}/src/main/companion-shared.ts`,`${n}/src/main/companion-commands.ts`,`${n}/src/main/terminal.ts`,`${n}/src/main/terminal-state.ts`])await U(w(t,a));await U(w(t,`${n}/scripts/stage-companion.mjs`));for(let a of[`${n}/tests/ai-import-boundary.test.ts`,`${n}/tests/renderer/settings-tab-ids.test.ts`,`${n}/tests/renderer/connected-cache.test.ts`,`${n}/tests/renderer/router-redirects.test.ts`,`${n}/tests/renderer/lib/side-panel-state.test.ts`,`${n}/tests/renderer/schedules-view.test.ts`,`${n}/tests/renderer/automation-status.test.ts`,`${n}/tests/renderer/consent-dialog.test.ts`,`${n}/tests/renderer/background-mode.test.ts`,`${n}/tests/renderer/connection-state.test.ts`,`${n}/tests/renderer/models-empty-view.test.ts`,`${n}/tests/renderer/models-default-reset.test.ts`,`${n}/tests/renderer/cli-catalog.test.ts`,`${n}/tests/renderer/connect-flow.test.ts`,`${n}/tests/renderer/terminal-settings-view.test.ts`,`${n}/tests/renderer/mcp-section-i18n.test.ts`,`${n}/tests/renderer/reload-on-companion-ready.test.ts`,`${n}/tests/renderer/schedule-merge.test.ts`,`${n}/tests/renderer/terminal-tools.test.ts`,`${n}/tests/renderer/terminal-hint-interpolation.test.ts`,`${n}/tests/renderer/lib/companion/consent.test.ts`,`${n}/tests/renderer/lib/companion/ensure.test.ts`,`${n}/tests/renderer/lib/companion/pairing.test.ts`,`${n}/tests/renderer/lib/companion/ensure-unpublished-brand.test.ts`,`${n}/tests/renderer/lib/companion/terminal.test.ts`,`${n}/tests/renderer/lib/companion/terminal-unpublished-brand.test.ts`,`${n}/tests/task-overrides.test.ts`,`${n}/tests/local-drive.test.ts`,`${n}/tests/drive-chat-store.test.ts`,`${n}/tests/use-local-run.test.ts`,`${n}/tests/use-local-model-options.test.ts`,`${n}/tests/renderer/chat-controller-local-seed.test.ts`,`${n}/tests/main/companion-state.test.ts`,`${n}/tests/main/companion-commands.test.ts`,`${n}/tests/main/companion-supervisor.test.ts`,`${n}/tests/main/companion-restage.test.ts`,`${n}/tests/main/companion-teardown.process.test.ts`,`${n}/tests/stage-companion.test.ts`,`${n}/tests/main/drive-preload-stream.test.ts`,`${n}/tests/main/drive-transport.test.ts`,`${n}/tests/main/ipc.test.ts`,`${n}/tests/main/terminal-cli-allowlist.test.ts`,`${n}/tests/main/terminal-manager.process.test.ts`,`${n}/tests/main/terminal-state.test.ts`,`${n}/tests/main/terminal-teardown.process.test.ts`,`${n}/tests/renderer/api-consumer-fixture.ts`])await U(w(t,a));let r=w(t,`${n}/package.json`),o=JSON.parse(await V(r,"utf-8"));for(let a of ms){if(!o.dependencies||!(a in o.dependencies))throw new Error(`stripDesktopAi: expected ${a} in ${n} dependencies (boilerplate drift).`);delete o.dependencies[a]}if(!o.scripts||!("rebuild:electron"in o.scripts))throw new Error(`stripDesktopAi: expected the rebuild:electron script in ${n} package.json (boilerplate drift).`);delete o.scripts["rebuild:electron"],hs(o,"stage:companion",n),await p(r,JSON.stringify(o,null,2)+`
|
|
1186
|
+
`),await ys(t,n);let i=w(t,"packages/i18n/translations");for(let a of await zn(i,{withFileTypes:!0})){if(!a.isDirectory())continue;let s=w(i,a.name,"desktop.json"),u=await V(s,"utf-8").catch(()=>null);if(u===null)continue;let g=JSON.parse(u),l=!1;for(let h of["agents","ai_hub","schedules","integrations"])h in g&&(delete g[h],l=!0);l&&await p(s,JSON.stringify(g,null," ")+`
|
|
1187
|
+
`)}}function hs(e,t,n){if(!e.scripts||!(t in e.scripts))throw new Error(`stripDesktopAi: expected the ${t} script in ${n} package.json (boilerplate drift).`);delete e.scripts[t];let r=`pnpm run ${t} && `;for(let o of["build:unpack","build:win","build:mac","build:linux","release"]){let i=e.scripts[o];if(i===void 0||!i.startsWith(r))throw new Error(`stripDesktopAi: expected ${o} to begin with "${r}" in ${n} package.json (boilerplate drift).`);e.scripts[o]=i.slice(r.length)}}async function ys(e,t){let n=w(e,`${t}/src/renderer/components/shell.tsx`);await p(n,C(await V(n,"utf-8"),"components/shell.tsx"));let r=w(e,`${t}/src/renderer/components/auth-gate.tsx`);await p(r,C(await V(r,"utf-8"),"components/auth-gate.tsx")),await I(r,` // The chat shell owns the ONE chat controller above the router, so a run keeps streaming as the user
|
|
1188
1188
|
// moves between the \`/chat\` screen and the side-panel chat tab. Stripped to a bare RouterProvider when
|
|
1189
1189
|
// the agents feature is off.
|
|
1190
1190
|
return (
|
|
@@ -1193,42 +1193,42 @@ If your product ships the [desktop app](/desktop), its **Terminal** side-panel t
|
|
|
1193
1193
|
</ChatShellProvider>
|
|
1194
1194
|
)
|
|
1195
1195
|
`,` return <RouterProvider router={router} />
|
|
1196
|
-
`,"auth-gate chat shell wrapper","stripDesktopAi");let o=
|
|
1196
|
+
`,"auth-gate chat shell wrapper","stripDesktopAi");let o=w(e,`${t}/src/renderer/config/sidebar.ts`),i=C(await V(o,"utf-8"),"config/sidebar.ts");i=_t(i,`import {
|
|
1197
1197
|
BuildingsIcon,
|
|
1198
1198
|
ChatCircleIcon,
|
|
1199
1199
|
ClockCountdownIcon,
|
|
1200
1200
|
GearIcon,
|
|
1201
1201
|
HouseIcon,
|
|
1202
1202
|
UserCircleIcon
|
|
1203
|
-
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await p(o,i);let a=
|
|
1204
|
-
`,"","router clientConfig import"),l=
|
|
1203
|
+
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await p(o,i);let a=w(e,`${t}/src/renderer/lib/config.ts`),s=C(await V(a,"utf-8"),"lib/config.ts");s=s.replace(/,(\n\} as const)/,"$1"),await p(a,s);let u=w(e,`${t}/src/renderer/lib/sidebar-flags.ts`);await p(u,C(await V(u,"utf-8"),"lib/sidebar-flags.ts"));let g=w(e,`${t}/src/renderer/router.tsx`),l=C(await V(g,"utf-8"),"router.tsx");l=_t(l,`import { clientConfig } from '@/lib/config'
|
|
1204
|
+
`,"","router clientConfig import"),l=_t(l,` createRouter,
|
|
1205
1205
|
redirect
|
|
1206
1206
|
} from '@tanstack/react-router'`,` createRouter
|
|
1207
|
-
} from '@tanstack/react-router'`,"router redirect import specifier"),l=
|
|
1207
|
+
} from '@tanstack/react-router'`,"router redirect import specifier"),l=_t(l,`import { ChatScreen } from '@/screens/chat'
|
|
1208
1208
|
import { SchedulesScreen } from '@/screens/schedules'
|
|
1209
1209
|
import { ModelsSettingsScreen } from '@/screens/settings/models'
|
|
1210
1210
|
import { TasksSettingsScreen } from '@/screens/settings/tasks'
|
|
1211
1211
|
import { McpSettingsScreen } from '@/screens/settings/mcp'
|
|
1212
1212
|
import { IntegrationsSettingsScreen } from '@/screens/settings/integrations'
|
|
1213
|
-
`,"","router AI screen imports"),l=
|
|
1214
|
-
`,"","router ai route spread"),await p(g,l);let
|
|
1213
|
+
`,"","router AI screen imports"),l=_t(l,` ...(clientConfig.agentsEnabled ? aiRoutes : []),
|
|
1214
|
+
`,"","router ai route spread"),await p(g,l);let h=w(e,`${t}/src/renderer/screens/settings/index.tsx`);await p(h,C(await V(h,"utf-8"),"screens/settings/index.tsx"));let y=w(e,`${t}/src/main/ipc.ts`);await p(y,C(await V(y,"utf-8"),"src/main/ipc.ts"));let _=w(e,`${t}/src/main/index.ts`);await p(_,C(await V(_,"utf-8"),"src/main/index.ts"));let v=w(e,`${t}/src/preload/index.ts`);await p(v,C(await V(v,"utf-8"),"src/preload/index.ts"));let $=w(e,`${t}/electron-builder.mjs`);await p($,C(await V($,"utf-8"),"electron-builder.mjs"))}import{readFile as ws}from"fs/promises";import{join as vs}from"path";var Uo=`on:
|
|
1215
1215
|
workflow_run:
|
|
1216
1216
|
workflows: ["Tag Release"]
|
|
1217
1217
|
branches: [main]
|
|
1218
1218
|
types: [completed]
|
|
1219
|
-
workflow_dispatch:`,
|
|
1219
|
+
workflow_dispatch:`,ks=`on:
|
|
1220
1220
|
workflow_run:
|
|
1221
1221
|
workflows: ["CI"]
|
|
1222
1222
|
branches: [main]
|
|
1223
1223
|
types: [completed]
|
|
1224
|
-
workflow_dispatch:`,
|
|
1224
|
+
workflow_dispatch:`,bs=`on:
|
|
1225
1225
|
# Automatic release on CI success is disabled for this project to conserve
|
|
1226
1226
|
# GitHub Actions minutes. Re-enable by uncommenting the workflow_run trigger.
|
|
1227
1227
|
# workflow_run:
|
|
1228
1228
|
# workflows: ["CI"]
|
|
1229
1229
|
# branches: [main]
|
|
1230
1230
|
# types: [completed]
|
|
1231
|
-
workflow_dispatch:`;async function
|
|
1231
|
+
workflow_dispatch:`;async function jo(e){if(!e.desktop)return;let t=vs(e.projectDir,".github/workflows/desktop-release.yml"),n=await ws(t,"utf8");if(!n.includes(Uo))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.`);let r=e.desktopAutoRelease?ks:bs;await p(t,n.replace(Uo,r))}import{join as Ss}from"path";async function Mo(e){let t=Es(e);await p(Ss(e.projectDir,".github/workflows/ci.yml"),t)}function Es(e){let t=q[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",o=t?"":` services:
|
|
1232
1232
|
postgres:
|
|
1233
1233
|
image: postgres:18-alpine
|
|
1234
1234
|
env:
|
|
@@ -1248,8 +1248,8 @@ import { IntegrationsSettingsScreen } from '@/screens/settings/integrations'
|
|
|
1248
1248
|
STRIPE_SECRET_KEY: test
|
|
1249
1249
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1250
1250
|
POLAR_ACCESS_TOKEN: test
|
|
1251
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1252
|
-
${
|
|
1251
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let h=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(h)}"`)}}})(),u=e.socialProviders.map(h=>me[h].envVars.map(y=>`
|
|
1252
|
+
${y.name}: test`).join("")).join("");return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1253
1253
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1254
1254
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1255
1255
|
|
|
@@ -1298,48 +1298,48 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1298
1298
|
run: echo "DATABASE_URL=${i}" > .env
|
|
1299
1299
|
|
|
1300
1300
|
- run: pnpm test
|
|
1301
|
-
`}import{readFile as
|
|
1302
|
-
`))}async function
|
|
1303
|
-
`))}async function
|
|
1301
|
+
`}import{readFile as Vo}from"fs/promises";import{existsSync as Is}from"fs";import{join as Jn}from"path";var Fo="@repo/database";function As(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function Ps(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 Vo(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," ")+`
|
|
1302
|
+
`))}async function xs(e,t){let n=Is(e)?JSON.parse(await Vo(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," ")+`
|
|
1303
|
+
`))}async function Bo(e){let t=As(e.demo===!0),n=Ps(e.architecture,e.frontend),r=Jn(e.projectDir,"apps",n);switch(e.deploymentTarget){case"node":await Rs(Jn(r,"package.json"),"start",t);return;case"vercel":await xs(Jn(r,"vercel.json"),t);return;default:{let o=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(o)}"`)}}}import{readFile as Ts}from"fs/promises";import{existsSync as _s}from"fs";import{join as an}from"path";var Os=["stripe","polar"];async function Go(e){let t=an(e.projectDir,"packages/payments/src"),n=e.paymentProvider,r=`// Active payment provider. To switch, change the path below to
|
|
1304
1304
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1305
1305
|
export { ops } from "./${n}/index";
|
|
1306
|
-
`;await p(
|
|
1306
|
+
`;await p(an(t,"providers/index.ts"),r),await p(an(t,"index.ts"),await Cs(t,n))}async function Cs(e,t){let n=an(e,"index.ts");if(!_s(n))throw new Error(`generatePaymentBarrel: expected ${n} to exist - did packages/payments move?`);let r=await Ts(n,"utf-8"),o=Os.filter(a=>a!==t);return r.split(`
|
|
1307
1307
|
`).filter(a=>!o.some(s=>a.includes(`./providers/${s}/`))).join(`
|
|
1308
|
-
`)}import{readdir as
|
|
1308
|
+
`)}import{readdir as Ds,readFile as Ns}from"fs/promises";import{join as Ko}from"path";async function Ho(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,n=JSON.stringify(t).slice(1,-1),r=Ko(e.projectDir,"packages/i18n/translations"),o;try{o=await Ds(r)}catch{return}for(let i of o){let a=Ko(r,i,"web.json"),s;try{s=await Ns(a,"utf-8")}catch{continue}let u=s.replaceAll("GenerateSaaS",n);u!==s&&await p(a,u)}}import{readFile as $s}from"fs/promises";import{join as zo}from"path";var Ls=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],Us=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function qo(e){let n=e.frontend==="nuxt"?Us:Ls;await Jo(zo(e.projectDir,".gitignore"),n),await Jo(zo(e.projectDir,".dockerignore"),n)}async function Jo(e,t){let n;try{n=await $s(e,"utf-8")}catch{return}let r=new Set(t),o=n.split(`
|
|
1309
1309
|
`).filter(i=>!r.has(i.trim()));o.length!==n.split(`
|
|
1310
1310
|
`).length&&await p(e,o.join(`
|
|
1311
|
-
`))}async function
|
|
1312
|
-
`),await p(
|
|
1313
|
-
`)}import{relative as
|
|
1314
|
-
`);i(new Error(
|
|
1315
|
-
${
|
|
1316
|
-
`),
|
|
1317
|
-
`),
|
|
1318
|
-
`),te.yellow("Deployment"))}function ic(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 ac(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 mt(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 Ke(e,t){let n=mt(e),r=mt(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 cn(e,t){return e.versions.find(n=>n.version===t)?.cli}function di(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:mt(e)===null}function pn(e,t,n="2.0.1"){if(di(n))return{ok:!0};let r=cn(e,e.latest);return!r||mt(r)===null?{ok:!0}:Ke(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 ui(e,t,n="2.0.1"){if(di(n))return{ok:!0};let r=cn(e,t);return!r||mt(r)===null?{ok:!0}:Ke(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 uc from"picocolors";var mc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function fc(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 mi(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 X("--frontend <type>","frontend framework").choices([...Ne])).addOption(new X("--architecture <type>","fullstack or separate").choices([...Ye])).addOption(new X("--payment <provider>","payment provider").choices([...We])).addOption(new X("--email <provider>","email provider").choices([...Xe])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new X("--billing-scope <scope>","billing scope (requires --org)").choices([...et])).option("--blog","enable blog").option("--no-blog","disable blog").option("--email-tracking","enable email analytics (open/click tracking + admin analytics page)").option("--no-email-tracking","disable email analytics").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("--desktop-auto","auto-trigger the desktop release workflow on CI success (default: manual-only)").option("--no-desktop-auto","manual-only desktop releases (workflow_dispatch)").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion + MCP server").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 X("--companion-source <source>","companion source: point at an existing shared companion repo, or vendor your own branded daemon").choices([...$e])).option("--companion-repo-url <url>","GitHub URL of the shared companion repo (with --companion-source shared; default: OpenCompanion)").option("--companion-local-path <path>","path to your local checkout of the shared companion (optional, for developing it alongside)").option("--mcp-server","include the outward MCP server (the /mcp route + Better Auth mcp() provider)").option("--no-mcp-server","exclude the outward MCP server").option("--ai-builtin","built-in AI: models under your app's name via OpenRouter, billed from credits (default)").option("--no-ai-builtin","no built-in AI").option("--ai-byok","let end-users connect their own provider API keys (default)").option("--no-ai-byok","no user-supplied API keys").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").option("--social-providers <providers>","comma-separated: google,github,facebook,discord,x").addOption(new X("--currency <code>","default currency for billing").choices([...me])).addOption(new X("--deploy <target>","deployment target").choices([...fe])).addOption(new X("--database <provider>","database provider").choices([...ge])).addOption(new X("--cache <provider>","cache provider").choices([...he])).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 X("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new X("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await gc(t?{...n,apiKey:t}:n)})}async function gc(e){let t=performance.now();dr("2.0.1");let n;try{n=Pr(e)}catch(E){A.cancel(T(E)),process.exit(1)}let r=A.spinner(),o;try{o=await rt({apiKey:e.apiKey,prompt:!e.yes})}catch(E){A.cancel(T(E)),process.exit(1)}e.demo&&Jn(o)!==mc&&(A.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=ve(o),a,s=async()=>{a=await xe(i);let E=pn(a,"init");if(!E.ok)throw new Error(E.message);return{latestVersion:a.latest,selectedVersion:a.latest,desktopAllowed:a.entitlements?.desktopAllowed??!0}};r.start("Verifying access...");let u,g,l=!0;try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),je(o)}catch(E){if(r.stop("Access verification failed."),E instanceof V&&E.status===401){e.yes&&(A.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),A.log.warning("Invalid API key."),o=await Et(),i=ve(o),r.start("Verifying access...");try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),je(o)}catch($){r.stop("Access verification failed."),A.cancel($ instanceof V&&$.status===401?"Invalid API key.":T($)),process.exit(1)}}else A.cancel(T(E)),process.exit(1)}A.log.success(`Latest version: ${u}`),n.desktop===!0&&!l&&(A.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let m;e.yes?m=Rr(l?n:{...n,desktop:!1}):m=await xr(n,{desktopAllowed:l});let w;r.start("Activating license...");try{let E=e.demo&&m.baseUrl?await fc(m.baseUrl):crypto.randomUUID(),$=()=>({frontend:m.frontend,version:g,installId:E,projectName:m.projectName,options:Dr(m)}),L;try{L=await Pn(i,$())}catch(Oe){let _=zt(Oe);if(!_?.lastAllowedVersion||!a)throw Oe;r.stop("License activation failed.");let k=ui(a,_.lastAllowedVersion);if(k.ok||(A.cancel(`${_.message} ${k.message}`),process.exit(1)),e.yes){let oe=cn(a,_.lastAllowedVersion);A.cancel(`${_.message} Re-run ${oe?`npx generatesaas@${oe} init`:"init"} without --yes to continue with v${_.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let B=await A.confirm({message:`Your update window has ended. Continue with v${_.lastAllowedVersion} (the last version your license covers)?`});(A.isCancel(B)||!B)&&(A.cancel("Setup cancelled."),process.exit(0)),g=_.lastAllowedVersion,r.start(`Activating license for v${g}...`),L=await Pn(i,$())}w={token:L.token,keyHash:Jn(o),installId:L.installId??E},r.stop("License activated.")}catch(E){r.stop("License activation failed."),A.cancel(T(E)),process.exit(1)}let v=dc(m.projectDir);if(sc(v)&&cc(v).length>0)if(e.yes)A.log.info(`Directory ${v} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let $=await A.select({message:`Directory ${v} 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"}]});(A.isCancel($)||$==="cancel")&&(A.cancel("Setup cancelled."),process.exit(0)),$==="overwrite"&&pc(v,{recursive:!0,force:!0})}let R={...m,projectDir:v,version:g,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await Jt(i,g,v),r.stop("Template downloaded.")}catch(E){r.stop("Download failed."),A.cancel(T(E)),process.exit(1)}let q;r.start("Generating project files...");try{if({dockerComposeGenerated:q}=await an(R),!e.demo){let E=await Fe(v);await p(lc(v,Kt),JSON.stringify(E,null," ")+`
|
|
1319
|
-
`),await
|
|
1320
|
-
`),
|
|
1321
|
-
`);let
|
|
1322
|
-
`)}if(g.stop("Baseline template stored."),!
|
|
1323
|
-
`),g.stop("Baseline hashes computed.")}if(await p(
|
|
1324
|
-
`),P.log.info(`Update staged: ${J.cyan(a.version)} \u2192 ${J.cyan(l.latest)}`),a.aiTools&&a.aiTools.length>0){let
|
|
1325
|
-
|
|
1326
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${J.cyan("generatesaas update")} without ${J.cyan("auto")} and answer it.`),process.exit(1));let o=await P.select({message:r.message,options:r.options});P.isCancel(o)&&(P.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e),
|
|
1311
|
+
`))}async function sn(e){let t=e.projectDir;e.demo||(await Kr(t),await zr(t),await Jr(t),await qr(t),e.desktop&&await Hr(t)),await Yr(t,e.aiTools),await Wr(t,e.frontend),await Zr(e),await Qr(e),await to(e),await eo(e),e.demo||await no(e),await io(e);let n=await ao(e);return await so(e),await co(e),await po(e),await lo(e),await uo(e),await mo(e),await yo(e),await wo(e),await bo(e),await Io(e),await xo(e),await Mo(e),await To(e),await _o(e),await Oo(e),await Co(e),await Do(e),await No(e),await Lo(e),await $o(e),await jo(e),await Fn(e),await Bn(e),await Gn(e),await Kn(e),await Bo(e),await Go(e),await Ho(e),await qo(e),{dockerComposeGenerated:n}}import{basename as Wo,join as Xo,relative as Ms}from"path";import{createHash as Yo}from"crypto";import{readFile as js}from"fs/promises";async function cn(e){let t=await js(e);return Yo("sha256").update(t).digest("hex")}function qn(e){return Yo("sha256").update(e).digest("hex")}var Vs=new Set(["data",z]);function Fs(e){let t=e.split("/");for(let n of t)if(Tn.has(n)||_n.has(n)||Vs.has(n)||n.startsWith(".env")&&!n.includes("example"))return!0;return!1}function Zo(e,t){return{projectName:e.projectName??Wo(t),appName:e.appName??e.projectName??Wo(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,billingScope:e.billingScope??"user",blog:e.blog??!1,emailTracking:e.emailTracking??!0,docs:e.docs??!1,desktop:e.desktop??!1,desktopAutoRelease:e.desktopAutoRelease??!0,ai:e.ai??!1,companion:e.companion??!1,companionSource:Y(e),companionRepoUrl:e.companionRepoUrl??Ue,companionLocalPath:e.companionLocalPath??"",companionName:e.companionName??Z(e.projectName),mcpServer:e.mcpServer??!1,aiBuiltin:Ee(e)&&(e.aiBuiltin??!0),aiByok:e.aiByok??!0,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,dockerServices:e.dockerServices??[],aiTools:e.aiTools??[],socialProviders:e.socialProviders??[],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 Bs(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,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,desktopAutoRelease:e.desktopAutoRelease,ai:e.ai,companion:e.companion,mcpServer:e.mcpServer,...e.companionName?{companionName:e.companionName}:{},...e.companionSource?{companionSource:e.companionSource}:{},...e.companionRepoUrl?{companionRepoUrl:e.companionRepoUrl}:{},...e.companionLocalPath!==void 0?{companionLocalPath:e.companionLocalPath}:{},aiBuiltin:e.aiBuiltin,aiByok:e.aiByok,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,dockerServices:e.dockerServices,socialProviders:e.socialProviders,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 Qo(e,t){let r=(await Fe(e.projectDir,e.projectDir,Fs)).sort(),o=await Promise.all(r.map(async s=>[Ve(Ms(e.projectDir,s)),await cn(s)])),i=Object.fromEntries(o),a=Bs(e,t);await p(Xo(e.projectDir,Ie),JSON.stringify(a,null," ")+`
|
|
1312
|
+
`),await p(Xo(e.projectDir,_r),JSON.stringify(i,null," ")+`
|
|
1313
|
+
`)}import{relative as Gs}from"path";async function Be(e){let n=(await Fe(e,e,it)).sort(),r=await Promise.all(n.map(async o=>[Ve(Gs(e,o)),await cn(o)]));return Object.fromEntries(r)}import{copyFile as Ks,mkdir as Hs,rm as zs}from"fs/promises";import{dirname as Js,join as ei,relative as qs}from"path";import{existsSync as Ys}from"fs";async function Yn(e,t){Ys(t)&&await zs(t,{recursive:!0,force:!0});let n=await Fe(e,e,it);for(let r of n){let o=Ve(qs(e,r)),i=ei(t,o);await Hs(Js(i),{recursive:!0}),await Ks(r,i)}}async function ti(e,t){await Yn(e,ei(t,zt))}import{existsSync as Ws}from"fs";import{readFile as ni,readdir as Xs}from"fs/promises";import{join as de,dirname as Zs,resolve as Qs,sep as ec}from"path";import{fileURLToPath as tc}from"url";var Ot={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},vm=Object.values(Ot),Wn="generatesaas-update",ri=Zs(tc(import.meta.url));function nc(){let e=de(ri,"skill","content");return Ws(e)?e:de(ri,"content")}function Xn(e){return!e||e.length===0?[]:e.map(t=>Ot[t])}async function Zn(e,t,n,r){let o=Xn(r);for(let i of o){let a=de(e,i,Wn),s=de(a,"scripts"),u=de(a,"references");await Wt(s),await Wt(u),await p(de(a,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",i)),await p(de(u,".gitkeep"),"");for(let[g,l]of Object.entries(n)){let h=Qs(s,g);h.startsWith(s+ec)&&await p(h,l)}}}async function oi(e,t){let n=nc(),r=await ni(de(n,"SKILL.md"),"utf-8"),o=de(n,"scripts"),i=await Xs(o),a={};for(let s of i)s!==".gitkeep"&&(a[s]=await ni(de(o,s),"utf-8"));await Zn(e,r,a,t)}import{execFile as rc,execFileSync as oc}from"child_process";import{access as ii,readFile as ic}from"fs/promises";import{join as Qn}from"path";import*as j from"@clack/prompts";function Ke(e){try{let t=process.platform==="win32"?"where":"which";return oc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Ge(e,t,n,r=3e5){return new Promise((o,i)=>{rc(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(`
|
|
1314
|
+
`);i(new Error(h?`${a.message}
|
|
1315
|
+
${h}`:a.message))}else o()})})}async function ai(e){if(!Ke("pnpm"))return j.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Ge("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let n=t instanceof Error?t.message:String(t);return j.log.warn(`Lockfile regeneration failed: ${n}`),j.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function si(e){if(!Ke("pnpm"))return j.log.warn("pnpm not found. Skipping dependency installation."),j.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=j.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Ge("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 j.log.warn(`pnpm install failed: ${r}`),j.log.warn("You can run it manually later."),!1}}async function ci(e){if(!Ke("pnpm"))return!1;let t=j.spinner();t.start("Generating baseline database migration...");try{return await Ge("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 j.log.warn(`Could not generate baseline migration: ${r}`),j.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function pi(e){try{return await ii(Qn(e,".git")),j.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ke("git"))return j.log.warn("git not found. Skipping repository initialization."),!1;let t=j.spinner();t.start("Initializing git repository...");try{return await Ge("git",["init"],e),await Ge("git",["add","-A"],e),await Ge("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),j.log.warn("You can run git init manually later."),!1}}async function li(e){if(!Ke("pnpm"))return!1;try{await ii(Qn(e,".git"))}catch{return!1}try{let t=JSON.parse(await ic(Qn(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 Ge("pnpm",["exec","simple-git-hooks"],e),!0}catch{return j.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as mt from"@clack/prompts";import Q from"picocolors";function di(e,t){t.dockerComposeGenerated&&!t.dockerAvailable&&mt.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=>Ye[a].label).join(", ");n.push(`pnpm infra ${Q.dim(`# ${i}`)}`)}if(n.push(`pnpm dev ${Q.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(Q.dim("Fill in remaining TODO values in .env"))),mt.note(n.join(`
|
|
1316
|
+
`),Q.yellow("Start Development")),t.dockerComposeGenerated){let i=[];i.push(`App ${Q.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${Q.cyan("http://localhost:3010")}`),e.dockerServices.includes("mailpit")&&i.push(`Mailpit ${Q.cyan("http://localhost:8025")}`),e.dockerServices.includes("inngest")&&i.push(`Inngest ${Q.cyan("http://localhost:8288")}`),mt.note(i.join(`
|
|
1317
|
+
`),Q.yellow("Dev Tools"))}let r=[],o=ac(e);o.length>0&&r.push(`Set in production: ${Q.dim(o.join(", "))}`),r.push("pnpm db:setup # Apply the database schema"),r.push(sc(e)),mt.note(r.join(`
|
|
1318
|
+
`),Q.yellow("Deployment"))}function ac(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 sc(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 ft(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 He(e,t){let n=ft(e),r=ft(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 pn(e,t){return e.versions.find(n=>n.version===t)?.cli}function ui(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ft(e)===null}function ln(e,t,n="2.1.0"){if(ui(n))return{ok:!0};let r=pn(e,e.latest);return!r||ft(r)===null?{ok:!0}:He(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 mi(e,t,n="2.1.0"){if(ui(n))return{ok:!0};let r=pn(e,t);return!r||ft(r)===null?{ok:!0}:He(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 mc from"picocolors";var fc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function gc(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 fi(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new W("--frontend <type>","frontend framework").choices([...$e])).addOption(new W("--architecture <type>","fullstack or separate").choices([...We])).addOption(new W("--payment <provider>","payment provider").choices([...Xe])).addOption(new W("--email <provider>","email provider").choices([...Ze])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new W("--billing-scope <scope>","billing scope (requires --org)").choices([...tt])).option("--blog","enable blog").option("--no-blog","disable blog").option("--email-tracking","enable email analytics (open/click tracking + admin analytics page)").option("--no-email-tracking","disable email analytics").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("--desktop-auto","auto-trigger the desktop release workflow on CI success (default: manual-only)").option("--no-desktop-auto","manual-only desktop releases (workflow_dispatch)").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion + MCP server").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 W("--companion-source <source>","companion source: point at an existing shared companion repo, or vendor your own branded daemon").choices([...Le])).option("--companion-repo-url <url>","GitHub URL of the shared companion repo (with --companion-source shared; default: OpenCompanion)").option("--companion-local-path <path>","path to your local checkout of the shared companion (optional, for developing it alongside)").option("--mcp-server","include the outward MCP server (the /mcp route + Better Auth mcp() provider)").option("--no-mcp-server","exclude the outward MCP server").option("--ai-builtin","built-in AI: models under your app's name via OpenRouter, billed from credits (default)").option("--no-ai-builtin","no built-in AI").option("--ai-byok","let end-users connect their own provider API keys (default)").option("--no-ai-byok","no user-supplied API keys").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").option("--social-providers <providers>","comma-separated: google,github,facebook,discord,x").addOption(new W("--currency <code>","default currency for billing").choices([...fe])).addOption(new W("--deploy <target>","deployment target").choices([...ge])).addOption(new W("--database <provider>","database provider").choices([...he])).addOption(new W("--cache <provider>","cache provider").choices([...ye])).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 W("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new W("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await hc(t?{...n,apiKey:t}:n)})}async function hc(e){let t=performance.now();ur("2.1.0");let n;try{n=Rr(e)}catch(k){A.cancel(T(k)),process.exit(1)}let r=A.spinner(),o;try{o=await ot({apiKey:e.apiKey,prompt:!e.yes})}catch(k){A.cancel(T(k)),process.exit(1)}e.demo&&qn(o)!==fc&&(A.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=ke(o),a,s=async()=>{a=await Re(i);let k=ln(a,"init");if(!k.ok)throw new Error(k.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."),Me(o)}catch(k){if(r.stop("Access verification failed."),k instanceof F&&k.status===401){e.yes&&(A.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),A.log.warning("Invalid API key."),o=await It(),i=ke(o),r.start("Verifying access...");try{({latestVersion:u,selectedVersion:g,desktopAllowed:l,companionAllowed:h}=await s()),r.stop("Access verified."),Me(o)}catch(x){r.stop("Access verification failed."),A.cancel(x instanceof F&&x.status===401?"Invalid API key.":T(x)),process.exit(1)}}else A.cancel(T(k)),process.exit(1)}A.log.success(`Latest version: ${u}`),n.desktop===!0&&!l&&(A.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&&(A.cancel("The companion is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let y;e.yes?y=xr({...n,...l?{}:{desktop:!1},...h?{}:{companion:!1}}):y=await Tr(n,{desktopAllowed:l,companionAllowed:h});let _;r.start("Activating license...");try{let k=e.demo&&y.baseUrl?await gc(y.baseUrl):crypto.randomUUID(),x=()=>({frontend:y.frontend,version:g,installId:k,projectName:y.projectName,options:Nr(y)}),ue;try{ue=await Rn(i,x())}catch(M){let b=Jt(M);if(!b?.lastAllowedVersion||!a)throw M;r.stop("License activation failed.");let L=mi(a,b.lastAllowedVersion);if(L.ok||(A.cancel(`${b.message} ${L.message}`),process.exit(1)),e.yes){let oe=pn(a,b.lastAllowedVersion);A.cancel(`${b.message} Re-run ${oe?`npx generatesaas@${oe} init`:"init"} without --yes to continue with v${b.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let Ce=await A.confirm({message:`Your update window has ended. Continue with v${b.lastAllowedVersion} (the last version your license covers)?`});(A.isCancel(Ce)||!Ce)&&(A.cancel("Setup cancelled."),process.exit(0)),g=b.lastAllowedVersion,r.start(`Activating license for v${g}...`),ue=await Rn(i,x())}_={token:ue.token,keyHash:qn(o),installId:ue.installId??k},r.stop("License activated.")}catch(k){r.stop("License activation failed."),A.cancel(T(k)),process.exit(1)}let v=uc(y.projectDir);if(cc(v)&&pc(v).length>0)if(e.yes)A.log.info(`Directory ${v} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let x=await A.select({message:`Directory ${v} 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"}]});(A.isCancel(x)||x==="cancel")&&(A.cancel("Setup cancelled."),process.exit(0)),x==="overwrite"&&lc(v,{recursive:!0,force:!0})}let $={...y,projectDir:v,version:g,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await qt(i,g,v),r.stop("Template downloaded.")}catch(k){r.stop("Download failed."),A.cancel(T(k)),process.exit(1)}let ne;r.start("Generating project files...");try{if({dockerComposeGenerated:ne}=await sn($),!e.demo){let k=await Be(v);await p(dc(v,Ht),JSON.stringify(k,null," ")+`
|
|
1319
|
+
`),await ti(v,v)}await oi(v,$.aiTools),await Qo($,_),r.stop("Project files generated.")}catch(k){r.stop("Generation failed."),A.cancel(T(k)),process.exit(1)}!await ai(v)&&$.demo===!0&&(A.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let re=await si(v);re&&$.demo!==!0&&e.dbMigration!==!1&&await ci(v),await pi(v),re&&await li(v);let _e=Ke("docker"),qe=An($).map(k=>k.key).filter(k=>!$.credentials?.[k]);di($,{pnpmInstalled:re,dockerComposeGenerated:ne,dockerAvailable:_e,skippedCredentials:qe}),mr(),A.log.info(mc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as nr}from"fs";import{readFile as rr}from"fs/promises";import{join as gt,resolve as Ic}from"path";import*as P from"@clack/prompts";import J from"picocolors";import{mkdtemp as yc,rm as wc}from"fs/promises";import{tmpdir as vc}from"os";import{join as kc}from"path";async function er(e,t,n,r){let o=await yc(kc(vc(),"generatesaas-stage-"));try{await qt(e,t,o),await sn({...n,projectDir:o}),await Yn(o,r)}finally{await wc(o,{recursive:!0,force:!0})}}import{readFile as bc,rm as Sc}from"fs/promises";import{join as tr}from"path";var gi=tr(z,"companion-release.json"),Ec=["apps/companion/","packages/companion-protocol/","packages/agent-core-types/","packages/agent-core/","scripts/companion-export/"];async function hi(e){let t;try{t=await bc(tr(e,gi),"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 yi(e){try{return await Sc(tr(e,gi)),!0}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function wi(e){return e.some(t=>Ec.some(n=>t.startsWith(n)))}function ki(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=Ic(n.cwd??process.cwd()),i=gt(o,Ie),a;try{a=JSON.parse(await rr(i,"utf-8"))}catch{P.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s;try{s=await ot()}catch(l){P.cancel(T(l)),process.exit(1)}let u=ke(s),g=P.spinner();try{g.start("Verifying access...");let l;try{l=await Re(u)}catch(b){throw b instanceof F&&b.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):b}let h=ln(l,"update");if(!h.ok)throw new Error(h.message);g.stop("Access verified."),Me(s),g.start("Fetching latest skill files...");let y=await Dr(u,l.latest);await Zn(o,y.skillMd,y.scripts,a.aiTools);let _=Xn(a.aiTools);if(g.stop("Skills updated."),P.log.success(`Skill files installed to ${J.cyan(_.length.toString())} locations.`),a.version===l.latest){P.log.info(`Already on the latest version (${a.version}).`);return}let v=JSON.stringify(a);Ir(a),Ar(a),await Ac(a,Pr(a),r);let $=yr(a),ne=wr(a),Se=JSON.stringify(ne)!==v;if(a=ne,a.licenseToken)try{let b=await $r(u,{currentToken:a.licenseToken,newVersion:l.latest});a.licenseToken=b.token,b.licenseKeyHash&&(a.licenseKeyHash=b.licenseKeyHash),await p(i,JSON.stringify(a,null," ")+`
|
|
1320
|
+
`),Se=!1,P.log.success("License refreshed.")}catch(b){let L=Jt(b);L&&(P.cancel(L.message),process.exit(1)),P.log.warn("License refresh skipped.")}Se&&await p(i,JSON.stringify(a,null," ")+`
|
|
1321
|
+
`);let re=Zo(a,o),_e=gt(o,Or);g.start(`Staging v${l.latest} (shaped for your config)...`),await er(u,l.latest,re,_e),g.stop("Template staged.");let{text:Oe,title:qe}=await Rc(u,l,a.version);Oe&&P.note(Oe,qe);let k=gt(o,Ht),x=gt(o,zt),ue=!nr(x),M=!nr(k);if(ue){if(g.start("Building baseline template (one-time migration)..."),await er(u,a.version,re,x),M){let b=await Be(x);await p(k,JSON.stringify(b,null," ")+`
|
|
1322
|
+
`)}if(g.stop("Baseline template stored."),!M){let b=await Tc(k,x);b>0&&P.log.warn(`Rebuilt baseline differs from the original for ${b} 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(M){g.start("Computing baseline template hashes...");let b=await Be(x);await p(k,JSON.stringify(b,null," ")+`
|
|
1323
|
+
`),g.stop("Baseline hashes computed.")}if(await p(gt(o,Cr),JSON.stringify({currentVersion:a.version,targetVersion:l.latest,changelog:Oe,stagedAt:new Date().toISOString(),...$.length>0?{newOptions:$}:{},...r?{mode:r}:{}},null," ")+`
|
|
1324
|
+
`),P.log.info(`Update staged: ${J.cyan(a.version)} \u2192 ${J.cyan(l.latest)}`),a.aiTools&&a.aiTools.length>0){let b=a.aiTools[0],L=vt[b].label;P.log.info(`Open your project in ${J.cyan(L)} and ask: ${J.cyan("'update my GenerateSaaS project'")}`)}else P.log.info(`Ask your AI coding assistant to ${J.cyan("'update my GenerateSaaS project'")}.`);if(a.companion===!0)try{if(se(a)==="vendored"){let b=await hi(o);if(b){let L=await xc(k,_e);wi(L)&&P.log.warn(`Companion: vendored daemon changed since your published v${b.version} - run pnpm companion:publish (your users auto-update once tagged)`)}}else await yi(o)&&P.log.info("Companion: removed the stale vendored publish state (.generatesaas/companion-release.json) - this project points at a shared companion.")}catch(b){P.log.warn(`Companion re-release check skipped: ${T(b)}`)}a.desktop===!0&&nr(gt(o,"apps/tauri"))&&P.log.warn(`Desktop: the app moved to an Electron shell (${J.cyan("apps/electron")}). Your project still has the old Tauri shell (${J.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${J.cyan("/desktop/updates")}.`)}catch(l){g.stop("Failed."),P.cancel(`Update failed: ${T(l)}`),process.exit(1)}})}async function Ac(e,t,n){if(t.kind==="none")return;if(t.kind==="daemon-materialized"){P.log.info(`Desktop: your app now bundles its own companion daemon. This update adds its source to your repo (${J.cyan("apps/companion")}, branded ${J.cyan(e.companionName??"")}) and about 106MB to each packaged build. Nothing to publish - it ships inside the app.`);return}let r=Pc[t.kind];n==="auto"&&(P.cancel(`${r.message}
|
|
1325
|
+
|
|
1326
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${J.cyan("generatesaas update")} without ${J.cyan("auto")} and answer it.`),process.exit(1));let o=await P.select({message:r.message,options:r.options});P.isCancel(o)&&(P.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e),In(e)}function vi(e){e.desktop=!1,e.desktopAutoRelease=!1}var Pc={"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,e.mcpServer=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion and the MCP server - they both require AI"},{value:{apply:vi},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:vi},label:"Drop the desktop app",hint:"your website keeps its AI surface and its shared companion exactly as they are today"}]}};async function Rc(e,t,n){let r=t.latest,o=t.versions.filter(a=>He(a.version,n)>0&&He(a.version,r)<=0).sort((a,s)=>He(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}
|
|
1327
1327
|
|
|
1328
1328
|
${s??"_No changelog available for this release._"}`)}return{text:i.join(`
|
|
1329
1329
|
|
|
1330
|
-
`),title:`Changelog v${n} \u2192 v${r}`}}async function
|
|
1331
|
-
`);
|
|
1332
|
-
`),D.yellow("License Details"))}function
|
|
1333
|
-
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));o.length===0&&(N.cancel("No URLs found in file."),process.exit(1));let i=0;for(let a of o)await
|
|
1330
|
+
`),title:`Changelog v${n} \u2192 v${r}`}}async function xc(e,t){let n=JSON.parse(await rr(e,"utf-8")),r=await Be(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 Tc(e,t){let n=JSON.parse(await rr(e,"utf-8")),r=await Be(t),o=0;for(let[i,a]of Object.entries(n))it(i)||r[i]!==a&&o++;for(let i of Object.keys(r))i in n||o++;return o}import*as X from"@clack/prompts";import ee from"picocolors";import{readFile as _c}from"fs/promises";import{join as Oc,resolve as Cc}from"path";function bi(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=Cc(t.cwd??process.cwd()),r=Oc(n,Ie),o;try{o=JSON.parse(await _c(r,"utf-8"))}catch{X.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let i=[`Version: ${ee.cyan(o.version)}`,`Frontend: ${ee.cyan(o.frontend)}`,o.deploymentTarget?`Deploy target: ${ee.cyan(o.deploymentTarget)}`:null,o.databaseProvider?`Database: ${ee.cyan(o.databaseProvider)}`:null,o.cacheProvider?`Cache: ${ee.cyan(o.cacheProvider)}`:null,o.aiTools&&o.aiTools.length>0?`AI tools: ${ee.cyan(o.aiTools.join(", "))}`:null].filter(Boolean).join(`
|
|
1331
|
+
`);X.note(i,ee.bold("Project Status"));let a=X.spinner();a.start("Checking for updates...");try{let s=await ot(),u=ke(s),l=(await Re(u)).latest;o.version===l?(a.stop("Up to date."),X.log.success(`Already on the latest version (${ee.green(l)})`)):(a.stop("Update available."),X.log.warning(`Update available: ${ee.yellow(o.version)} \u2192 ${ee.green(l)}`),X.log.info(`Open this project in your AI coding agent and ask it to ${ee.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(s){a.stop("Check failed."),s instanceof F&&s.status===401?X.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):X.log.warning(`Could not check for updates: ${T(s)}`)}})}import{readFile as Dc}from"fs/promises";import*as N from"@clack/prompts";import D from"picocolors";function Nc(){return process.env.GENERATESAAS_API_KEY??Et()}function $c(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 Lc(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Uc(e){switch(e.verdict){case"licensed":return N.log.success(`${D.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return N.log.success(`${D.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 N.log.error(`${D.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 N.log.error(`${D.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${D.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return N.log.error(`${D.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return N.log.warn(`${D.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Si(e,t){let n=process.env.GENERATESAAS_API_URL??St,r=Nc();e.start("Cross-referencing license records...");try{let o=r?$c(await Lr(n,r,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Lc(await xn(n,{token:t.token,domain:t.domain}));return e.stop(`${D.green("Checked")} - records cross-referenced`),Uc(o)}catch(o){return e.stop(`${D.yellow("Skipped")} - ${T(o)}`),null}}function jc(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 or(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Ei(e){N.note([`License ID: ${D.cyan(String(e.lid??"unknown"))}`,`Version: ${D.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${or(e.pat)}`,`Last updated: ${or(e.uat)}`,`Expires: ${or(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1332
|
+
`),D.yellow("License Details"))}function Mc(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 Ii(e){let t=N.spinner(),n=null,r="no candidates";for(let a of Mc(e)){t.start(`Checking ${a}...`);try{let s=await fetch(a);if(!s.ok){r=`${a} returned ${s.status}`,t.stop(`${D.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(`${D.yellow("Not here")} - ${r}`);continue}n=u,t.stop(`${D.green("Found")} - license endpoint responded`);break}catch(s){r=`${a}: ${T(s)}`,t.stop(`${D.yellow("Unreachable")} - ${r}`)}}if(n===null){N.log.warn(`No license endpoint found (last: ${r}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let a=Ai(e);return a?await Si(t,{domain:a})??!1:!1}let o;try{o=jc(n)}catch{return N.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let a=process.env.GENERATESAAS_API_URL??St,s=await xn(a,{token:n});if(s.valid)t.stop(`${D.green("Valid")} - signature verified`);else return t.stop(`${D.red("Invalid")} - ${s.reason}`),!1}catch{return t.stop(`${D.yellow("Skipped")} - could not reach verification service`),N.log.warn("Signature not verified. Displaying unverified claims:"),Ei(o),!1}return Ei(o),await Si(t,{token:n,lkh:typeof o.lkh=="string"?o.lkh:void 0,nid:typeof o.nid=="string"?o.nid:void 0,domain:Ai(e)})??!0}function Ai(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,n)=>{if(!t&&!n.file&&(N.cancel("Provide a URL or --file <path>."),process.exit(1)),n.file){let o=(await Dc(n.file,"utf-8")).split(`
|
|
1333
|
+
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));o.length===0&&(N.cancel("No URLs found in file."),process.exit(1));let i=0;for(let a of o)await Ii(a)&&i++,N.log.info("");N.log.success(`${i}/${o.length} sites verified.`)}else await Ii(t)||process.exit(1)})}import{existsSync as Vc,rmSync as Fc}from"fs";import*as te from"@clack/prompts";function Ri(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(ve)?(Fc(ve),te.log.success("API key removed.")):te.log.info("No API key configured.");return}let n=Et();n?te.log.info(`Current API key: ****${n.slice(-4)}`):te.log.info("No API key configured.");let r=await It(),o=ke(r),i=te.spinner();i.start("Verifying API key...");try{await Re(o),i.stop("API key verified."),Me(r),te.log.success("API key saved.")}catch(a){i.stop("Verification failed."),a instanceof F&&a.status===401?te.cancel("Invalid API key."):te.cancel(T(a)),process.exit(1)}})}import{existsSync as dn,rmSync as Bc,readFileSync as ar,writeFileSync as xi}from"fs";import{join as ze}from"path";import*as G from"@clack/prompts";var Gc=["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"],Kc=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1334
1334
|
`,` licenseHeartbeatFunction,
|
|
1335
1335
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1336
1336
|
`,` .route("/license", licenseRoutes)
|
|
1337
|
-
`]}];function
|
|
1337
|
+
`]}];function Hc(e){return(e&&e.length>0?e.map(n=>Ot[n]):Object.values(Ot)).map(n=>ze(n,Wn))}function ir(e){return dn(e)?(Bc(e,{recursive:!0}),!0):!1}function zc(e,t){if(!dn(e))return!1;let n=ar(e,"utf-8"),r=n;for(let o of t)r=r.replace(o,"");return r===n?!1:(xi(e,r,"utf-8"),!0)}function Jc(e){let t=ze(e,".gitignore");if(!dn(t))return!1;let n=ar(t,"utf-8"),r=n.split(`
|
|
1338
1338
|
`).filter(o=>!o.includes(".generatesaas")).join(`
|
|
1339
|
-
`);return r===n?!1:(
|
|
1339
|
+
`);return r===n?!1:(xi(t,r,"utf-8"),!0)}function Ti(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),n=ze(t,Ie),r;try{r=JSON.parse(ar(n,"utf-8"))}catch{G.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let o=await G.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(G.isCancel(o)&&(G.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)}),G.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{G.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let i=[],a=[];for(let s of Hc(r.aiTools))ir(ze(t,s))&&i.push(s);for(let s of Gc)ir(ze(t,s))&&i.push(s);ir(ze(t,z))&&i.push(z+"/");for(let s of Kc){let u=ze(t,s.file);zc(u,s.removals)?a.push(s.file):dn(u)&&G.log.warn(`Could not auto-modify ${s.file} - manually remove license/heartbeat references.`)}Jc(t)&&a.push(".gitignore");for(let s of i)G.log.info(`Deleted ${s}`);for(let s of a)G.log.info(`Modified ${s}`);G.log.success("Ejected successfully. This project is now fully standalone.")})}var Je=new qc().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.1.0").addHelpText("after",`
|
|
1340
1340
|
Examples:
|
|
1341
1341
|
$ generatesaas init Interactive setup
|
|
1342
1342
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1343
1343
|
$ generatesaas status Check for updates
|
|
1344
1344
|
$ generatesaas auth Set or update API key
|
|
1345
|
-
`);
|
|
1345
|
+
`);fi(Je);ki(Je);bi(Je);Pi(Je);Ri(Je);Ti(Je);Je.parseAsync().catch(e=>{_i.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|