generatesaas 2.2.0 → 2.3.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 +164 -158
- package/dist/skill/content/SKILL.md +0 -36
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,27 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as Pc}from"commander";import*as ii from"@clack/prompts";import{existsSync as Us,readdirSync as Ms,rmSync as Fs}from"fs";import{join as Vs,resolve as Bs}from"path";import{Option as Z}from"commander";import*as k from"@clack/prompts";import*as _t from"@clack/prompts";import rn from"picocolors";function Gn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";_t.intro(rn.bgYellow(rn.black(t)))}function Kn(){_t.outro(rn.yellow("Happy building!"))}import*as m from"@clack/prompts";import f from"picocolors";var st={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},ct={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},xt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ot={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Be={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}},pt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Ie={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var ne={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},K={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},re={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},lt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],dt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],Hn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Dt(e){let t=K[e.databaseProvider].managed,n=re[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var Re=["nextjs","nuxt"],Ge=["fullstack","separate"],Ke=["stripe","polar","none"],He=["smtp","ses","resend"],ze=["postgres","redis","inngest","mailpit"],Je=["claude-code","cursor","codex","gemini-cli","windsurf"],se=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ce=["node","vercel"],pe=["postgres","neon","supabase"],le=["redis","upstash"],Pe=["shared","vendored"];function Ct(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Ye(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Nt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function I(e){return e instanceof Error?e.message:String(e)}function W(e){let t=e?.trim();return t?`${Ye(t)} Companion`:"My Companion"}var Te="https://github.com/Duzbee/OpenCompanion";function de(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function zn(e){return e.desktop===!0&&e.ai===!0}function H(e){if(zn(e)){if(e.companionSource==="shared")throw new Error("A desktop app with AI bundles its own companion daemon, so its companion source must be vendored. Remove the shared companion source, or turn AI off on this project.");return"vendored"}return de(e)}function ue(e){return zn(e)?!0:e.companion===!0&&de(e)==="vendored"}function $t(e){return e.demo===!0&&e.companion===!0?!0:ue(e)}function ut(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Jn=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Re,adoptable:!1,impact:"structural"},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ge,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ce,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:le,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ke,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:se,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:He,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens) and decides whether a companion daemon is bundled inside the packaged app. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"companion",label:"Companion daemon",hint:"Lets your users install a companion daemon that runs their own AI subscriptions (and any device-side work you add) on their hardware. Point it at an existing shared companion like OpenCompanion (default, nothing to maintain), or vendor and publish your own branded daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionSource",label:"Companion source",hint:"Point at an existing shared companion repo (like OpenCompanion), or vendor a branded daemon you own and publish yourself.",category:"Features",kind:"enum",default:e=>H(e),choices:Pe,adoptable:!0,impact:"structural",requires:e=>e.companion===!0||e.desktop===!0&&e.ai===!0,requiresLabel:"requires the companion, or a desktop app with AI"},{key:"companionRepoUrl",label:"Companion repo URL",hint:"GitHub repository of the shared companion this project points at. Its brand.json supplies the daemon identity; your users install from its latest release.",category:"Features",kind:"text",default:()=>Te,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&de(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>W(e.projectName),adoptable:!0,impact:"config",requires:e=>ue(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",requires:e=>ut(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:ze,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:Je,adoptable:!1,impact:"config"}];function si(e,t){return e[t]!==void 0}function Yn(e){return Jn.filter(t=>t.adoptable&&!si(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function qn(e){let t={};for(let n of Jn)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}import{readFile as Xn}from"fs/promises";import{join as ci}from"path";var qe="GENERATESAAS_COMPANION_BRAND_JSON",Wn=["daemon/brand.json","apps/companion/brand.json"];function oe(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`);let r=n.hostname.toLowerCase();if(r!=="github.com"&&r!=="www.github.com")throw new Error(`Only GitHub-hosted shared companions are supported right now (got "${n.hostname}"). Host the companion on GitHub, or vendor your own with --companion-source vendored.`);let o=n.pathname.split("/").filter(Boolean),i=o[0],a=o[1]?.replace(/\.git$/,"");if(!i||!a)throw new Error(`"${t}" is missing the owner/repo path. Use a full GitHub URL like https://github.com/owner/repo.`);return{owner:i,repo:a,canonicalUrl:`https://github.com/${i}/${a}`}}function Zn(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function on(e,t){let n;try{n=JSON.parse(e)}catch{throw new Error(`The companion brand.json from ${t} is not valid JSON.`)}if(typeof n!="object"||n===null)throw new Error(`The companion brand.json from ${t} is not a JSON object.`);let r=n;for(let o of["name","binary","envPrefix"]){let i=r[o];if(typeof i!="string"||i.trim()==="")throw new Error(`The companion brand.json from ${t} is missing a usable "${o}" field. Point at a companion repo built with the GenerateSaaS export pipeline, or vendor your own with --companion-source vendored.`)}return{name:r.name,binary:r.binary,envPrefix:r.envPrefix}}function pi(e,t,n){let r=JSON.parse(e).repoUrl;if(typeof r!="string"||r.trim()==="")return;let o;try{o=oe(r)}catch{throw new Error(`The companion brand.json from ${t} names an unusable repoUrl ("${r}"), so it cannot be verified against ${n.canonicalUrl}. Fix that brand.json, or unset ${qe} to fetch the identity from GitHub.`)}if(!Zn(o,n))throw new Error(`The companion brand.json from ${t} belongs to ${o.canonicalUrl}, but the project points at ${n.canonicalUrl}. Point ${qe} and --companion-repo-url at the same companion, or unset ${qe} to fetch the identity from GitHub.`)}async function li(e,t){let n=ci(e,"apps/companion/brand.json"),r;try{r=await Xn(n,"utf8")}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(r).repoUrl}catch{throw new Error("The template's apps/companion/brand.json is not valid JSON (boilerplate drift).")}if(typeof o!="string"||o.trim()==="")return null;let i;try{i=oe(o)}catch{return null}return Zn(i,t)?on(r,`the template (${n})`):null}async function di(e){for(let t of Wn){let n=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/HEAD/${t}`,r;try{r=await fetch(n)}catch(o){throw new Error(`Could not reach GitHub to read the companion identity (${n}): ${I(o)}. Check your network, or set GENERATESAAS_COMPANION_BRAND_JSON to a local brand.json.`)}if(r.status!==404){if(!r.ok)throw new Error(`GitHub returned ${r.status} for ${n}. Check that ${e.canonicalUrl} exists and is public.`);return on(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Wn.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function Qn(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=oe(t),r=await li(e.projectDir,n);if(r)return r;let o=process.env[qe]?.trim();if(o){let i;try{i=await Xn(o,"utf8")}catch(u){throw new Error(`Could not read ${qe} (${o}): ${I(u)}.`)}let a=`${qe} (${o})`,s=on(i,a);return pi(i,a,n),s}return await di(n)}var tr=["companion"];function an(e){if(!tr.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function nr(e){return tr.some(n=>e[n]===!0)&&(e.ai=!0),e}function rr(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=ui(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&sn(e),n}function sn(e){return ue(e)&&(e.companionSource=H(e),e.companionName===void 0&&(e.companionName=W(e.projectName))),e}function ui(e,t){return e.desktop!==!0?{kind:"none"}:e.ai===!0&&e.companionSource==="shared"?{kind:"shared-source-contradiction"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:e.ai===!0&&e.companionName===void 0?{kind:"daemon-materialized"}:{kind:"none"}}function or(e){let t={};if(e.name!==void 0){if(!Nt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.frontend!==void 0){if(!Re.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Re.join(", ")}`);t.frontend=e.frontend}if(e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!Pe.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${Pe.join(", ")}`);if(e.companion===!1)throw new Error("--companion-source requires the companion; remove --no-companion.");t.companionSource=e.companionSource,t.companion===void 0&&(t.companion=!0)}if(e.companionRepoUrl!==void 0){if(e.companion===!1)throw new Error("--companion-repo-url requires the companion; remove --no-companion.");t.companionRepoUrl=oe(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(t.companionSource==="vendored"&&t.companionRepoUrl!==void 0)throw new Error("--companion-repo-url applies to a shared companion; remove it or use --companion-source shared.");if(an(t),e.desktop===!0&&t.ai===!0&&t.companionRepoUrl!==void 0)throw new Error("--companion-repo-url points at a SHARED companion, but a desktop app with AI bundles its own; remove it, or turn AI off with --no-ai.");if(e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.docker!==void 0&&(t.dockerServices=er(e.docker,ze,"docker service")),e.aiTools!==void 0&&(t.aiTools=er(e.aiTools,Je,"AI tool")),e.currency!==void 0){if(!se.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${se.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ce.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ce.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!le.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${le.join(", ")}`);t.cacheProvider=e.cache}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var ye={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,companion:!1,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function ir(e){let t=e.projectName??ye.projectName,n=e.projectDir??`./${t}`,r=e.appName??Ye(t),o=e.deploymentTarget??ye.deploymentTarget,i=ne[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":ye.databaseProvider),s=e.cacheProvider??(i?"upstash":ye.cacheProvider),u=e.emailProvider??(i?"resend":ye.emailProvider),g=e.dockerServices??(i?ye.dockerServices.filter(h=>h!=="postgres"&&h!=="redis"):ye.dockerServices),l={...ye,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.desktop&&l.ai&&(l.companionSource=H(l)),ue(l)&&l.companionName===void 0&&(l.companionName=W(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=de(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=W(l.projectName)):l.companionRepoUrl===void 0&&(l.companionRepoUrl=Te));for(let h of lt){if(l.deploymentTarget!==h.target)continue;let S=l.databaseProvider===h.provider?"database":"cache";if(l.databaseProvider===h.provider||l.cacheProvider===h.provider)throw new Error(`Incompatible: --deploy ${h.target} + --${S} ${h.provider}. ${h.reason}`)}for(let h of dt)if(l.architecture===h.architecture&&l.deploymentTarget===h.target)throw new Error(`Incompatible: --architecture ${h.architecture} + --deploy ${h.target}. ${h.reason}`);return l}function er(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(i=>i.trim()).filter(Boolean),o=r.filter(i=>!t.includes(i));if(o.length>0)throw new Error(`Invalid ${n}(s): ${o.join(", ")}. Valid values: ${t.join(", ")}`);return r}function A(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function cn(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function ar(e,t){let n=!1;e&&an(e),m.log.info(f.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Nt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return A(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await m.text({message:"App name:",initialValue:Ye(r),validate:d=>{if(!d?.trim())return"App name is required."}});return A(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await m.text({message:"Project location:",initialValue:`./${r}`});return A(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(st),d=await m.select({message:"Frontend framework:",options:c.map(b=>({value:b,label:st[b].label,hint:st[b].hint}))});return A(d),d})();m.log.info(f.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await m.select({message:"Deployment target:",options:ce.map(d=>({value:d,label:ne[d].label,hint:ne[d].hint}))});A(c),s=c}let u=e?.architecture?dt.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(u)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);let g=new Set(dt.filter(c=>c.target===s).map(c=>c.architecture)),l=Ge.filter(c=>!g.has(c)),h=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return m.log.info(`Auto-selected ${ct[d].label} architecture (only compatible option for ${ne[s].label}).`),d}n=!0;let c=await m.select({message:"Architecture:",options:l.map(d=>({value:d,label:ct[d].label,hint:ct[d].hint}))});return A(c),c})(),S=e?.databaseProvider??await(async()=>{n=!0;let c=pe.filter(b=>!lt.some(q=>q.target===s&&q.provider===b));if(c.length===1){let b=c[0];return m.log.info(`Auto-selected ${K[b].label} (only compatible option for ${ne[s].label}).`),b}let d=await m.select({message:"Database provider:",options:c.map(b=>({value:b,label:K[b].label,hint:K[b].hint}))});return A(d),d})(),C=e?.cacheProvider??await(async()=>{n=!0;let c=le.filter(b=>!lt.some(q=>q.target===s&&q.provider===b));if(c.length===1){let b=c[0];return m.log.info(`Auto-selected ${re[b].label} (only compatible option for ${ne[s].label}).`),b}let d=await m.select({message:"Cache provider:",options:c.map(b=>({value:b,label:re[b].label,hint:re[b].hint}))});return A(d),d})();if(ne[s]?.edgeRuntime){let c=Hn.map(d=>` - ${d}`).join(`
|
|
3
|
-
`);
|
|
4
|
-
`),
|
|
5
|
-
`),b=[
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`,scripts:{}}:await(await
|
|
11
|
-
|
|
12
|
-
`)}async function
|
|
13
|
-
`)}function
|
|
14
|
-
`).find(
|
|
15
|
-
`,"",`${t} ai.mdx ${n} card`,r)}async function
|
|
16
|
-
`).find(
|
|
17
|
-
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function
|
|
18
|
-
`,"",`${t} meta.json ${n} nav entry`,
|
|
19
|
-
`,n=await
|
|
20
|
-
`))}}var
|
|
21
|
-
`)}function
|
|
22
|
-
- **Payments:** ${
|
|
23
|
-
- \`apps/companion\` - the source of **${e.companionName??W(e.projectName)}**, the branded companion daemon your users install. Publish releases with \`pnpm companion:publish\`; \`generatesaas update\` flags when a re-release is due.`:S=`
|
|
24
|
-
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\` (your users install it from that repo's releases). It cannot be modified from this repo; to customize device-side behavior, switch \`companionSource\` to \`vendored\` via \`generatesaas update\`.`);let C=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",E=t?"**Navigation:** always use `localePath()` for paths (hardcoded paths break non-default locales); `await navigateTo()` in SSR.":"**Navigation:** `next/link` for links; `redirect()` from `next/navigation` for programmatic redirects in Server Components.";return`# AGENTS.md
|
|
2
|
+
import{Command as Ua}from"commander";import*as Ai from"@clack/prompts";import{existsSync as Xs,readdirSync as Zs,rmSync as Qs}from"fs";import{join as ea,resolve as ta}from"path";import{Option as q}from"commander";import*as y from"@clack/prompts";import*as ft from"@clack/prompts";import Ut from"picocolors";function fn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";ft.intro(Ut.bgYellow(Ut.black(t)))}function gn(){ft.outro(Ut.yellow("Happy building!"))}import*as f from"@clack/prompts";import g from"picocolors";var Je={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},qe={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)"}},gt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},ht={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},hn={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var we={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 Y={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"}]}},ve={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},We=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],Xe=[{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)."}],yn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Oe(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var ke=["nextjs","nuxt"],De=["fullstack","separate"],Ce=["stripe","polar","none"],Ne=["smtp","ses","resend"];var wn=["claude-code","cursor","codex","gemini-cli","windsurf"],ee=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],te=["node","vercel"],ne=["postgres","neon","supabase"],re=["redis","upstash"];function vn(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function yt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function wt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function O(e){return e instanceof Error?e.message:String(e)}var kn=["companion"];function Mt(e){if(!kn.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function bn(e){return kn.some(n=>e[n]===!0)&&(e.ai=!0),e}function Sn(e){let t=Ri(e,e.desktopAi);return delete e.desktopAi,t}function Ri(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function En(e){let t={};if(e.name!==void 0){if(!wt(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(!ke.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${ke.join(", ")}`);t.frontend=e.frontend}if(e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),Mt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!ee.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ee.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!te.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${te.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ne.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ne.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!re.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${re.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 $e={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,companion:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function An(e){let t=e.projectName??$e.projectName,n=e.projectDir??`./${t}`,r=e.appName??yt(t),i=e.deploymentTarget??$e.deploymentTarget,o=Y[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":$e.databaseProvider),a=e.cacheProvider??(o?"upstash":$e.cacheProvider),d=e.emailProvider??(o?"resend":$e.emailProvider),l={...$e,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:d};l.paymentProvider==="none"&&(l.credits=!1);for(let u of We){if(l.deploymentTarget!==u.target)continue;let k=l.databaseProvider===u.provider?"database":"cache";if(l.databaseProvider===u.provider||l.cacheProvider===u.provider)throw new Error(`Incompatible: --deploy ${u.target} + --${k} ${u.provider}. ${u.reason}`)}for(let u of Xe)if(l.architecture===u.architecture&&l.deploymentTarget===u.target)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);return l}function P(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function Ft(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function In(e,t){let n=!1;e&&Mt(e),f.log.info(g.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let p=await f.text({message:"Project name:",placeholder:"my-saas",validate:m=>{if(!m?.trim())return"Project name is required.";if(!wt(m))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return P(p),p})(),i=e?.appName??await(async()=>{n=!0;let p=await f.text({message:"App name:",initialValue:yt(r),validate:m=>{if(!m?.trim())return"App name is required."}});return P(p),p})(),o=e?.projectDir??await(async()=>{n=!0;let p=await f.text({message:"Project location:",initialValue:`./${r}`});return P(p),p==="."?process.cwd():p})(),s=e?.frontend??await(async()=>{n=!0;let p=Object.keys(Je),m=await f.select({message:"Frontend framework:",options:p.map(b=>({value:b,label:Je[b].label,hint:Je[b].hint}))});return P(m),m})();f.log.info(g.bold("Infrastructure"));let a=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let p=await f.select({message:"Deployment target:",options:te.map(m=>({value:m,label:Y[m].label,hint:Y[m].hint}))});P(p),a=p}let d=e?.architecture?Xe.find(p=>p.architecture===e.architecture&&p.target===a):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let l=new Set(Xe.filter(p=>p.target===a).map(p=>p.architecture)),u=De.filter(p=>!l.has(p)),k=e?.architecture??await(async()=>{if(u.length===1){let m=u[0];return f.log.info(`Auto-selected ${qe[m].label} architecture (only compatible option for ${Y[a].label}).`),m}n=!0;let p=await f.select({message:"Architecture:",options:u.map(m=>({value:m,label:qe[m].label,hint:qe[m].hint}))});return P(p),p})(),A=e?.databaseProvider??await(async()=>{n=!0;let p=ne.filter(b=>!We.some(se=>se.target===a&&se.provider===b));if(p.length===1){let b=p[0];return f.log.info(`Auto-selected ${Q[b].label} (only compatible option for ${Y[a].label}).`),b}let m=await f.select({message:"Database provider:",options:p.map(b=>({value:b,label:Q[b].label,hint:Q[b].hint}))});return P(m),m})(),$=e?.cacheProvider??await(async()=>{n=!0;let p=re.filter(b=>!We.some(se=>se.target===a&&se.provider===b));if(p.length===1){let b=p[0];return f.log.info(`Auto-selected ${ve[b].label} (only compatible option for ${Y[a].label}).`),b}let m=await f.select({message:"Cache provider:",options:p.map(b=>({value:b,label:ve[b].label,hint:ve[b].hint}))});return P(m),m})();if(Y[a]?.edgeRuntime){let p=yn.map(m=>` - ${m}`).join(`
|
|
3
|
+
`);f.note(p,"Unavailable on edge runtime")}f.log.info(g.bold("Features"));let v=e?.paymentProvider??await(async()=>{n=!0;let p=await f.select({message:"Payment provider:",options:Ce.map(m=>({value:m,label:gt[m].label,hint:gt[m].hint}))});return P(p),p})(),U=e?.defaultCurrency??await(async()=>{if(v==="none")return"USD";n=!0;let p=await f.select({message:"Default currency:",options:ee.map(m=>({value:m,label:m,hint:we[m].name}))});return P(p),p})(),me=e?.emailProvider??await(async()=>{n=!0;let p=await f.select({message:"Email provider:",options:Ne.map(m=>({value:m,label:ht[m].label,hint:ht[m].hint}))});return P(p),p})(),X=e?.multiTenancy??await(async()=>{n=!0;let p=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return P(p),p})(),fe=e?.blog??await(async()=>{n=!0;let p=await f.confirm({message:"Enable blog?",initialValue:!0});return P(p),p})(),He=e?.docs??await(async()=>{n=!0;let p=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return P(p),p})(),ge=t?.desktopAllowed!==!1,h=e?.desktop??(ge?await(async()=>{n=!0;let p=await f.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return P(p),p})():(f.log.info(g.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),R=e?.ai??await(async()=>{n=!0;let p=await f.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion)",initialValue:!1});return P(p),p})(),F=t?.companionAllowed!==!1,he=R?e?.companion??(F?await(async()=>{n=!0;let p=await f.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 P(p),p})():(f.log.info(g.dim("Companion: available on the Pro plan and up - skipped.")),!1)):!1,C=e?.revenueSharing??await(async()=>{n=!0;let p=await f.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return P(p),p})(),I=v==="none"?!1:e?.credits??await(async()=>{n=!0;let p=await f.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return P(p),p})(),Z=e?.demo,ye=Ft({databaseProvider:A,cacheProvider:$,paymentProvider:v,emailProvider:me,demo:Z}),Ye={};if(ye.length>0&&n){f.log.info(g.bold("Credentials")+g.dim(" all optional - press Enter to skip, fill in .env later"));for(let p of ye)if(n=!0,p.secret){let m=await f.password({message:p.message,mask:"*"});P(m),typeof m=="string"&&m.trim()&&(Ye[p.key]=m.trim())}else{let m=await f.text({message:p.message,placeholder:p.placeholder});P(m),typeof m=="string"&&m.trim()&&(Ye[p.key]=m.trim())}}if(n){let p=[` Name: ${g.cyan(r)}`,` App name: ${g.cyan(i)}`,` Location: ${g.cyan(o)}`,` Frontend: ${g.cyan(Je[s].label)}`,` Architecture: ${g.cyan(qe[k].label)}`].join(`
|
|
4
|
+
`),m=[` Deploy target: ${g.cyan(Y[a]?.label??"Node.js / Docker")}`,` Database: ${g.cyan(Q[A].label)}`,` Cache: ${g.cyan(ve[$].label)}`].filter(Boolean).join(`
|
|
5
|
+
`),b=[v!=="none"?` Payment: ${g.cyan(gt[v].label)} (${U})`:` Payment: ${g.dim("none")}`,` Credits: ${I?g.cyan("Yes"):g.dim("No")}`,` AI features: ${R?g.cyan("Yes"):g.dim("No")}`,...R?[` Companion: ${he?g.cyan("Yes"):g.dim("No")}`]:[],` Email: ${g.cyan(ht[me].label)}`,` Multi-tenancy: ${X?g.cyan("Yes"):g.dim("No")}`,` Blog: ${fe?g.cyan("Yes"):g.dim("No")}`,` Docs app: ${He?g.cyan("Yes"):g.dim("No")}`,` Desktop app: ${h?g.cyan("Yes"):g.dim("No")}`,` Rev. sharing: ${C?g.cyan("Yes"):g.dim("No")}`].join(`
|
|
6
|
+
`),se=[g.bold("Project"),p,"",g.bold("Infrastructure"),m,"",g.bold("Features"),b];if(ye.length>0){let Ii=ye.map(mn=>{let Pi=Ye[mn.key]?g.green("provided"):g.dim("skipped");return` ${mn.key}: ${Pi}`}).join(`
|
|
7
|
+
`);se.push("",g.bold("Credentials"),Ii)}f.note(se.join(`
|
|
8
|
+
`),"Summary");let un=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(un)||!un)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:r,appName:i,projectDir:o,frontend:s,architecture:k,deploymentTarget:a,databaseProvider:A,cacheProvider:$,paymentProvider:v,emailProvider:me,multiTenancy:X,blog:fe,docs:He,desktop:h,ai:R,companion:he,revenueSharing:C,credits:I,defaultCurrency:U,...Object.keys(Ye).length>0?{credentials:Ye}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...Z!==void 0?{demo:Z}:{}}}import{createReadStream as Cn,existsSync as Ui}from"fs";import{mkdir as Mi}from"fs/promises";import{join as Fi}from"path";import{Readable as Vi}from"stream";import{pipeline as Yt}from"stream/promises";import{extract as Bi}from"tar";import{join as be}from"path";import{homedir as Ti}from"os";var Ze=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",K=".generatesaas",ae=be(K,"manifest.json"),Pn=be(K,"hashes.json"),vt=be(K,"template-hashes.json"),kt=be(K,"template"),Rn=be(K,"staging"),Tn=be(K,"staging.json"),ie=be(Ti(),".generatesaas");var N=class extends Error{constructor(n,r,i){super(r);this.status=n;this.body=i}status;body;name="ApiError"};function oe(e){return{apiKey:e,baseUrl:Ze}}async function ce(e,t,n){let r=`${e.baseUrl}${t}`,i=await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/2.3.0"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new N(i.status,o,s)}return i}import{existsSync as xi,readFileSync as _i,writeFileSync as Oi,mkdirSync as Di}from"fs";import{dirname as Ci}from"path";import*as pe from"@clack/prompts";function Qe(){if(!xi(ie))return null;try{let e=JSON.parse(_i(ie,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&pe.log.warning(`Found old GitHub token in ${ie}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Se(e){Di(Ci(ie),{recursive:!0}),Oi(ie,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function Le(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=Qe();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 et()}async function et(){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 Ni}from"fs/promises";async function le(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ni(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 ce(e,"/versions")).json()}async function Vt(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await ce(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(n){if(n instanceof N&&n.status===404)return null;throw n}}async function xn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await ce(e,`/skill/${encodeURIComponent(t)}`)).json()}function bt(e){if(!(e instanceof N)||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 _n(e){return{frontend:e.frontend,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function Bt(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await ce(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function On(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await ce(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Kt(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 Dn(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 i=await r.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${r.status}`)}return await r.json()}var Gt=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),zt=new Set(["pnpm-lock.yaml"]);function je(e){if(Ht(e))return!0;for(let t of e.split("/"))if(zt.has(t))return!0;return!1}var $i=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md"]),Li=["scripts/docs-lint.ts"],ji=["docs/superpowers","packages/cli","packages/cli-api","apps/companion","docs/opencompanion","infra/docker-compose.yml",".claude/commands",".claude/skills/web-next-port",".claude/skills/web-next-port-workspace",".claude/settings.local.json",".claude/worktrees"];function Ht(e){let t=e.split("/");for(let n of t)if(Gt.has(n))return!0;if(Li.includes(e))return!1;if($i.has(t[0]))return!0;for(let n of ji)if(e===n||e.startsWith(n+"/"))return!0;return!1}async function St(e,t,n){await Mi(n,{recursive:!0});let r=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(r){let a=Fi(r,`v${t}.tar.gz`);if(!Ui(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await Yt(Cn(a),Jt(n));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await Yt(Cn(i),Jt(n));return}let o=await ce(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=Vi.fromWeb(o.body);await Yt(s,Jt(n))}function Jt(e){return Bi({cwd:e,strip:1,filter:t=>{let n=t.replace(/^[^/]+\//,"");return n?!Ht(n):!0},sync:!1})}import{readdir as to,readFile as it,rm as jn,writeFile as ot}from"fs/promises";import{join as ue}from"path";import{readFile as rt,rm as Xi}from"fs/promises";import{join as nt}from"path";import{mkdir as Ki,readdir as Gi,rm as zi,rmdir as Hi,writeFile as Yi}from"fs/promises";import{dirname as Et,join as Ji,relative as qi,sep as Wi}from"path";function Ee(e){return e.split(Wi).join("/")}async function At(e){await Ki(e,{recursive:!0})}async function c(e,t){await At(Et(e)),await Yi(e,t,"utf-8")}async function tt(e,t){await zi(e,{force:!0});let n=Et(e);for(;n!==t&&n!==Et(n);){try{await Hi(n)}catch{return}n=Et(n)}}async function Ae(e,t,n){let r=[],i=await Gi(e,{withFileTypes:!0});for(let o of i){let s=Ji(e,o.name),a=Ee(qi(t,s));n(a)||(o.isDirectory()?r.push(...await Ae(s,t,n)):o.isFile()&&r.push(s))}return r}function Zi(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function de(e,t,n,r){let i=Zi(n);if(e.match(i)===null)throw new Error(`${r}: expected gsaas ${n} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${n}-start`)||o.includes(`gsaas:${n}-end`))throw new Error(`${r}: an unbalanced gsaas ${n} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
|
|
11
|
+
|
|
12
|
+
`)}async function L(e,t,n,r,i){let o=await rt(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(o.indexOf(t,s+t.length)!==-1)throw new Error(`${i}: the ${r} seam appears more than once (boilerplate drift).`);await c(e,o.slice(0,s)+n+o.slice(s+t.length))}async function It(e,t,n,r){let i=/\n([\t ]+)"/.exec(await rt(e,"utf-8"))?.[1];if(i!==n){let o=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${r}: expected ${e} to be ${o(n)}-indented, but it is ${i===void 0?"not indented":o(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await c(e,`${JSON.stringify(t,null,n)}
|
|
13
|
+
`)}function Pt(e){return e.frontend==="nextjs"?"next":"nuxt"}async function Qi(e,t,n,r){let i=nt(e,"ai.mdx"),s=(await rt(i,"utf-8")).split(`
|
|
14
|
+
`).find(a=>a.includes(`href="${n}"`));if(s===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${n} (boilerplate drift).`);await L(i,`${s}
|
|
15
|
+
`,"",`${t} ai.mdx ${n} card`,r)}async function eo(e,t,n,r){let i=nt(e,"ai.mdx"),o=`| **${n}** |`,a=(await rt(i,"utf-8")).split(`
|
|
16
|
+
`).find(d=>d.startsWith(o));if(a===void 0)throw new Error(`${r}: expected the ai.mdx "${n}" hub-table row (boilerplate drift).`);await L(i,`${a}
|
|
17
|
+
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function Nn(e,t,n,r,i,o){let s=nt(e,"docs",t);await Xi(nt(s,n),{recursive:!0}),await L(nt(s,"meta.json"),` "${n}",
|
|
18
|
+
`,"",`${t} meta.json ${n} nav entry`,i);for(let a of r)await Qi(s,t,a,i);o!==void 0&&await eo(s,t,o,i)}async function $n(e){let t=`import { config } from "@repo/config";
|
|
19
|
+
`,n=await rt(e,"utf-8");if(!n.includes(t))return;let r=n.replace(t,""),i=r.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(i)||await c(e,r)}var no=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function Un(e){await Promise.all(no.map(t=>jn(ue(e,t),{recursive:!0,force:!0})))}var ro=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function Mn(e){let t="removeDesktopDemoScreen";await jn(ue(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let n of ro){let r=ue(e,n);await ot(r,de(await it(r,"utf-8"),n,"demo",t))}}var io="packages/config/src/blog.ts";async function Fn(e){let t=ue(e,io),n=await it(t,"utf-8"),r=Ln(Ln(n,"blogCategories",t),"blogAuthors",t);await ot(t,r)}function Ln(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 Vn(e){let t=ue(e,"packages/i18n/translations"),n;try{n=await to(t)}catch{return}for(let r of n){let i=ue(t,r,"web.json"),o;try{o=await it(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await ot(i,JSON.stringify(s,null," ")+`
|
|
20
|
+
`))}}var oo="packages/config/src/ai/tasks.ts";async function Bn(e){let t=ue(e,oo),n=await it(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 ot(t,r)}async function Kn(e,t){let n=ue(e,".claude","settings.json"),r;try{r=await it(n,"utf8")}catch{return}let i=JSON.parse(r);delete i.alwaysThinkingEnabled,delete i.enableAllProjectMcpServers,i.env&&(delete i.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(i.env).length===0&&delete i.env),i.permissions?.allow&&(i.permissions.allow=i.permissions.allow.filter(o=>so(o,t))),await ot(n,JSON.stringify(i,null," ")+`
|
|
21
|
+
`)}function so(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as Gn}from"path";var ao={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},co={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},po={redis:"Redis",upstash:"Upstash Redis"},lo={node:"Node.js / Docker",vercel:"Vercel"},uo={stripe:"Stripe",polar:"Polar"};function mo(e){let t=e.frontend==="nuxt",n=t?"Nuxt 4":"Next.js 16",r=t?"apps/web-nuxt":"apps/web-next",i=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",o=e.architecture==="fullstack",s=o?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",a=o?`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.",d=po[e.cacheProvider],l=lo[e.deploymentTarget],u=e.paymentProvider==="none"?"":`
|
|
22
|
+
- **Payments:** ${uo[e.paymentProvider]}`,k=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",A=e.companion?"\n- **Companion daemon** - your users install OpenCompanion on a machine they control and pair it with their account. Everything you own lives in this repo: the `/companion/*` routes, the relay, the Companions page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",$=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",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
|
|
25
23
|
|
|
26
24
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
27
25
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -47,13 +45,13 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
47
45
|
|
|
48
46
|
## Stack
|
|
49
47
|
|
|
50
|
-
- **Frontend:** ${n} ${
|
|
51
|
-
- **API:** Hono, RPC-typed. ${
|
|
52
|
-
- **Database:** Drizzle ORM + ${
|
|
53
|
-
- **Cache + jobs:** ${
|
|
54
|
-
- **Auth:** Better Auth${
|
|
55
|
-
- **Email:** ${
|
|
56
|
-
- **Deploy:** ${
|
|
48
|
+
- **Frontend:** ${n} ${s}
|
|
49
|
+
- **API:** Hono, RPC-typed. ${a}
|
|
50
|
+
- **Database:** Drizzle ORM + ${ao[e.databaseProvider]}
|
|
51
|
+
- **Cache + jobs:** ${d} + Inngest
|
|
52
|
+
- **Auth:** Better Auth${u}
|
|
53
|
+
- **Email:** ${co[e.emailProvider]}
|
|
54
|
+
- **Deploy:** ${l}
|
|
57
55
|
|
|
58
56
|
## Where things live (extend these - don't reinvent)
|
|
59
57
|
|
|
@@ -63,8 +61,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
63
61
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
64
62
|
- \`packages/runtime/src/env.ts\` - the validated (Zod) env schema. New env var \u2192 add it here **and** to \`.env.example\` (the committed reference); set the local value in \`.env\`.
|
|
65
63
|
- \`packages/{payments,mail,sms,storage,notifications}\` - config-gated integrations. Every provider's files stay even when its feature is off, so flipping a flag is enough to enable it.
|
|
66
|
-
- \`${r}\` - the ${n} app (${
|
|
67
|
-
- \`docs/${t?"nuxt":"next"}/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${
|
|
64
|
+
- \`${r}\` - the ${n} app (${i}).${A}
|
|
65
|
+
- \`docs/${t?"nuxt":"next"}/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${k}.
|
|
68
66
|
|
|
69
67
|
## Code style
|
|
70
68
|
|
|
@@ -81,8 +79,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
81
79
|
|
|
82
80
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
83
81
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
84
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${
|
|
85
|
-
- ${
|
|
82
|
+
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${$} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
83
|
+
- ${v}
|
|
86
84
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
87
85
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
88
86
|
|
|
@@ -93,14 +91,12 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
93
91
|
## This project
|
|
94
92
|
|
|
95
93
|
Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
|
|
96
|
-
`}async function
|
|
97
|
-
`)}import{join as
|
|
94
|
+
`}async function zn(e){await c(Gn(e.projectDir,"AGENTS.md"),mo(e)),await c(Gn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
95
|
+
`)}import{join as fo}from"path";var go={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ho(e){let t=e.appName.trim()||e.projectName,n=e.frontend==="nuxt",r=n?"Nuxt 4":"Next.js 16",i=n?"apps/web-nuxt":"apps/web-next",o=go[e.databaseProvider],s=e.architecture==="fullstack"?`${r} app at \`${i}/\` 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 \`${i}/\` and a separate Hono backend at \`apps/backend/\`.`,a=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
98
96
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
99
97
|
- API: http://localhost:3010
|
|
100
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
This project ships with Dockerfiles for each app. Build images with \`docker build\` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).${a?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,h=e.aiTools.length>0?"To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: `update my GenerateSaaS project`.":"To pull the latest boilerplate changes into this project, install an AI coding agent (Claude Code / Cursor / Codex / Gemini CLI / Windsurf) and ask: `update my GenerateSaaS project`. The skill bundle that drives the update lives under each tool's skill root.";return`# ${t}
|
|
98
|
+
- Inngest dev server: http://127.0.0.1:8288`,d=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
99
|
+
`,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\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
|
|
104
100
|
|
|
105
101
|
${s}
|
|
106
102
|
|
|
@@ -109,7 +105,7 @@ ${s}
|
|
|
109
105
|
- **Frontend:** ${r}
|
|
110
106
|
- **Backend:** Hono (TypeScript, RPC-typed)
|
|
111
107
|
- **Auth:** Better Auth
|
|
112
|
-
- **ORM / DB:** Drizzle + ${
|
|
108
|
+
- **ORM / DB:** Drizzle + ${o}
|
|
113
109
|
- **Background jobs:** Inngest
|
|
114
110
|
- **i18n:** ${n?"@nuxtjs/i18n":"next-intl"}
|
|
115
111
|
|
|
@@ -120,11 +116,11 @@ pnpm install
|
|
|
120
116
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
121
117
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
122
118
|
# reference. All apps load the single root \`.env\`.
|
|
123
|
-
${
|
|
119
|
+
${d}pnpm db:setup # first run: create the database schema (idempotent)
|
|
124
120
|
pnpm dev
|
|
125
121
|
\`\`\`
|
|
126
122
|
|
|
127
|
-
${
|
|
123
|
+
${a}
|
|
128
124
|
|
|
129
125
|
## Build your SaaS
|
|
130
126
|
|
|
@@ -156,19 +152,18 @@ pnpm dlx generatesaas eject
|
|
|
156
152
|
|
|
157
153
|
## Updates
|
|
158
154
|
|
|
159
|
-
|
|
160
|
-
`}async function
|
|
161
|
-
`)}async function ia(e,t,n){let r=Ce(e,"apps/electron/dev-app-update.yml");try{await ra(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await p(r,`provider: generic
|
|
155
|
+
To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
|
|
156
|
+
`}async function Hn(e){await c(fo(e.projectDir,"README.md"),ho(e))}import{access as yo}from"fs/promises";import{join as Ue}from"path";async function wo(e,t,n){let r=Ue(e,"apps/electron/dev-app-update.yml");try{await yo(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await c(r,`provider: generic
|
|
162
157
|
url: ${t}
|
|
163
158
|
updaterCacheDirName: ${n}
|
|
164
|
-
`)}function
|
|
165
|
-
`)}async function
|
|
159
|
+
`)}function vo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function ko(e,t){let n=vn(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${n.replace(/-/g,"")}`,productName:e,protocol:n}}var st={name:"OpenCompanion",binary:"opencompanion",envPrefix:"OPENCOMPANION",repoUrl:"https://github.com/AlexChelan/OpenCompanion",installBase:"https://github.com/AlexChelan/OpenCompanion/releases/latest/download"};function bo(e){return e.companion?["{"," enabled: true,",' clientId: "companion",'," daemon: {",` name: ${JSON.stringify(st.name)},`,` binary: ${JSON.stringify(st.binary)},`,` envPrefix: ${JSON.stringify(st.envPrefix)},`,` repoUrl: ${JSON.stringify(st.repoUrl)},`,` installBase: ${JSON.stringify(st.installBase)}`," }"," }"].join(`
|
|
160
|
+
`):'{ enabled: false, clientId: "companion" }'}async function Yn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=e.paymentProvider!=="none",r=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",o=vo(i),s=e.demo?"false":"true",a=e.demo?`{
|
|
166
161
|
enableInDev: true,
|
|
167
162
|
chatwoot: {
|
|
168
163
|
baseUrl: "https://support.alexchelan.com",
|
|
169
164
|
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
170
165
|
}
|
|
171
|
-
}`:"{}",
|
|
166
|
+
}`:"{}",d=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",l=ko(t,o),u=`https://cdn.${o}/desktop`,k=bo(e),A=`import type { AppConfig } from "@repo/config/types";
|
|
172
167
|
import { desktopConfig } from "./desktop.mjs";
|
|
173
168
|
import { observabilityConfig } from "./observability.mjs";
|
|
174
169
|
import { supportConfig } from "./support.mjs";
|
|
@@ -179,9 +174,9 @@ const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim
|
|
|
179
174
|
export const config: AppConfig = {
|
|
180
175
|
siteName: "${t}",
|
|
181
176
|
fullSiteName: "${t}",
|
|
182
|
-
domain: "${
|
|
177
|
+
domain: "${i}",
|
|
183
178
|
baseUrl: process.env.BASE_URL ?? "${r}",
|
|
184
|
-
indexable: ${
|
|
179
|
+
indexable: ${s},
|
|
185
180
|
logo: {
|
|
186
181
|
main: "/images/logo.svg",
|
|
187
182
|
square: "/images/logo-square.svg"
|
|
@@ -206,16 +201,16 @@ export const config: AppConfig = {
|
|
|
206
201
|
limitPerSecond: 3,
|
|
207
202
|
senders: {
|
|
208
203
|
transactional: {
|
|
209
|
-
email: "noreply@${
|
|
204
|
+
email: "noreply@${o}",
|
|
210
205
|
senderName: "${t}"
|
|
211
206
|
},
|
|
212
207
|
marketing: {
|
|
213
|
-
email: "hello@${
|
|
208
|
+
email: "hello@${o}",
|
|
214
209
|
senderName: "${t}",
|
|
215
210
|
signatureName: "Alex"
|
|
216
211
|
},
|
|
217
212
|
support: {
|
|
218
|
-
email: "support@${
|
|
213
|
+
email: "support@${o}",
|
|
219
214
|
senderName: "${t} Support"
|
|
220
215
|
}
|
|
221
216
|
},
|
|
@@ -243,7 +238,7 @@ export const config: AppConfig = {
|
|
|
243
238
|
prefix: "key_"
|
|
244
239
|
},
|
|
245
240
|
apiDocs: true,
|
|
246
|
-
performanceMonitor: { enabled: ${
|
|
241
|
+
performanceMonitor: { enabled: ${d} },
|
|
247
242
|
observability: observabilityConfig,
|
|
248
243
|
notifications: {
|
|
249
244
|
enabled: true,
|
|
@@ -283,7 +278,7 @@ export const config: AppConfig = {
|
|
|
283
278
|
}`:`{
|
|
284
279
|
base: "${e.defaultCurrency}",
|
|
285
280
|
list: [
|
|
286
|
-
{ symbol: "${
|
|
281
|
+
{ symbol: "${we[e.defaultCurrency].symbol}", name: "${we[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${we[e.defaultCurrency].place}", space: ${we[e.defaultCurrency].space} }
|
|
287
282
|
],
|
|
288
283
|
countryMap: {
|
|
289
284
|
default: "${e.defaultCurrency}"
|
|
@@ -331,8 +326,8 @@ export const config: AppConfig = {
|
|
|
331
326
|
}
|
|
332
327
|
},
|
|
333
328
|
desktop: desktopConfig,
|
|
334
|
-
// Companion:
|
|
335
|
-
companion: ${
|
|
329
|
+
// Companion: the OpenCompanion daemon your users install to run their own subscription CLIs for this app. Off by default.
|
|
330
|
+
companion: ${k},
|
|
336
331
|
// Outward MCP server exposing the capability layer to external agents. Its code ships with every
|
|
337
332
|
// project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
|
|
338
333
|
mcpServer: { enabled: ${e.demo?"true":"false"} },
|
|
@@ -376,7 +371,7 @@ export * from "./pricing";
|
|
|
376
371
|
export * from "./roles";
|
|
377
372
|
export * from "./section-tabs";
|
|
378
373
|
export * from "./tenancy";
|
|
379
|
-
|
|
374
|
+
`,$=Ue(e.projectDir,"packages/config/src/index.ts");await c($,A),await c(Ue(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
380
375
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
381
376
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
382
377
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -384,9 +379,9 @@ export * from "./tenancy";
|
|
|
384
379
|
|
|
385
380
|
export const desktopConfig = {
|
|
386
381
|
enabled: ${e.desktop},
|
|
387
|
-
appId: "${
|
|
388
|
-
productName: "${
|
|
389
|
-
protocol: "${
|
|
382
|
+
appId: "${l.appId}",
|
|
383
|
+
productName: "${l.productName}",
|
|
384
|
+
protocol: "${l.protocol}",
|
|
390
385
|
baseUrl: "${r}",
|
|
391
386
|
// Name of the app's data folder (created under the OS app-data dir). Where the app
|
|
392
387
|
// and its AI agents persist files - logs, gathered data, generated artifacts. Rename
|
|
@@ -395,7 +390,12 @@ export const desktopConfig = {
|
|
|
395
390
|
// Public base URL the release workflow uploads to; electron-updater polls
|
|
396
391
|
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
397
392
|
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
398
|
-
autoUpdate: { url: "${
|
|
393
|
+
autoUpdate: { url: "${u}" },
|
|
394
|
+
// Whether the support live-chat widget you configured in config.support (Crisp,
|
|
395
|
+
// Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
|
|
396
|
+
// every surface. Set false to keep live chat on your website only - the app then
|
|
397
|
+
// mounts no widget and its CSP never names the provider's origins.
|
|
398
|
+
supportChat: true,
|
|
399
399
|
agents: {
|
|
400
400
|
// Feature toggles only. Agents run in the app's main process (companion supervision +
|
|
401
401
|
// the daemon transport bridge), driven through the @repo/agent-core seam - typed
|
|
@@ -420,10 +420,15 @@ export const desktopConfig = {
|
|
|
420
420
|
// connection lock). Default false: the app is local-first and connecting is an
|
|
421
421
|
// OPTIONAL, explicit user action. Set true for a structurally private product - the
|
|
422
422
|
// connect surface never renders AND the daemon refuses pairing.
|
|
423
|
-
connectionLock: false
|
|
423
|
+
connectionLock: false,
|
|
424
|
+
// Whether agent work continues after the window closes. OFF by default: the runtime is a
|
|
425
|
+
// child process of the app and is killed at quit. Turn it on if your product's value
|
|
426
|
+
// depends on schedules firing while the app is closed; end users then get a
|
|
427
|
+
// "Keep running after I close the window" toggle.
|
|
428
|
+
background: false
|
|
424
429
|
}
|
|
425
430
|
};
|
|
426
|
-
`),await
|
|
431
|
+
`),await c(Ue(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
|
|
427
432
|
// TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
|
|
428
433
|
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
429
434
|
|
|
@@ -432,13 +437,13 @@ export const tenancyConfig = ${e.multiTenancy?`{
|
|
|
432
437
|
organizationLimit: 5,
|
|
433
438
|
billingScope: "${e.demo?"organization":"user"}"
|
|
434
439
|
}`:"{ multiTenant: false }"};
|
|
435
|
-
`),await
|
|
440
|
+
`),await c(Ue(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
|
|
436
441
|
// the TypeScript config index reads it directly (the Electron main + renderer and
|
|
437
442
|
// the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
|
|
438
443
|
// index re-exports this as config.support.
|
|
439
444
|
|
|
440
|
-
export const supportConfig = ${
|
|
441
|
-
`),await
|
|
445
|
+
export const supportConfig = ${a};
|
|
446
|
+
`),await c(Ue(e.projectDir,"packages/config/src/observability.mjs"),`// Plain-JS observability (error reporting) config. NO env reads, so tooling that
|
|
442
447
|
// cannot import the TypeScript config index reads it directly (the Electron main +
|
|
443
448
|
// renderer, which have no env at all once packaged). Mirrors the support.mjs
|
|
444
449
|
// pattern. The config index re-exports this as config.observability.
|
|
@@ -456,8 +461,8 @@ export const observabilityConfig = {
|
|
|
456
461
|
dsn: ""
|
|
457
462
|
}
|
|
458
463
|
};
|
|
459
|
-
`),e.desktop&&await
|
|
460
|
-
`)}async function
|
|
464
|
+
`),e.desktop&&await wo(e.projectDir,u,`${l.protocol}-updater`)}import{join as So}from"path";function Eo(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function qt(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(`
|
|
465
|
+
`)}async function Jn(e){let t=So(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let $=`import type { PricingConfig } from "@repo/config/types";
|
|
461
466
|
|
|
462
467
|
export const pricingConfig: PricingConfig = {
|
|
463
468
|
defaultPlan: "free",
|
|
@@ -486,21 +491,21 @@ export const pricingConfig: PricingConfig = {
|
|
|
486
491
|
credits: { enabled: false },
|
|
487
492
|
products: { enabled: false, items: [] }
|
|
488
493
|
};
|
|
489
|
-
`;await
|
|
494
|
+
`;await c(t,$);return}let r=e.paymentProvider,i=Eo(r),o=e.credits,s=!!e.ai,a=qt({credits:5,rateLimit:100,withCredits:o,...s&&{maxSchedules:3}}),d=qt({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxSchedules:10}}),l=qt({credits:50,rateLimit:5e3,withCredits:o}),u=n==="USD"?"":` // !! ${n} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
490
495
|
// !! USD), but your plan prices and credit purchases are denominated in ${n}. Verify that the
|
|
491
496
|
// !! ${n} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
492
497
|
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
493
|
-
`;
|
|
498
|
+
`;o&&n!=="USD"&&console.warn(`
|
|
494
499
|
!! ${n} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
495
500
|
!! plan prices and credit purchases are denominated in ${n}. At the shipped economics 1 credit
|
|
496
501
|
!! carries ~0.42 USD of AI cost - verify every ${n} price still covers it (see the comment on the
|
|
497
502
|
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
498
|
-
`);let
|
|
503
|
+
`);let k=o?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
499
504
|
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
500
505
|
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
501
506
|
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
502
507
|
// full utilization runs you at a loss.
|
|
503
|
-
${
|
|
508
|
+
${u} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",A=`import type { PricingConfig } from "@repo/config/types";
|
|
504
509
|
|
|
505
510
|
export const pricingConfig: PricingConfig = {
|
|
506
511
|
defaultPlan: "free",
|
|
@@ -524,7 +529,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
524
529
|
amounts: { ${n}: 0 }
|
|
525
530
|
}
|
|
526
531
|
],
|
|
527
|
-
${
|
|
532
|
+
${a}
|
|
528
533
|
},
|
|
529
534
|
{
|
|
530
535
|
id: "starter",
|
|
@@ -539,18 +544,18 @@ ${s}
|
|
|
539
544
|
],
|
|
540
545
|
prices: [
|
|
541
546
|
{
|
|
542
|
-
${
|
|
547
|
+
${i}
|
|
543
548
|
interval: "month",
|
|
544
549
|
amounts: { ${n}: 9 }
|
|
545
550
|
},
|
|
546
551
|
{
|
|
547
|
-
${
|
|
552
|
+
${i}
|
|
548
553
|
interval: "year",
|
|
549
554
|
amounts: { ${n}: 90 },
|
|
550
555
|
anchorAmounts: { ${n}: 109 }
|
|
551
556
|
}
|
|
552
557
|
],
|
|
553
|
-
${
|
|
558
|
+
${d}
|
|
554
559
|
},
|
|
555
560
|
{
|
|
556
561
|
id: "pro",
|
|
@@ -568,33 +573,33 @@ ${u}
|
|
|
568
573
|
],
|
|
569
574
|
prices: [
|
|
570
575
|
{
|
|
571
|
-
${
|
|
576
|
+
${i}
|
|
572
577
|
interval: "month",
|
|
573
578
|
amounts: { ${n}: 29 },
|
|
574
579
|
anchorAmounts: { ${n}: 39 },
|
|
575
580
|
featured: true
|
|
576
581
|
},
|
|
577
582
|
{
|
|
578
|
-
${
|
|
583
|
+
${i}
|
|
579
584
|
interval: "year",
|
|
580
585
|
amounts: { ${n}: 290 },
|
|
581
586
|
anchorAmounts: { ${n}: 349 }
|
|
582
587
|
}
|
|
583
588
|
],
|
|
584
|
-
${
|
|
589
|
+
${l}
|
|
585
590
|
}
|
|
586
591
|
],
|
|
587
|
-
${
|
|
592
|
+
${k},
|
|
588
593
|
products: {
|
|
589
594
|
enabled: false,
|
|
590
595
|
items: []
|
|
591
596
|
}
|
|
592
597
|
};
|
|
593
|
-
`;await
|
|
594
|
-
`)}function
|
|
595
|
-
`)}async function
|
|
596
|
-
`+
|
|
597
|
-
`+
|
|
598
|
+
`;await c(t,A)}var Ao={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"}]},Io={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 at(e,t){return t?e.map(n=>{let r=t[n.key];return r?{...n,defaultValue:r,comment:void 0}:n}):e}function ct(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 Wt(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Wn(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function Po(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 Rt(e,t,n,r){e.push(r==="example"?`${t}=`:`${t}=${n}`)}function qn(e,t){let n=t==="example"?void 0:e.credentials,{apiUrl:r,baseUrl:i}=Wn(e),o=[];e.architecture==="separate"?o.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${r}`,`BASE_URL=${i}`):o.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),o.push("","# Database"),ct(at(Q[e.databaseProvider].envVars,n),o),o.push("","# Cache"),ct(at(ve[e.cacheProvider].envVars,n),o),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Rt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Rt(o,"CONTENT_API_KEY",Wt(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Rt(o,"INNGEST_EVENT_KEY",Wt(32),t),Rt(o,"INNGEST_SIGNING_KEY",Wt(32),t),o.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(o.push("","# API Port (standalone backend)","API_PORT=3010"),o.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let s=Ao[e.emailProvider];if(s&&(o.push("","# Email"),ct(at(s,n),o)),e.paymentProvider!=="none"){let a=Io[e.paymentProvider];a&&(o.push("","# Payment"),ct(at(a,n),o))}return e.demo&&(o.push("","# Captcha (Cloudflare Turnstile)"),ct(at([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],n),o)),o.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY="),o.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only provider API key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database."),o.push(""),o.join(`
|
|
599
|
+
`)}function Ro(e){let{apiUrl:t}=Wn(e),n=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",r=["# API Configuration",`${n}=${t}`],i=Po(e);return i&&e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${n}=${i.backend}`),r.push(""),r.join(`
|
|
600
|
+
`)}async function Xn(e){let t=Ro(e);await c(`${e.projectDir}/.env`,t+`
|
|
601
|
+
`+qn(e,"env")),await c(`${e.projectDir}/.env.example`,t+`
|
|
602
|
+
`+qn(e,"example"))}import{join as To}from"path";async function Zn(e){let t=Oe(e),n=[],r=[];t.includes("postgres")&&(n.push(` postgres:
|
|
598
603
|
image: postgres:18-alpine
|
|
599
604
|
ports:
|
|
600
605
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -630,16 +635,16 @@ ${h},
|
|
|
630
635
|
image: inngest/inngest:v1.17.4
|
|
631
636
|
ports:
|
|
632
637
|
- "\${INNGEST_PORT:-8288}:8288"
|
|
633
|
-
command: inngest dev`);let
|
|
638
|
+
command: inngest dev`);let i=`services:
|
|
634
639
|
${n.join(`
|
|
635
640
|
|
|
636
641
|
`)}
|
|
637
|
-
`;
|
|
642
|
+
`;r.length>0&&(i+=`
|
|
638
643
|
volumes:
|
|
639
644
|
${r.join(`
|
|
640
645
|
`)}
|
|
641
|
-
`),await
|
|
642
|
-
`)}import{join as
|
|
646
|
+
`),await c(To(e.projectDir,"infra/docker-compose.yml"),i)}import{join as xo}from"path";function _o(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 Oo(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 Qn(e){let t={version:"0.2.0",configurations:_o(e),compounds:Oo(e)};await c(xo(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
647
|
+
`)}import{join as Do}from"path";async function er(e){if(e.architecture!=="separate")return;await c(Do(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
|
|
643
648
|
import app from "@repo/api";
|
|
644
649
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
645
650
|
|
|
@@ -670,12 +675,12 @@ bootstrap().catch((error) => {
|
|
|
670
675
|
logger.error("[Backend] Fatal error", error);
|
|
671
676
|
process.exit(1);
|
|
672
677
|
});
|
|
673
|
-
`)}import{readFile as
|
|
674
|
-
export const pool = db.$client
|
|
675
|
-
import { drizzle } from "drizzle-orm/neon-
|
|
676
|
-
export const db = drizzle(
|
|
678
|
+
`)}import{readFile as Co}from"fs/promises";import{join as No}from"path";var Xt='import { drizzle } from "drizzle-orm/node-postgres";',Zt=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
679
|
+
export const pool = db.$client;`,$o={postgres:{importLine:Xt,instantiation:Zt},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
|
|
680
|
+
import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
|
|
681
|
+
export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
677
682
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
678
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
683
|
+
export const db = drizzle(client, { schema });`}};async function tr(e){let t=No(e.projectDir,"packages/database/src/index.ts"),n=await Co(t,"utf-8");if(!n.includes(Xt)||!n.includes(Zt))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=$o[e.databaseProvider],i=n.replace(Xt,r.importLine).replace(Zt,r.instantiation);await c(t,i)}import{join as Tt}from"path";async function nr(e){switch(e.cacheProvider){case"redis":await Lo(e),await jo(e);break;case"upstash":await Uo(e),await Mo(e);break}}async function Lo(e){await c(Tt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
679
684
|
import { Redis } from "ioredis";
|
|
680
685
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
681
686
|
import { env } from "./env";
|
|
@@ -804,7 +809,7 @@ export async function closeRedis() {
|
|
|
804
809
|
closed = true;
|
|
805
810
|
}
|
|
806
811
|
}
|
|
807
|
-
`)}async function
|
|
812
|
+
`)}async function jo(e){await c(Tt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
808
813
|
import { redis } from "./redis";
|
|
809
814
|
|
|
810
815
|
export class MutexTimeoutError extends Error {
|
|
@@ -841,7 +846,7 @@ export async function withMutex<T>(
|
|
|
841
846
|
await mutex.release();
|
|
842
847
|
}
|
|
843
848
|
}
|
|
844
|
-
`)}async function
|
|
849
|
+
`)}async function Uo(e){await c(Tt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
845
850
|
import type { Store } from "hono-rate-limiter";
|
|
846
851
|
import { env } from "./env";
|
|
847
852
|
|
|
@@ -959,7 +964,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
959
964
|
|
|
960
965
|
/** No persistent connection to close with Upstash REST. */
|
|
961
966
|
export async function closeRedis(): Promise<void> {}
|
|
962
|
-
`)}async function
|
|
967
|
+
`)}async function Mo(e){await c(Tt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
963
968
|
import { redis } from "./redis";
|
|
964
969
|
|
|
965
970
|
export class MutexTimeoutError extends Error {
|
|
@@ -1004,7 +1009,7 @@ export async function withMutex<T>(
|
|
|
1004
1009
|
await lock.release();
|
|
1005
1010
|
}
|
|
1006
1011
|
}
|
|
1007
|
-
`)}async function
|
|
1012
|
+
`)}async function rr(e){await c(`${e.projectDir}/packages/runtime/src/env.ts`,Fo(e))}function Fo(e){return`import { z } from "zod";
|
|
1008
1013
|
|
|
1009
1014
|
const EnvSchema = z.object({
|
|
1010
1015
|
NODE_ENV: z.enum(["development", "production"]).default("development"),
|
|
@@ -1131,13 +1136,13 @@ export const env = (() => {
|
|
|
1131
1136
|
const parsedApiUrl = new URL(env.API_URL);
|
|
1132
1137
|
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1133
1138
|
export const apiOrigin = parsedApiUrl.origin;
|
|
1134
|
-
`}import{readFile as
|
|
1135
|
-
`)}function
|
|
1136
|
-
`)}var
|
|
1137
|
-
`))}}import{readFile as
|
|
1138
|
-
`);let
|
|
1139
|
+
`}import{readFile as Vo}from"fs/promises";import{join as V}from"path";var xt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function Fe(e){let t=await Vo(e,"utf-8");return JSON.parse(t)}async function Ve(e,t){await c(e,JSON.stringify(t,null," ")+`
|
|
1140
|
+
`)}function pt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function Me(e,t,n,r=!1){let i=r?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=n}async function ir(e){await Bo(e),await Ko(e),await Go(e),await zo(e),e.frontend==="nextjs"?await qo(e):await Jo(e)}async function Bo(e){let t=V(e.projectDir,"packages/api/package.json"),n=await Fe(t);pt(n,["sharp","@types/sharp"]),await Ve(t,n)}async function Ko(e){let t=V(e.projectDir,"packages/runtime/package.json"),n=await Fe(t);e.cacheProvider==="upstash"&&(pt(n,["ioredis","rate-limit-redis","redis-semaphore"]),Me(n,"@upstash/redis",xt["@upstash/redis"]),Me(n,"@upstash/lock",xt["@upstash/lock"])),await Ve(t,n)}async function Go(e){let t=V(e.projectDir,"packages/database/package.json"),n=await Fe(t);e.databaseProvider==="neon"?(pt(n,["pg","@types/pg"]),Me(n,"@neondatabase/serverless",xt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(pt(n,["pg","@types/pg"]),Me(n,"postgres",xt.postgres)),await Ve(t,n)}async function zo(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/backend/package.json"),n=await Fe(t);e.deploymentTarget!=="node"&&pt(n,["@hono/node-server"]),await Ve(t,n)}var Ho=["server/routes/.well-known/oauth-authorization-server/[...path].ts","server/routes/.well-known/oauth-protected-resource/[...path].ts","server/routes/.well-known/oauth-authorization-server.ts","server/routes/.well-known/oauth-protected-resource.ts"],Yo=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Jo(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/web-nuxt");await tt(V(t,"server/api/[...paths].ts"),t);for(let o of Ho)await tt(V(t,o),t);let n=V(t,"package.json"),r=await Fe(n),i=r.dependencies?.["@repo/api"];i&&(delete r.dependencies?.["@repo/api"],Me(r,"@repo/api",i,!0)),await Ve(n,r)}async function qo(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/web-next");await tt(V(t,"app/api/[[...rest]]/route.ts"),t);for(let o of Yo)await tt(V(t,o),t);let n=V(t,"package.json"),r=await Fe(n),i=r.dependencies?.["@repo/api"];i&&(delete r.dependencies?.["@repo/api"],Me(r,"@repo/api",i,!0)),await Ve(n,r)}import{readFile as sr}from"fs/promises";import{join as ar}from"path";async function cr(e){let t=ar(e.projectDir,"turbo.json"),n;try{n=await sr(t,"utf-8")}catch{return}let r=JSON.parse(n),i=r.tasks?.build;if(!i)return;let o=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",s=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),a=!1;if(Array.isArray(i.env)){let d=i.env.filter(l=>l!==o);d.length!==i.env.length&&(i.env=d,a=!0)}if(Array.isArray(i.outputs)){let d=i.outputs.filter(l=>!s.has(l));d.length!==i.outputs.length&&(i.outputs=d,a=!0)}a&&await c(t,JSON.stringify(r,null," ")+`
|
|
1141
|
+
`)}var Wo=["base.json","node.json","next.json"],or="GenerateSaaS ";async function pr(e){if(!e.demo)for(let t of Wo){let n=ar(e.projectDir,"tooling/typescript",t),r;try{r=await sr(n,"utf-8")}catch{continue}let i=JSON.parse(r);typeof i.display!="string"||!i.display.startsWith(or)||(i.display=i.display.slice(or.length),await c(n,JSON.stringify(i,null," ")+`
|
|
1142
|
+
`))}}import{readFile as Xo,rm as Zo}from"fs/promises";import{existsSync as lr}from"fs";import{join as dr}from"path";async function ur(e){if(e.frontend==="nuxt")return;let t=dr(e.projectDir,"packages/i18n/package.json");if(!lr(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await Xo(t,"utf-8")),r=!!(n.exports?.["./module"]??n.exports?.["./nuxt"]),i=!1;if(n.exports)for(let s of["./module","./nuxt"])s in n.exports&&(delete n.exports[s],i=!0);n.devDependencies&&"@nuxt/kit"in n.devDependencies&&(delete n.devDependencies["@nuxt/kit"],i=!0),i&&await c(t,JSON.stringify(n,null," ")+`
|
|
1143
|
+
`);let o=dr(e.projectDir,"packages/i18n/nuxt");if(r&&!lr(o))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${o} is missing - did the i18n Nuxt module move?`);await Zo(o,{recursive:!0,force:!0})}import{readFile as fr,rm as Qo}from"fs/promises";import{join as _t}from"path";async function gr(e){e.cacheProvider==="upstash"&&await Promise.all([mr(_t(e.projectDir,"packages/runtime/tests/setup.ts")),mr(_t(e.projectDir,"packages/mail/tests/setup.ts")),es(e.projectDir),Qo(_t(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function mr(e){let t;try{t=await fr(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",
|
|
1139
1144
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1140
|
-
`);n!==t&&await
|
|
1145
|
+
`);n!==t&&await c(e,n)}async function es(e){let t=_t(e,"packages/api/tests/setup.ts"),n;try{n=await fr(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",
|
|
1141
1146
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1142
1147
|
`),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",
|
|
1143
1148
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1158,25 +1163,26 @@ vi.mock("@upstash/lock", () => {
|
|
|
1158
1163
|
return { Lock };
|
|
1159
1164
|
});
|
|
1160
1165
|
|
|
1161
|
-
$1`),r!==n&&await
|
|
1162
|
-
`).find(
|
|
1163
|
-
`,"","configuration.mdx companion config-table row",n)}
|
|
1164
|
-
`),
|
|
1165
|
-
`))}async function
|
|
1166
|
+
$1`),r!==n&&await c(t,r)}import{readdir as wr,readFile as Ot,rm as M}from"fs/promises";import{join as E}from"path";import{readFile as yr,rm as T}from"fs/promises";import{join as S}from"path";import{readFile as lt}from"fs/promises";import{join as dt}from"path";async function hr(e,t){let n=dt(e,"packages/api/src/routes/internal/index.ts");await c(n,de(await lt(n,"utf-8"),"internal router","companion",t)),await $n(n);let r=dt(e,"packages/api/src/ai/schedule-runner.ts");await c(r,de(await lt(r,"utf-8"),"schedule-runner.ts","companion",t));for(let s of["packages/api/src/index.ts","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 a=dt(e,s);await c(a,de(await lt(a,"utf-8"),s,"companion",t))}let i=dt(e,"packages/api/src/ai/settings-store.ts");await c(i,de(await lt(i,"utf-8"),"settings-store.ts","companion",t));let o=dt(e,"packages/api/tests/ai/settings-store.test.ts");await c(o,de(await lt(o,"utf-8"),"settings-store.test.ts","companion",t))}async function Qt(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await T(S(t,"packages/api/src/relay"),{recursive:!0}),await T(S(t,"packages/api/src/companion"),{recursive:!0}),await T(S(t,"packages/api/src/ai/companion-model.ts")),await T(S(t,"packages/api/tests/relay"),{recursive:!0}),await T(S(t,"packages/api/tests/companion"),{recursive:!0}),await T(S(t,"packages/api/src/routes/internal/companion.ts")),await T(S(t,"packages/api/src/routes/internal/companion-transport.ts")),await T(S(t,"packages/api/src/routes/internal/companion-limits.ts")),await T(S(t,"packages/api/tests/routes/companion.test.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-harness.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-poll.test.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await T(S(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await T(S(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await T(S(t,"packages/api/tests/ai/companion-model.test.ts")),await T(S(t,"packages/api/tests/ai/companion-chat.test.ts")),await T(S(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await T(S(t,"packages/api/tests/helpers/redis-mock.ts"));let r=S(t,"packages/api/package.json"),i=JSON.parse(await yr(r,"utf-8"));if(!i.exports?.["./companion"])throw new Error(`${n}: expected packages/api/package.json to carry the ./companion export`);delete i.exports["./companion"],await It(r,i," ",n),await hr(t,n);let o=Pt(e);await Nn(t,o,"companion",[`/${o}/companion`],n,"Companions"),await L(S(t,`docs/${o}/ai.mdx`),`Runs on a paired [companion](/${o}/companion) CLI are never metered either - the user's own subscription executes them. `,"","ai.mdx companion metering sentence",n),await L(S(t,`docs/${o}/caching.mdx`),` - see [poll cadence and request budgets](/${o}/companion/install#per-companion-request-budgets)`,"","caching.mdx companion budgets link",n);let s=S(t,`docs/${o}/configuration.mdx`),a="| `companion.enabled` |",d=(await yr(s,"utf-8")).split(`
|
|
1167
|
+
`).find(l=>l.startsWith(a));if(d===void 0)throw new Error(`${n}: expected the ${o} configuration.mdx \`companion.enabled\` row (boilerplate drift).`);await L(s,`${d}
|
|
1168
|
+
`,"","configuration.mdx companion config-table row",n)}var ts=new Set(["ci.yml","desktop-release.yml"]),ns={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"]},rs=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:build","check-types:scripts","ai:parity","companion:export","companion:verify","companion:publish"];async function vr(e){let t=E(e.projectDir,".github/workflows"),n=await wr(t).catch(()=>[]);for(let r of n)ts.has(r)||await M(E(t,r),{recursive:!0,force:!0})}async function is(e,t){let n=E(e,"package.json"),r=JSON.parse(await Ot(n,"utf-8"));if(!r.scripts)return!1;let i=!1;for(let o of t)o in r.scripts&&(delete r.scripts[o],i=!0);return i&&await c(n,JSON.stringify(r,null," ")+`
|
|
1169
|
+
`),i}async function kr(e){await is(e.projectDir,[...rs])}async function br(e){let t=E(e.projectDir,"package.json"),n=await Ot(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 c(t,JSON.stringify(r,null," ")+`
|
|
1170
|
+
`))}async function Sr(e){let t=E(e.projectDir,"package.json"),n=JSON.parse(await Ot(t,"utf-8")),r=n.scripts?.test;if(r!=="turbo run test && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test && vitest run", got ${JSON.stringify(r)} (boilerplate drift).`);n.scripts.test="turbo run test",await c(t,JSON.stringify(n,null," ")+`
|
|
1171
|
+
`)}async function Er(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await M(E(e.projectDir,t),{recursive:!0,force:!0})}async function Ar(e){e.docs||await M(E(e.projectDir,"apps/docs"),{recursive:!0})}async function Ir(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";await M(E(e.projectDir,t),{recursive:!0,force:!0}),await M(E(e.projectDir,"docs/index.mdx")),e.desktop||await M(E(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await os(e)}async function os(e){let t=e.projectDir,n="stripUnusedDocsSilo",r=Pt(e),i=E(t,`docs/${r}/configuration.mdx`),o=e.desktop,s=e.desktop&&e.ai;e.desktop||(await L(i,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",n),await L(i,"<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 L(E(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",n)),o||await L(i,"The desktop app's AI orchestration gates on `config.desktop.agents.enabled`, which a desktop project derives from your AI option (not a separate switch). The app always ships that AI source, so flipping the flag on turns the screens back on - but the bundled companion daemon is **not** runtime-toggleable: a project generated without AI never received `apps/companion`. Leaving the flag off costs nothing (the staging step skips itself and the app packages fine); it is turning it on that requires re-running the CLI with AI on first - see [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",n),!s&&e.companion&&(await L(E(t,`docs/${r}/companion/index.mdx`),`## Set up from the desktop app
|
|
1166
1172
|
|
|
1167
1173
|
If your product also ships the [desktop app](/desktop), it runs the companion for each user as a local daemon on their own machine - consent-first, with no terminal, no pairing, and no code to copy. It attaches to any daemon already serving the machine - including the user's own always-on service - and starts its own only when none is running, so one daemon serves both the app and any paired backend. It supervises that daemon while the app is open and, on quit, stops only the one it started - never the user's service. See [Companion setup](/desktop/companion).
|
|
1168
1174
|
|
|
1169
|
-
`,"","companion index.mdx desktop-setup section",n),await
|
|
1175
|
+
`,"","companion index.mdx desktop-setup section",n),await L(E(t,`docs/${r}/companion/terminal.mdx`),`## In the desktop app
|
|
1170
1176
|
|
|
1171
1177
|
If your product ships the [desktop app](/desktop), its **Terminal** side-panel tab is this same session, in an embedded terminal: the app spawns the daemon's \`terminal\` command in a real pty, and its folder picker **grants** the folder it picked (the durable, per-app grant above) before the session opens. See [Terminal and side panel](/desktop/ai/terminal).
|
|
1172
1178
|
|
|
1173
|
-
`,"","companion terminal.mdx desktop-panel section",n))}async function
|
|
1179
|
+
`,"","companion terminal.mdx desktop-panel section",n))}async function Pr(e){if(e.desktop)return;await M(E(e.projectDir,"apps/electron"),{recursive:!0});let t=E(e.projectDir,"packages/i18n/translations");for(let i of await wr(t,{withFileTypes:!0}))i.isDirectory()&&await M(E(t,i.name,"desktop.json"),{force:!0});await M(E(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of ns[e.frontend])await M(E(e.projectDir,i),{recursive:!0});await M(E(e.projectDir,"packages/utils/src/desktop-download.ts")),await M(E(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=E(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await Ot(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 It(n,r," ","stripDesktopApp")}function ss(e){return e.desktop}async function Rr(e){ss(e)||await M(E(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as as}from"fs/promises";import{join as cs}from"path";var Tr=`on:
|
|
1174
1180
|
workflow_run:
|
|
1175
1181
|
workflows: ["Tag Release"]
|
|
1176
1182
|
branches: [main]
|
|
1177
1183
|
types: [completed]
|
|
1178
|
-
workflow_dispatch:`,
|
|
1179
|
-
workflow_dispatch:`;async function
|
|
1184
|
+
workflow_dispatch:`,ps=`on:
|
|
1185
|
+
workflow_dispatch:`;async function xr(e){if(!e.desktop)return;let t=cs(e.projectDir,".github/workflows/desktop-release.yml"),n=await as(t,"utf8");if(!n.includes(Tr))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await c(t,n.replace(Tr,ps))}import{join as ls}from"path";async function _r(e){let t=ds(e);await c(ls(e.projectDir,".github/workflows/ci.yml"),t)}function ds(e){let t=Q[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",i=t?"":` services:
|
|
1180
1186
|
postgres:
|
|
1181
1187
|
image: postgres:18-alpine
|
|
1182
1188
|
env:
|
|
@@ -1190,13 +1196,13 @@ If your product ships the [desktop app](/desktop), its **Terminal** side-panel t
|
|
|
1190
1196
|
--health-interval 10s
|
|
1191
1197
|
--health-timeout 5s
|
|
1192
1198
|
--health-retries 5
|
|
1193
|
-
`,
|
|
1199
|
+
`,o=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",s=n?`
|
|
1194
1200
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1195
|
-
UPSTASH_REDIS_REST_TOKEN: test-token`:"",
|
|
1201
|
+
UPSTASH_REDIS_REST_TOKEN: test-token`:"",a=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1196
1202
|
STRIPE_SECRET_KEY: test
|
|
1197
1203
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1198
1204
|
POLAR_ACCESS_TOKEN: test
|
|
1199
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1205
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let u=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(u)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1200
1206
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1201
1207
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1202
1208
|
|
|
@@ -1220,8 +1226,8 @@ jobs:
|
|
|
1220
1226
|
name: Checks
|
|
1221
1227
|
runs-on: ubuntu-latest
|
|
1222
1228
|
timeout-minutes: 20
|
|
1223
|
-
${
|
|
1224
|
-
CONTENT_API_KEY: test-contentapi-key-16chars${
|
|
1229
|
+
${i} env:
|
|
1230
|
+
CONTENT_API_KEY: test-contentapi-key-16chars${s}${a}
|
|
1225
1231
|
STORAGE_REGION: test
|
|
1226
1232
|
STORAGE_ENDPOINT: http://test
|
|
1227
1233
|
STORAGE_ACCESS_KEY_ID: test
|
|
@@ -1242,53 +1248,53 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1242
1248
|
NODE_OPTIONS: --max-old-space-size=6144`:" - run: pnpm check-types"}
|
|
1243
1249
|
|
|
1244
1250
|
- name: Write root env
|
|
1245
|
-
run: echo "DATABASE_URL=${
|
|
1251
|
+
run: echo "DATABASE_URL=${o}" > .env
|
|
1246
1252
|
|
|
1247
1253
|
- run: pnpm test
|
|
1248
|
-
`}import{readFile as
|
|
1249
|
-
`))}async function
|
|
1250
|
-
`))}async function
|
|
1254
|
+
`}import{readFile as Or}from"fs/promises";import{existsSync as us}from"fs";import{join as en}from"path";var Dr="@repo/database";function ms(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function fs(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 gs(e,t,n){let r=await Or(e,"utf-8"),i=JSON.parse(r),o=i.scripts?.[t];if(!o)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);o.includes(Dr)||(i.scripts={...i.scripts,[t]:`${n} && ${o}`},await c(e,JSON.stringify(i,null," ")+`
|
|
1255
|
+
`))}async function hs(e,t){let n=us(e)?JSON.parse(await Or(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},r=n.buildCommand?.trim()||"pnpm build";r.includes(Dr)||(n.buildCommand=`${t} && ${r}`,await c(e,JSON.stringify(n,null," ")+`
|
|
1256
|
+
`))}async function Cr(e){let t=ms(e.demo===!0),n=fs(e.architecture,e.frontend),r=en(e.projectDir,"apps",n);switch(e.deploymentTarget){case"node":await gs(en(r,"package.json"),"start",t);return;case"vercel":await hs(en(r,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as ys}from"fs/promises";import{existsSync as ws}from"fs";import{join as Dt}from"path";var vs=["stripe","polar"];async function Nr(e){let t=Dt(e.projectDir,"packages/payments/src"),n=e.paymentProvider,r=`// Active payment provider. To switch, change the path below to
|
|
1251
1257
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1252
1258
|
export { ops } from "./${n}/index";
|
|
1253
|
-
`;await
|
|
1254
|
-
`).filter(
|
|
1255
|
-
`)}import{readdir as
|
|
1256
|
-
`).filter(
|
|
1257
|
-
`).length&&await
|
|
1258
|
-
`))}async function
|
|
1259
|
-
`),await
|
|
1260
|
-
`)}import{relative as
|
|
1261
|
-
`);
|
|
1262
|
-
${
|
|
1263
|
-
`),
|
|
1264
|
-
`),
|
|
1265
|
-
`),
|
|
1266
|
-
`),await To(E,E)}await Oo(E,N.aiTools),await Ro(N,C),r.stop("Project files generated.")}catch(y){r.stop("Generation failed."),k.cancel(I(y)),process.exit(1)}!await Co(E)&&N.demo===!0&&(k.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let ae=await No(E);ae&&N.demo!==!0&&e.dbMigration!==!1&&await $o(E),await Lo(E),ae&&await jo(E);let Ee=Le("docker"),he=cn(N).map(y=>y.key).filter(y=>!N.credentials?.[y]);Uo(N,{pnpmInstalled:ae,dockerComposeGenerated:te,dockerAvailable:Ee,skippedCredentials:he}),Kn(),k.log.info(Gs.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Ln}from"fs";import{readFile as jn}from"fs/promises";import{join as rt,resolve as tc}from"path";import*as v from"@clack/prompts";import L from"picocolors";import{mkdtemp as Js,rm as Ys}from"fs/promises";import{tmpdir as qs}from"os";import{join as Ws}from"path";async function Nn(e,t,n,r){let o=await Js(Ws(qs(),"generatesaas-stage-"));try{await Mt(e,t,o),await qt({...n,projectDir:o}),await _n(o,r)}finally{await Ys(o,{recursive:!0,force:!0})}}function Bo(e){return e?"ON":"OFF"}var Pt="packages/config/src/index.ts",Xs=[{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>'Retired option `billingScope`: your project recorded organization-scoped billing, but it is now a plain config value generated as `user`. Applying this update as-is bills the individual member instead of the organization: new checkouts create member-scoped subscriptions and org-level entitlements stop resolving. Put it back with `billingScope: "organization"` in `packages/config/src/tenancy-flags.mjs`. How should this update proceed?'},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${Pt} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${Pt} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${Pt}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===ut(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Bo(e.aiBuiltin)}, but it is now a plain config value generated ${Bo(ut(e))} for a project ${ut(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${Pt} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${Pt} to keep it off.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local companion checkout at ${e.companionLocalPath}. The option is gone; point the \`GENERATESAAS_COMPANION_BRAND_JSON\` env var at that checkout's \`brand.json\` instead.`}];function Go(e){let t=[];for(let n of Xs){if(n.normalize?.(e),e[n.key]===void 0)continue;(!n.applies||n.applies(e))&&!n.preserved(e)&&t.push({key:n.key,message:n.describe(e),severity:n.severity}),delete e[n.key]}return t}import{readFile as Zs,rm as Qs}from"fs/promises";import{join as $n}from"path";var Ko=$n(V,"companion-release.json"),ec=["apps/companion/","packages/companion-protocol/","packages/agent-core-types/","packages/agent-core/","scripts/companion-export/"];async function Ho(e){let t;try{t=await Zs($n(e,Ko),"utf-8")}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&r.code==="ENOENT")return null;throw r}let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"version"in n&&typeof n.version=="string"&&n.version.length>0?{version:n.version}:null}async function zo(e){try{return await Qs($n(e,Ko)),!0}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function Jo(e){return e.some(t=>ec.some(n=>t.startsWith(n)))}function qo(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,n)=>{let r=t==="auto"?"auto":void 0,o=tc(n.cwd??process.cwd()),i=rt(o,we),a;try{a=JSON.parse(await jn(i,"utf-8"))}catch{v.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s;try{s=await We()}catch(l){v.cancel(I(l)),process.exit(1)}let u=fe(s),g=v.spinner();try{g.start("Verifying access...");let l;try{l=await be(u)}catch(w){throw w instanceof $&&w.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):w}let h=Zt(l,"update");if(!h.ok)throw new Error(h.message);g.stop("Access verified."),xe(s),g.start("Fetching latest skill files...");let S=await lr(u,l.latest);await Dn(o,S.skillMd,S.scripts,a.aiTools);let C=On(a.aiTools);if(g.stop("Skills updated."),v.log.success(`Skill files installed to ${L.cyan(C.length.toString())} locations.`),a.version===l.latest){v.log.info(`Already on the latest version (${a.version}).`);return}let E=JSON.stringify(a);nr(a),await nc(a,rr(a),r),await oc(Go(a),r);let N=Yn(a),te=qn(a),Fe=JSON.stringify(te)!==E;if(a=te,a.licenseToken)try{let w=await ur(u,{currentToken:a.licenseToken,newVersion:l.latest});a.licenseToken=w.token,w.licenseKeyHash&&(a.licenseKeyHash=w.licenseKeyHash),await p(i,JSON.stringify(a,null," ")+`
|
|
1267
|
-
`),
|
|
1268
|
-
`);let
|
|
1269
|
-
`)}if(
|
|
1270
|
-
`),
|
|
1271
|
-
`),
|
|
1272
|
-
|
|
1273
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1274
|
-
|
|
1275
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1276
|
-
|
|
1277
|
-
${
|
|
1278
|
-
|
|
1279
|
-
`),title:`Changelog v${n} \u2192 v${r}`}}async function
|
|
1280
|
-
`);
|
|
1281
|
-
`),
|
|
1282
|
-
`).map(
|
|
1259
|
+
`;await c(Dt(t,"providers/index.ts"),r),await c(Dt(t,"index.ts"),await ks(t,n))}async function ks(e,t){let n=Dt(e,"index.ts");if(!ws(n))throw new Error(`generatePaymentBarrel: expected ${n} to exist - did packages/payments move?`);let r=await ys(n,"utf-8"),i=vs.filter(s=>s!==t);return r.split(`
|
|
1260
|
+
`).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
|
|
1261
|
+
`)}import{readdir as bs,readFile as Ss}from"fs/promises";import{join as $r}from"path";async function Lr(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,n=JSON.stringify(t).slice(1,-1),r=$r(e.projectDir,"packages/i18n/translations"),i;try{i=await bs(r)}catch{return}for(let o of i){let s=$r(r,o,"web.json"),a;try{a=await Ss(s,"utf-8")}catch{continue}let d=a.replaceAll("GenerateSaaS",n);d!==a&&await c(s,d)}}import{readFile as Es}from"fs/promises";import{join as jr}from"path";var As=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],Is=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function Mr(e){let n=e.frontend==="nuxt"?Is:As;await Ur(jr(e.projectDir,".gitignore"),n),await Ur(jr(e.projectDir,".dockerignore"),n)}async function Ur(e,t){let n;try{n=await Es(e,"utf-8")}catch{return}let r=new Set(t),i=n.split(`
|
|
1262
|
+
`).filter(o=>!r.has(o.trim()));i.length!==n.split(`
|
|
1263
|
+
`).length&&await c(e,i.join(`
|
|
1264
|
+
`))}async function Ct(e){let t=e.projectDir;e.demo||(await Un(t),await Fn(t),await Vn(t),await Bn(t),e.desktop&&await Mn(t)),await Kn(t,e.frontend),await zn(e),await Hn(e),await Yn(e),e.demo||await Jn(e),await Xn(e),await Zn(e),await Qn(e),await er(e),await tr(e),await nr(e),await rr(e),await ir(e),await cr(e),await pr(e),await ur(e),await gr(e),await vr(e),await _r(e),await kr(e),await br(e),await Sr(e),await Er(e),await Ar(e),await Ir(e),await Pr(e),await Rr(e),await xr(e),await Qt(e),await Cr(e),await Nr(e),await Lr(e),await Mr(e)}import{basename as Vr,join as Br,relative as Rs}from"path";import{createHash as Fr}from"crypto";import{readFile as Ps}from"fs/promises";async function Nt(e){let t=await Ps(e);return Fr("sha256").update(t).digest("hex")}function tn(e){return Fr("sha256").update(e).digest("hex")}var Ts=new Set(["data",K]);function xs(e){let t=e.split("/");for(let n of t)if(Gt.has(n)||zt.has(n)||Ts.has(n)||n.startsWith(".env")&&!n.includes("example"))return!0;return!1}function Kr(e,t){return{projectName:e.projectName??Vr(t),appName:e.appName??e.projectName??Vr(t),projectDir:t,frontend:e.frontend==="nextjs"?"nextjs":"nuxt",architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,companion:e.companion??!1,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function _s(e,t){return{version:e.version,initialVersion:e.version,repo:"AlexChelan/GenerateSaaS",appName:e.appName,projectName:e.projectName,frontend:e.frontend,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,ai:e.ai,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Gr(e,t){let r=(await Ae(e.projectDir,e.projectDir,xs)).sort(),i=await Promise.all(r.map(async a=>[Ee(Rs(e.projectDir,a)),await Nt(a)])),o=Object.fromEntries(i),s=_s(e,t);await c(Br(e.projectDir,ae),JSON.stringify(s,null," ")+`
|
|
1265
|
+
`),await c(Br(e.projectDir,Pn),JSON.stringify(o,null," ")+`
|
|
1266
|
+
`)}import{relative as Os}from"path";async function Be(e){let n=(await Ae(e,e,je)).sort(),r=await Promise.all(n.map(async i=>[Ee(Os(e,i)),await Nt(i)]));return Object.fromEntries(r)}import{copyFile as Ds,mkdir as Cs,rm as Ns}from"fs/promises";import{dirname as $s,join as zr,relative as Ls}from"path";import{existsSync as js}from"fs";async function nn(e,t){js(t)&&await Ns(t,{recursive:!0,force:!0});let n=await Ae(e,e,je);for(let r of n){let i=Ee(Ls(e,r)),o=zr(t,i);await Cs($s(o),{recursive:!0}),await Ds(r,o)}}async function Hr(e,t){await nn(e,zr(t,kt))}import{existsSync as Us}from"fs";import{readFile as Yr,readdir as Ms}from"fs/promises";import{join as J,dirname as Fs,resolve as Vs,sep as Bs}from"path";import{fileURLToPath as Ks}from"url";var Gs={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Ie=Object.values(Gs),rn="generatesaas-update",Jr=Fs(Ks(import.meta.url));function zs(){let e=J(Jr,"skill","content");return Us(e)?e:J(Jr,"content")}async function on(e,t,n){for(let r of Ie){let i=J(e,r,rn),o=J(i,"scripts"),s=J(i,"references");await At(o),await At(s),await c(J(i,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",r)),await c(J(s,".gitkeep"),"");for(let[a,d]of Object.entries(n)){let l=Vs(o,a);l.startsWith(o+Bs)&&await c(l,d)}}}async function qr(e){let t=zs(),n=await Yr(J(t,"SKILL.md"),"utf-8"),r=J(t,"scripts"),i=await Ms(r),o={};for(let s of i)s!==".gitkeep"&&(o[s]=await Yr(J(r,s),"utf-8"));await on(e,n,o)}import{execFile as Hs,execFileSync as Ys}from"child_process";import{access as Wr,readFile as Js}from"fs/promises";import{join as sn}from"path";import*as D from"@clack/prompts";function Re(e){try{let t=process.platform==="win32"?"where":"which";return Ys(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Pe(e,t,n,r=3e5){return new Promise((i,o)=>{Hs(e,t,{cwd:n,timeout:r,maxBuffer:50*1024*1024},(s,a,d)=>{if(s){let l=String(a||"").trim(),k=[String(d||"").trim(),l].filter(Boolean).join(`
|
|
1267
|
+
`);o(new Error(k?`${s.message}
|
|
1268
|
+
${k}`:s.message))}else i()})})}async function Xr(e){if(!Re("pnpm"))return D.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Pe("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let n=t instanceof Error?t.message:String(t);return D.log.warn(`Lockfile regeneration failed: ${n}`),D.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Zr(e){if(!Re("pnpm"))return D.log.warn("pnpm not found. Skipping dependency installation."),D.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=D.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Pe("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(n){t.stop("Dependency installation failed.");let r=n instanceof Error?n.message:String(n);return D.log.warn(`pnpm install failed: ${r}`),D.log.warn("You can run it manually later."),!1}}async function Qr(e){if(!Re("pnpm"))return!1;let t=D.spinner();t.start("Generating baseline database migration...");try{return await Pe("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(n){t.stop("Baseline migration generation failed.");let r=n instanceof Error?n.message:String(n);return D.log.warn(`Could not generate baseline migration: ${r}`),D.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function ei(e){try{return await Wr(sn(e,".git")),D.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Re("git"))return D.log.warn("git not found. Skipping repository initialization."),!1;let t=D.spinner();t.start("Initializing git repository...");try{return await Pe("git",["init"],e),await Pe("git",["add","-A"],e),await Pe("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),D.log.warn("You can run git init manually later."),!1}}async function ti(e){if(!Re("pnpm"))return!1;try{await Wr(sn(e,".git"))}catch{return!1}try{let t=JSON.parse(await Js(sn(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 Pe("pnpm",["exec","simple-git-hooks"],e),!0}catch{return D.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Ke from"@clack/prompts";import G from"picocolors";function ni(e,t){let n=Oe(e);t.dockerAvailable||Ke.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let r=[];r.push(`cd ${e.projectDir}`),t.pnpmInstalled||r.push("pnpm install"),r.push(`pnpm infra ${G.dim(`# ${n.map(a=>hn[a].label).join(", ")}`)}`),r.push(`pnpm dev ${G.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(r.push(""),r.push(G.dim("Fill in remaining TODO values in .env"))),Ke.note(r.join(`
|
|
1269
|
+
`),G.yellow("Start Development"));let i=[];i.push(`App ${G.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${G.cyan("http://localhost:3010")}`),n.includes("mailpit")&&i.push(`Mailpit ${G.cyan("http://localhost:8025")}`),n.includes("inngest")&&i.push(`Inngest ${G.cyan("http://localhost:8288")}`),Ke.note(i.join(`
|
|
1270
|
+
`),G.yellow("Dev Tools"));let o=[],s=qs(e);s.length>0&&o.push(`Set in production: ${G.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(Ws(e)),Ke.note(o.join(`
|
|
1271
|
+
`),G.yellow("Deployment"))}function qs(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 Ws(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 Ge(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 Te(e,t){let n=Ge(e),r=Ge(t);if(!n||!r)return 0;for(let i=0;i<3;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function $t(e,t){return e.versions.find(n=>n.version===t)?.cli}function ri(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:Ge(e)===null}function Lt(e,t,n="2.3.0"){if(ri(n))return{ok:!0};let r=$t(e,e.latest);return!r||Ge(r)===null?{ok:!0}:Te(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 ii(e,t,n="2.3.0"){if(ri(n))return{ok:!0};let r=$t(e,t);return!r||Ge(r)===null?{ok:!0}:Te(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 na from"picocolors";var ra="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function ia(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 oi(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 q("--frontend <type>","frontend framework").choices([...ke])).addOption(new q("--architecture <type>","fullstack or separate").choices([...De])).addOption(new q("--payment <provider>","payment provider").choices([...Ce])).addOption(new q("--email <provider>","email provider").choices([...Ne])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--blog","enable blog").option("--no-blog","disable blog").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-companion","exclude the backend companion feature").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new q("--currency <code>","default currency for billing").choices([...ee])).addOption(new q("--deploy <target>","deployment target").choices([...te])).addOption(new q("--database <provider>","database provider").choices([...ne])).addOption(new q("--cache <provider>","cache provider").choices([...re])).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 q("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new q("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await oa(t?{...n,apiKey:t}:n)})}async function oa(e){let t=performance.now();fn("2.3.0");let n;try{n=En(e)}catch(h){y.cancel(O(h)),process.exit(1)}let r=y.spinner(),i;try{i=await Le({apiKey:e.apiKey,prompt:!e.yes})}catch(h){y.cancel(O(h)),process.exit(1)}e.demo&&tn(i)!==ra&&(y.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=oe(i),s,a=async()=>{s=await le(o);let h=Lt(s,"init");if(!h.ok)throw new Error(h.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,companionAllowed:s.entitlements?.companionAllowed??!0}};r.start("Verifying access...");let d,l,u=!0,k=!0;try{({latestVersion:d,selectedVersion:l,desktopAllowed:u,companionAllowed:k}=await a()),r.stop("Access verified."),Se(i)}catch(h){if(r.stop("Access verification failed."),h instanceof N&&h.status===401){e.yes&&(y.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),y.log.warning("Invalid API key."),i=await et(),o=oe(i),r.start("Verifying access...");try{({latestVersion:d,selectedVersion:l,desktopAllowed:u,companionAllowed:k}=await a()),r.stop("Access verified."),Se(i)}catch(R){r.stop("Access verification failed."),y.cancel(R instanceof N&&R.status===401?"Invalid API key.":O(R)),process.exit(1)}}else y.cancel(O(h)),process.exit(1)}y.log.success(`Latest version: ${d}`),n.desktop===!0&&!u&&(y.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),n.companion===!0&&!k&&(y.cancel("The companion is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let A;e.yes?A=An({...n,...u?{}:{desktop:!1},...k?{}:{companion:!1}}):A=await In(n,{desktopAllowed:u,companionAllowed:k});let $;r.start("Activating license...");try{let h=e.demo&&A.baseUrl?await ia(A.baseUrl):crypto.randomUUID(),R=()=>({frontend:A.frontend,version:l,installId:h,projectName:A.projectName,options:_n(A)}),F;try{F=await Bt(o,R())}catch(he){let C=bt(he);if(!C?.lastAllowedVersion||!s)throw he;r.stop("License activation failed.");let I=ii(s,C.lastAllowedVersion);if(I.ok||(y.cancel(`${C.message} ${I.message}`),process.exit(1)),e.yes){let ye=$t(s,C.lastAllowedVersion);y.cancel(`${C.message} Re-run ${ye?`npx generatesaas@${ye} init`:"init"} without --yes to continue with v${C.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let Z=await y.confirm({message:`Your update window has ended. Continue with v${C.lastAllowedVersion} (the last version your license covers)?`});(y.isCancel(Z)||!Z)&&(y.cancel("Setup cancelled."),process.exit(0)),l=C.lastAllowedVersion,r.start(`Activating license for v${l}...`),F=await Bt(o,R())}$={token:F.token,keyHash:tn(i),installId:F.installId??h},r.stop("License activated.")}catch(h){r.stop("License activation failed."),y.cancel(O(h)),process.exit(1)}let v=ta(A.projectDir);if(Xs(v)&&Zs(v).length>0)if(e.yes)y.log.info(`Directory ${v} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let R=await y.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"}]});(y.isCancel(R)||R==="cancel")&&(y.cancel("Setup cancelled."),process.exit(0)),R==="overwrite"&&Qs(v,{recursive:!0,force:!0})}let U={...A,projectDir:v,version:l,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await St(o,l,v),r.stop("Template downloaded.")}catch(h){r.stop("Download failed."),y.cancel(O(h)),process.exit(1)}r.start("Generating project files...");try{if(await Ct(U),!e.demo){let h=await Be(v);await c(ea(v,vt),JSON.stringify(h,null," ")+`
|
|
1272
|
+
`),await Hr(v,v)}await qr(v),await Gr(U,$),r.stop("Project files generated.")}catch(h){r.stop("Generation failed."),y.cancel(O(h)),process.exit(1)}!await Xr(v)&&U.demo===!0&&(y.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let X=await Zr(v);X&&U.demo!==!0&&e.dbMigration!==!1&&await Qr(v),await ei(v),X&&await ti(v);let fe=Re("docker"),ge=Ft(U).map(h=>h.key).filter(h=>!U.credentials?.[h]);ni(U,{pnpmInstalled:X,dockerAvailable:fe,skippedCredentials:ge}),gn(),y.log.info(na.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as cn}from"fs";import{readFile as mi}from"fs/promises";import{join as ze,resolve as ua}from"path";import*as w from"@clack/prompts";import z from"picocolors";import{mkdtemp as sa,rm as aa}from"fs/promises";import{tmpdir as ca}from"os";import{join as pa}from"path";async function an(e,t,n,r){let i=await sa(pa(ca(),"generatesaas-stage-"));try{await St(e,t,i),await Ct({...n,projectDir:i}),await nn(i,r)}finally{await aa(i,{recursive:!0,force:!0})}}function ut(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var si=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:ke,adoptable:!1,impact:"structural",shapesTree:!0},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:De,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:te,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ne,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:re,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ce,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ee,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ne,adoptable:!1,impact:"config",shapesTree:!1},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"companion",label:"Companion daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install OpenCompanion, the daemon we publish and keep updated - your project ships the pairing, dispatch and Companions surface, never the daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,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",shapesTree:!1,requires:e=>ut(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function la(e,t){return e[t]!==void 0}function ai(e){return si.filter(t=>t.adoptable&&!la(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 ci(e){let t={};for(let n of si)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}}function pi(e){return e?"ON":"OFF"}var mt="packages/config/src/index.ts";function li(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",n=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(r=>!(r==="postgres"&&t)&&!(r==="redis"&&n)).sort()}function di(e){return[...Oe({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var da=[{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>'Retired option `billingScope`: your project recorded organization-scoped billing, but it is now a plain config value generated as `user`. Applying this update as-is bills the individual member instead of the organization: new checkouts create member-scoped subscriptions and org-level entitlements stop resolving. Put it back with `billingScope: "organization"` in `packages/config/src/tenancy-flags.mjs`. How should this update proceed?'},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${mt} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${mt} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${mt}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===ut(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${pi(e.aiBuiltin)}, but it is now a plain config value generated ${pi(ut(e))} for a project ${ut(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${mt} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${mt} to keep it off.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local companion checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one companion daemon (OpenCompanion) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` companion source. There is now one companion daemon - OpenCompanion - which we publish and your users install from its own releases. Your project keeps the companion feature and its own pairing, dispatch and Companions page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install OpenCompanion, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at OpenCompanion, the one daemon we publish.`},{key:"dockerServices",severity:"warn",preserved:e=>li(e).join(",")===di(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${li(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${di(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===wn.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${Ie.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`}];function ui(e){let t=[];for(let n of da){if(n.normalize?.(e),e[n.key]===void 0)continue;(!n.applies||n.applies(e))&&!n.preserved(e)&&t.push({key:n.key,message:n.describe(e),severity:n.severity}),delete e[n.key]}return t}function fi(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,i=ua(n.cwd??process.cwd()),o=ze(i,ae),s;try{s=JSON.parse(await mi(o,"utf-8"))}catch{w.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let a;try{a=await Le()}catch(u){w.cancel(O(u)),process.exit(1)}let d=oe(a),l=w.spinner();try{l.start("Verifying access...");let u;try{u=await le(d)}catch(I){throw I instanceof N&&I.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):I}let k=Lt(u,"update");if(!k.ok)throw new Error(k.message);l.stop("Access verified."),Se(a),l.start("Fetching latest skill files...");let A=await xn(d,u.latest);await on(i,A.skillMd,A.scripts);let $=Ie;if(l.stop("Skills updated."),w.log.success(`Skill files installed to ${z.cyan($.length.toString())} locations.`),s.version===u.latest){w.log.info(`Already on the latest version (${s.version}).`);return}let v=JSON.stringify(s);bn(s),await ma(s,Sn(s),r),await ga(ui(s),r);let U=ai(s),me=ci(s),X=JSON.stringify(me)!==v;if(s=me,s.licenseToken)try{let I=await On(d,{currentToken:s.licenseToken,newVersion:u.latest});s.licenseToken=I.token,I.licenseKeyHash&&(s.licenseKeyHash=I.licenseKeyHash),await c(o,JSON.stringify(s,null," ")+`
|
|
1273
|
+
`),X=!1,w.log.success("License refreshed.")}catch(I){let Z=bt(I);Z&&(w.cancel(Z.message),process.exit(1)),w.log.warn("License refresh skipped.")}X&&await c(o,JSON.stringify(s,null," ")+`
|
|
1274
|
+
`);let fe=Kr(s,i),He=ze(i,Rn);l.start(`Staging v${u.latest} (shaped for your config)...`),await an(d,u.latest,fe,He),l.stop("Template staged.");let{text:ge,title:h}=await wa(d,u,s.version);ge&&w.note(ge,h);let R=ze(i,vt),F=ze(i,kt),he=!cn(F),C=!cn(R);if(he){if(l.start("Building baseline template (one-time migration)..."),await an(d,s.version,fe,F),C){let I=await Be(F);await c(R,JSON.stringify(I,null," ")+`
|
|
1275
|
+
`)}if(l.stop("Baseline template stored."),!C){let I=await va(R,F);I>0&&w.log.warn(`Rebuilt baseline differs from the original for ${I} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(C){l.start("Computing baseline template hashes...");let I=await Be(F);await c(R,JSON.stringify(I,null," ")+`
|
|
1276
|
+
`),l.stop("Baseline hashes computed.")}await c(ze(i,Tn),JSON.stringify({currentVersion:s.version,targetVersion:u.latest,changelog:ge,stagedAt:new Date().toISOString(),...U.length>0?{newOptions:U}:{},...r?{mode:r}:{}},null," ")+`
|
|
1277
|
+
`),w.log.info(`Update staged: ${z.cyan(s.version)} \u2192 ${z.cyan(u.latest)}`),w.log.info(`Ask your AI coding assistant to ${z.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&cn(ze(i,"apps/tauri"))&&w.log.warn(`Desktop: the app moved to an Electron shell (${z.cyan("apps/electron")}). Your project still has the old Tauri shell (${z.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${z.cyan("/desktop/updates")}.`)}catch(u){l.stop("Failed."),w.cancel(`Update failed: ${O(u)}`),process.exit(1)}})}async function ma(e,t,n){if(t.kind==="none")return;let r=ya[t.kind];n==="auto"&&(w.cancel(`${r.message}
|
|
1278
|
+
|
|
1279
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${z.cyan("generatesaas update")} without ${z.cyan("auto")} and answer it.`),process.exit(1));let i=await w.select({message:r.message,options:r.options});w.isCancel(i)&&(w.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var fa={billingScope:[{value:"stage",label:"Stage it - I will put the scope back myself",hint:'set `billingScope: "organization"` in packages/config/src/tenancy-flags.mjs before taking new checkouts'},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/tenancy-flags.mjs first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function ga(e,t){let n=[];for(let r of e){let i=r.severity==="ask"?fa[r.key]:void 0;if(!i){w.log.warn(r.message);continue}n.push({notice:r,answers:i})}for(let{notice:r,answers:i}of n){t==="auto"&&(w.cancel(`${r.message}
|
|
1280
|
+
|
|
1281
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${z.cyan("generatesaas update")} without ${z.cyan("auto")} and answer it.`),process.exit(1));let o=await w.select({message:r.message,options:i});(w.isCancel(o)||o==="stop")&&(w.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function ha(e){e.desktop=!1}var ya={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.companion=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion - it requires AI"},{value:{apply:ha},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function wa(e,t,n){let r=t.latest,i=t.versions.filter(s=>Te(s.version,n)>0&&Te(s.version,r)<=0).sort((s,a)=>Te(s.version,a.version));if(i.length<=1)return{text:await Vt(e,r),title:`Changelog v${r}`};let o=[];for(let s of i){let a=null;try{a=await Vt(e,s.version)}catch{a=null}let d=s.date?` (${s.date.slice(0,10)})`:"",l=s.breaking?" [BREAKING]":"";o.push(`# v${s.version}${d}${l}
|
|
1282
|
+
|
|
1283
|
+
${a??"_No changelog available for this release._"}`)}return{text:o.join(`
|
|
1284
|
+
|
|
1285
|
+
`),title:`Changelog v${n} \u2192 v${r}`}}async function va(e,t){let n=JSON.parse(await mi(e,"utf-8")),r=await Be(t),i=0;for(let[o,s]of Object.entries(n))je(o)||r[o]!==s&&i++;for(let o of Object.keys(r))o in n||i++;return i}import*as B from"@clack/prompts";import W from"picocolors";import{readFile as ka}from"fs/promises";import{join as ba,resolve as Sa}from"path";function gi(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=Sa(t.cwd??process.cwd()),r=ba(n,ae),i;try{i=JSON.parse(await ka(r,"utf-8"))}catch{B.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${W.cyan(i.version)}`,`Frontend: ${W.cyan(i.frontend)}`,i.deploymentTarget?`Deploy target: ${W.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${W.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${W.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
|
|
1286
|
+
`);B.note(o,W.bold("Project Status"));let s=B.spinner();s.start("Checking for updates...");try{let a=await Le(),d=oe(a),u=(await le(d)).latest;i.version===u?(s.stop("Up to date."),B.log.success(`Already on the latest version (${W.green(u)})`)):(s.stop("Update available."),B.log.warning(`Update available: ${W.yellow(i.version)} \u2192 ${W.green(u)}`),B.log.info(`Open this project in your AI coding agent and ask it to ${W.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof N&&a.status===401?B.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):B.log.warning(`Could not check for updates: ${O(a)}`)}})}import{readFile as Ea}from"fs/promises";import*as _ from"@clack/prompts";import x from"picocolors";function Aa(){return process.env.GENERATESAAS_API_KEY??Qe()}function Ia(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 Pa(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Ra(e){switch(e.verdict){case"licensed":return _.log.success(`${x.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return _.log.success(`${x.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 _.log.error(`${x.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 _.log.error(`${x.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${x.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return _.log.error(`${x.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return _.log.warn(`${x.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function hi(e,t){let n=process.env.GENERATESAAS_API_URL??Ze,r=Aa();e.start("Cross-referencing license records...");try{let i=r?Ia(await Dn(n,r,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Pa(await Kt(n,{token:t.token,domain:t.domain}));return e.stop(`${x.green("Checked")} - records cross-referenced`),Ra(i)}catch(i){return e.stop(`${x.yellow("Skipped")} - ${O(i)}`),null}}function Ta(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 pn(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function yi(e){_.note([`License ID: ${x.cyan(String(e.lid??"unknown"))}`,`Version: ${x.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${pn(e.pat)}`,`Last updated: ${pn(e.uat)}`,`Expires: ${pn(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1287
|
+
`),x.yellow("License Details"))}function xa(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 wi(e){let t=_.spinner(),n=null,r="no candidates";for(let s of xa(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){r=`${s} returned ${a.status}`,t.stop(`${x.yellow("Not here")} - ${r}`);continue}let d=(await a.text()).trim();if(!d||d.split(".").length!==3){r=`${s} did not return a JWT`,t.stop(`${x.yellow("Not here")} - ${r}`);continue}n=d,t.stop(`${x.green("Found")} - license endpoint responded`);break}catch(a){r=`${s}: ${O(a)}`,t.stop(`${x.yellow("Unreachable")} - ${r}`)}}if(n===null){_.log.warn(`No license endpoint found (last: ${r}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=vi(e);return s?await hi(t,{domain:s})??!1:!1}let i;try{i=Ta(n)}catch{return _.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??Ze,a=await Kt(s,{token:n});if(a.valid)t.stop(`${x.green("Valid")} - signature verified`);else return t.stop(`${x.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${x.yellow("Skipped")} - could not reach verification service`),_.log.warn("Signature not verified. Displaying unverified claims:"),yi(i),!1}return yi(i),await hi(t,{token:n,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:vi(e)})??!0}function vi(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ki(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&&(_.cancel("Provide a URL or --file <path>."),process.exit(1)),n.file){let i=(await Ea(n.file,"utf-8")).split(`
|
|
1288
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(_.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await wi(s)&&o++,_.log.info("");_.log.success(`${o}/${i.length} sites verified.`)}else await wi(t)||process.exit(1)})}import{existsSync as _a,rmSync as Oa}from"fs";import*as H from"@clack/prompts";function bi(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){_a(ie)?(Oa(ie),H.log.success("API key removed.")):H.log.info("No API key configured.");return}let n=Qe();n?H.log.info(`Current API key: ****${n.slice(-4)}`):H.log.info("No API key configured.");let r=await et(),i=oe(r),o=H.spinner();o.start("Verifying API key...");try{await le(i),o.stop("API key verified."),Se(r),H.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof N&&s.status===401?H.cancel("Invalid API key."):H.cancel(O(s)),process.exit(1)}})}import{existsSync as jt,rmSync as Da,readFileSync as dn,writeFileSync as Si}from"fs";import{join as xe}from"path";import*as j from"@clack/prompts";var Ca=["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"],Na=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1283
1289
|
`,` licenseHeartbeatFunction,
|
|
1284
1290
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1285
1291
|
`,` .route("/license", licenseRoutes)
|
|
1286
|
-
`]}];function
|
|
1287
|
-
`).filter(
|
|
1288
|
-
`);return r===n?!1:(
|
|
1292
|
+
`]}];function $a(){return Ie.map(e=>xe(e,rn))}function ln(e){return jt(e)?(Da(e,{recursive:!0}),!0):!1}function La(e,t){if(!jt(e))return!1;let n=dn(e,"utf-8"),r=n;for(let i of t)r=r.replace(i,"");return r===n?!1:(Si(e,r,"utf-8"),!0)}function ja(e){let t=xe(e,".gitignore");if(!jt(t))return!1;let n=dn(t,"utf-8"),r=n.split(`
|
|
1293
|
+
`).filter(i=>!i.includes(".generatesaas")).join(`
|
|
1294
|
+
`);return r===n?!1:(Si(t,r,"utf-8"),!0)}function Ei(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),n=xe(t,ae),r;try{r=JSON.parse(dn(n,"utf-8"))}catch{j.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await j.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(j.isCancel(i)&&(j.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)}),j.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{j.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of $a())ln(xe(t,a))&&o.push(a);for(let a of Ca)ln(xe(t,a))&&o.push(a);ln(xe(t,K))&&o.push(K+"/");for(let a of Na){let d=xe(t,a.file);La(d,a.removals)?s.push(a.file):jt(d)&&j.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}ja(t)&&s.push(".gitignore");for(let a of o)j.log.info(`Deleted ${a}`);for(let a of s)j.log.info(`Modified ${a}`);j.log.success("Ejected successfully. This project is now fully standalone.")})}var _e=new Ua().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.3.0").addHelpText("after",`
|
|
1289
1295
|
Examples:
|
|
1290
1296
|
$ generatesaas init Interactive setup
|
|
1291
1297
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1292
1298
|
$ generatesaas status Check for updates
|
|
1293
1299
|
$ generatesaas auth Set or update API key
|
|
1294
|
-
`);
|
|
1300
|
+
`);oi(_e);fi(_e);gi(_e);ki(_e);bi(_e);Ei(_e);_e.parseAsync().catch(e=>{Ai.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|