generatesaas 2.1.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 +198 -243
- package/dist/skill/content/SKILL.md +0 -36
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,29 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as qc}from"commander";import*as _i from"@clack/prompts";import{existsSync as cc,readdirSync as pc,rmSync as lc}from"fs";import{join as dc,resolve as uc}from"path";import{Option as W}from"commander";import*as A from"@clack/prompts";import*as $t from"@clack/prompts";import wn from"picocolors";function ur(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";$t.intro(wn.bgYellow(wn.black(t)))}function mr(){$t.outro(wn.yellow("Happy building!"))}import*as m from"@clack/prompts";import f from"picocolors";var yt={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},wt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},Lt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Ut={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},jt={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},Ye={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}},vt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Ne={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var ie={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},q={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},ae={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},kt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],bt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],fr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Mt(e){let t=q[e.databaseProvider].managed,n=ae[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var me={google:{label:"Google",envVars:[{name:"GOOGLE_CLIENT_ID",secret:!1},{name:"GOOGLE_CLIENT_SECRET",secret:!0}]},github:{label:"GitHub",envVars:[{name:"GITHUB_CLIENT_ID",secret:!1},{name:"GITHUB_CLIENT_SECRET",secret:!0}]},facebook:{label:"Facebook",envVars:[{name:"FACEBOOK_CLIENT_ID",secret:!1},{name:"FACEBOOK_CLIENT_SECRET",secret:!0}]},discord:{label:"Discord",envVars:[{name:"DISCORD_CLIENT_ID",secret:!1},{name:"DISCORD_CLIENT_SECRET",secret:!0}]},x:{label:"X",envVars:[{name:"TWITTER_CLIENT_ID",secret:!1},{name:"TWITTER_CLIENT_SECRET",secret:!0}]}};var $e=["nextjs","nuxt"],We=["fullstack","separate"],Xe=["stripe","polar","none"],Ze=["smtp","ses","resend"],Qe=["postgres","redis","inngest","mailpit"],et=["claude-code","cursor","codex","gemini-cli","windsurf"],tt=["user","organization"],fe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ge=["node","vercel"],he=["postgres","neon","supabase"],ye=["redis","upstash"],nt=["google","github","facebook","discord","x"],Le=["shared","vendored"];function Vt(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function rt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ft(e){return/^[a-z][a-z0-9-]*$/.test(e)}function T(e){return e instanceof Error?e.message:String(e)}function Z(e){let t=e?.trim();return t?`${rt(t)} Companion`:"My Companion"}var Ue="https://github.com/Duzbee/OpenCompanion";function se(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function gr(e){return e.desktop===!0&&e.ai===!0}function Y(e){if(gr(e)){if(e.companionSource==="shared")throw new Error("A desktop app with AI bundles its own companion daemon, so its companion source must be vendored. Remove the shared companion source, or turn AI off on this project.");return"vendored"}return se(e)}function we(e){return gr(e)?!0:e.companion===!0&&se(e)==="vendored"}function Bt(e){return e.demo===!0&&e.companion===!0?!0:we(e)}function Ee(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var hr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:$e,adoptable:!1,impact:"structural"},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:We,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ge,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:he,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ye,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Xe,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:fe,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ze,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:tt,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"emailTracking",label:"Email analytics",hint:"Tracks opens and clicks of marketing emails and adds an admin analytics page.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config"},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, and BYOK options. On a desktop project it also ships the app's local AI stack and bundles a companion daemon inside the packaged app. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"companion",label:"Companion daemon",hint:"Lets your users install a companion daemon that runs their own AI subscriptions (and any device-side work you add) on their hardware. Point it at an existing shared companion like OpenCompanion (default, nothing to maintain), or vendor and publish your own branded daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionSource",label:"Companion source",hint:"Point at an existing shared companion repo (like OpenCompanion), or vendor a branded daemon you own and publish yourself.",category:"Features",kind:"enum",default:e=>Y(e),choices:Le,adoptable:!0,impact:"structural",requires:e=>e.companion===!0||e.desktop===!0&&e.ai===!0,requiresLabel:"requires the companion, or a desktop app with AI"},{key:"companionRepoUrl",label:"Companion repo URL",hint:"GitHub repository of the shared companion this project points at. Its brand.json supplies the daemon identity; your users install from its latest release.",category:"Features",kind:"text",default:()=>Ue,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionLocalPath",label:"Companion local checkout",hint:"Optional path to your local checkout of the shared companion, if you develop it alongside this project. Leave empty otherwise.",category:"Features",kind:"text",default:()=>"",adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>Z(e.projectName),adoptable:!0,impact:"config",requires:e=>we(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{key:"mcpServer",label:"Outward MCP server",hint:"Exposes the app's capability layer to external agents as an authenticated MCP OAuth server.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"aiBuiltin",label:"Built-in AI (credits)",hint:"Your app offers models under its own name via OpenRouter, billed from user credits (which need a payment provider to buy). The only setup is OPENROUTER_API_KEY.",category:"Features",kind:"boolean",default:e=>Ee(e),adoptable:!1,impact:"config",requires:e=>e.ai===!0&&Ee(e),requiresLabel:"requires AI features and a payment provider"},{key:"aiByok",label:"User API keys (BYOK)",hint:"Let end-users connect their own provider API keys; runs on their key never use credits.",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",requires:e=>Ee(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config"},{key:"socialProviders",label:"Social login providers",hint:"Which social sign-in buttons the auth screen shows.",category:"Features",kind:"multiselect",default:[],choices:nt,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Qe,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:et,adoptable:!1,impact:"config"}];function Ci(e,t){return e[t]!==void 0}function yr(e){return hr.filter(t=>t.adoptable&&!Ci(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function wr(e){let t={};for(let n of hr)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}import{readFile as kn}from"fs/promises";import{join as vr}from"path";var vn="GENERATESAAS_COMPANION_BRAND_JSON",Gt=["daemon/brand.json","apps/companion/brand.json"];function ce(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`);let r=n.hostname.toLowerCase();if(r!=="github.com"&&r!=="www.github.com")throw new Error(`Only GitHub-hosted shared companions are supported right now (got "${n.hostname}"). Host the companion on GitHub, or vendor your own with --companion-source vendored.`);let o=n.pathname.split("/").filter(Boolean),i=o[0],a=o[1]?.replace(/\.git$/,"");if(!i||!a)throw new Error(`"${t}" is missing the owner/repo path. Use a full GitHub URL like https://github.com/owner/repo.`);return{owner:i,repo:a,canonicalUrl:`https://github.com/${i}/${a}`}}function kr(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function Kt(e,t){let n;try{n=JSON.parse(e)}catch{throw new Error(`The companion brand.json from ${t} is not valid JSON.`)}if(typeof n!="object"||n===null)throw new Error(`The companion brand.json from ${t} is not a JSON object.`);let r=n;for(let o of["name","binary","envPrefix"]){let i=r[o];if(typeof i!="string"||i.trim()==="")throw new Error(`The companion brand.json from ${t} is missing a usable "${o}" field. Point at a companion repo built with the GenerateSaaS export pipeline, or vendor your own with --companion-source vendored.`)}return{name:r.name,binary:r.binary,envPrefix:r.envPrefix}}async function Di(e,t){let n=vr(e,"apps/companion/brand.json"),r;try{r=await kn(n,"utf8")}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(r).repoUrl}catch{throw new Error("The template's apps/companion/brand.json is not valid JSON (boilerplate drift).")}if(typeof o!="string"||o.trim()==="")return null;let i;try{i=ce(o)}catch{return null}return kr(i,t)?Kt(r,`the template (${n})`):null}async function Ni(e,t){for(let n of Gt){let r=vr(e,n),o;try{o=await kn(r,"utf8")}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;throw s}let i=Kt(o,r),a=JSON.parse(o).repoUrl;if(typeof a=="string"&&a.trim()!==""){let s;try{s=ce(a)}catch{throw new Error(`The companion checkout at ${r} names an unusable repoUrl ("${a}"), so it cannot be verified against ${t.canonicalUrl}. Fix the checkout's brand.json, or drop --companion-local-path to fetch the identity from GitHub.`)}if(!kr(s,t))throw new Error(`The companion checkout at ${e} belongs to ${s.canonicalUrl}, but the project points at ${t.canonicalUrl}. Point --companion-repo-url and --companion-local-path at the same companion, or drop --companion-local-path to fetch the identity from GitHub.`)}return i}throw new Error(`No brand.json found in ${e} (checked ${Gt.join(" and ")}). Point --companion-local-path at a checkout of the companion repo, or remove it to fetch the identity from GitHub.`)}async function $i(e){for(let t of Gt){let n=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/HEAD/${t}`,r;try{r=await fetch(n)}catch(o){throw new Error(`Could not reach GitHub to read the companion identity (${n}): ${T(o)}. Check your network, or pass --companion-local-path to a local checkout of the companion.`)}if(r.status!==404){if(!r.ok)throw new Error(`GitHub returned ${r.status} for ${n}. Check that ${e.canonicalUrl} exists and is public.`);return Kt(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Gt.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function br(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=ce(t),r=await Di(e.projectDir,n);if(r)return r;let o=e.companionLocalPath?.trim();if(o)return await Ni(o,n);let i=process.env[vn]?.trim();if(i){let a;try{a=await kn(i,"utf8")}catch(s){throw new Error(`Could not read ${vn} (${i}): ${T(s)}.`)}return Kt(a,`${vn} (${i})`)}return await $i(n)}var Sr=["companion","mcpServer"];function Sn(e){if(!Sr.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Er(e){if(e.ai!==!0)return!0;let t=e.aiBuiltin===!0&&Ee(e),n=e.desktop===!0;return t||e.aiByok===!0||e.companion===!0||n}function En(e){if(!Er(e))throw new Error("AI features have no usable model source: built-in AI needs a payment provider (it bills from user credits), user API keys (BYOK) are off, and there is no companion. Enable one - add a payment provider, keep user API keys (drop --no-ai-byok), or add the companion (--companion).")}function Ir(e){return Sr.some(n=>e[n]===!0)&&(e.ai=!0),e}function Ar(e){return e.ai!==!0||(e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1),Ee(e)||(e.aiBuiltin=!1),Er(e)||(e.aiByok=!0)),e}function Pr(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=Li(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&In(e),n}function In(e){return we(e)&&(e.companionSource=Y(e),e.companionName===void 0&&(e.companionName=Z(e.projectName))),e}function Li(e,t){return e.desktop!==!0?{kind:"none"}:e.ai===!0&&e.companionSource==="shared"?{kind:"shared-source-contradiction"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:e.ai===!0&&e.companionName===void 0?{kind:"daemon-materialized"}:{kind:"none"}}function Rr(e){let t={};if(e.name!==void 0){if(!Ft(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.frontend!==void 0){if(!$e.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${$e.join(", ")}`);t.frontend=e.frontend}if(e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.billingScope!==void 0){if(e.org!==!0)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(e.blog!==void 0&&(t.blog=e.blog),e.emailTracking!==void 0&&(t.emailTracking=e.emailTracking),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!Le.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${Le.join(", ")}`);if(e.companion===!1)throw new Error("--companion-source requires the companion; remove --no-companion.");t.companionSource=e.companionSource,t.companion===void 0&&(t.companion=!0)}if(e.companionRepoUrl!==void 0){if(e.companion===!1)throw new Error("--companion-repo-url requires the companion; remove --no-companion.");t.companionRepoUrl=ce(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(e.companionLocalPath!==void 0){if(e.companion===!1)throw new Error("--companion-local-path requires the companion; remove --no-companion.");let n=e.companionLocalPath.trim();n!==""&&(t.companionLocalPath=n,t.companion===void 0&&(t.companion=!0))}if(t.companionSource==="vendored"&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path apply to a shared companion; remove them or use --companion-source shared.");if(e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiBuiltin!==void 0){if(e.aiBuiltin===!0&&e.payment==="none")throw new Error("--ai-builtin requires a payment provider (got --payment none). Built-in AI bills from user credits.");t.aiBuiltin=e.aiBuiltin}if(e.aiByok!==void 0&&(t.aiByok=e.aiByok),Sn(t),e.desktop===!0&&t.ai===!0&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path point at a SHARED companion, but a desktop app with AI bundles its own; remove them, or turn AI off with --no-ai.");if(e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.docker!==void 0&&(t.dockerServices=bn(e.docker,Qe,"docker service")),e.aiTools!==void 0&&(t.aiTools=bn(e.aiTools,et,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=bn(e.socialProviders,nt,"social provider")),e.currency!==void 0){if(!fe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${fe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ge.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ge.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!he.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${he.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ye.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ye.join(", ")}`);t.cacheProvider=e.cache}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var pe={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,emailTracking:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,ai:!1,companion:!1,mcpServer:!1,aiBuiltin:!0,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function xr(e){let t=e.projectName??pe.projectName,n=e.projectDir??`./${t}`,r=e.appName??rt(t),o=e.deploymentTarget??pe.deploymentTarget,i=ie[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":pe.databaseProvider),s=e.cacheProvider??(i?"upstash":pe.cacheProvider),u=e.emailProvider??(i?"resend":pe.emailProvider),g=e.dockerServices??(i?pe.dockerServices.filter(h=>h!=="postgres"&&h!=="redis"):pe.dockerServices),l={...pe,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.multiTenancy||(l.billingScope="user"),l.ai||(l.aiBuiltin=pe.aiBuiltin,l.aiByok=pe.aiByok),l.paymentProvider==="none"&&(l.aiBuiltin=!1),l.desktop&&l.ai&&(l.companionSource=Y(l)),we(l)&&l.companionName===void 0&&(l.companionName=Z(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=se(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=Z(l.projectName)):(l.companionRepoUrl===void 0&&(l.companionRepoUrl=Ue),l.companionLocalPath===void 0&&(l.companionLocalPath=""))),En(l);for(let h of kt){if(l.deploymentTarget!==h.target)continue;let y=l.databaseProvider===h.provider?"database":"cache";if(l.databaseProvider===h.provider||l.cacheProvider===h.provider)throw new Error(`Incompatible: --deploy ${h.target} + --${y} ${h.provider}. ${h.reason}`)}for(let h of bt)if(l.architecture===h.architecture&&l.deploymentTarget===h.target)throw new Error(`Incompatible: --architecture ${h.architecture} + --deploy ${h.target}. ${h.reason}`);return l}function bn(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(i=>i.trim()).filter(Boolean),o=r.filter(i=>!t.includes(i));if(o.length>0)throw new Error(`Invalid ${n}(s): ${o.join(", ")}. Valid values: ${t.join(", ")}`);return r}function E(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function An(e){let t=[];e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0}));for(let n of e.socialProviders){let r=me[n];for(let o of r.envVars)t.push({key:o.name,message:`${o.name} (${r.label}, optional):`,secret:o.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Tr(e,t){let n=!1;e&&Sn(e),m.log.info(f.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Ft(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return E(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await m.text({message:"App name:",initialValue:rt(r),validate:d=>{if(!d?.trim())return"App name is required."}});return E(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await m.text({message:"Project location:",initialValue:`./${r}`});return E(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(yt),d=await m.select({message:"Frontend framework:",options:c.map(S=>({value:S,label:yt[S].label,hint:yt[S].hint}))});return E(d),d})();m.log.info(f.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await m.select({message:"Deployment target:",options:ge.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint}))});E(c),s=c}let u=e?.architecture?bt.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(u)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);let g=new Set(bt.filter(c=>c.target===s).map(c=>c.architecture)),l=We.filter(c=>!g.has(c)),h=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return m.log.info(`Auto-selected ${wt[d].label} architecture (only compatible option for ${ie[s].label}).`),d}n=!0;let c=await m.select({message:"Architecture:",options:l.map(d=>({value:d,label:wt[d].label,hint:wt[d].hint}))});return E(c),c})(),y=e?.databaseProvider??await(async()=>{n=!0;let c=he.filter(S=>!kt.some(K=>K.target===s&&K.provider===S));if(c.length===1){let S=c[0];return m.log.info(`Auto-selected ${q[S].label} (only compatible option for ${ie[s].label}).`),S}let d=await m.select({message:"Database provider:",options:c.map(S=>({value:S,label:q[S].label,hint:q[S].hint}))});return E(d),d})(),_=e?.cacheProvider??await(async()=>{n=!0;let c=ye.filter(S=>!kt.some(K=>K.target===s&&K.provider===S));if(c.length===1){let S=c[0];return m.log.info(`Auto-selected ${ae[S].label} (only compatible option for ${ie[s].label}).`),S}let d=await m.select({message:"Cache provider:",options:c.map(S=>({value:S,label:ae[S].label,hint:ae[S].hint}))});return E(d),d})();if(ie[s]?.edgeRuntime){let c=fr.map(d=>` - ${d}`).join(`
|
|
3
|
-
`);
|
|
4
|
-
`),
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`,scripts:{}}:await(await
|
|
11
|
-
|
|
12
|
-
`)}async function
|
|
13
|
-
`)}function
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`,"",`${t}
|
|
19
|
-
`,""
|
|
20
|
-
|
|
21
|
-
`)
|
|
22
|
-
|
|
23
|
-
- **Payments:** ${wa[e.paymentProvider]}`,h=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",y="";e.companion&&(se(e)==="vendored"?y=`
|
|
24
|
-
- \`apps/companion\` - the source of **${e.companionName??Z(e.projectName)}**, the branded companion daemon your users install. Publish releases with \`pnpm companion:publish\`; \`generatesaas update\` flags when a re-release is due.`:e.companionLocalPath?y=`
|
|
25
|
-
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\`. A local checkout lives at \`${e.companionLocalPath}\` - edit and commit device-side behavior THERE, not in this repo (clone from the repo URL if the checkout is missing).`:y=`
|
|
26
|
-
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\` (your users install it from that repo's releases). It cannot be modified from this repo; to customize device-side behavior, switch \`companionSource\` to \`vendored\` via \`generatesaas update\`.`);let _=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",v=t?"**Navigation:** always use `localePath()` for paths (hardcoded paths break non-default locales); `await navigateTo()` in SSR.":"**Navigation:** `next/link` for links; `redirect()` from `next/navigation` for programmatic redirects in Server Components.";return`# AGENTS.md
|
|
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
|
|
27
23
|
|
|
28
24
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
29
25
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -49,13 +45,13 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
49
45
|
|
|
50
46
|
## Stack
|
|
51
47
|
|
|
52
|
-
- **Frontend:** ${n} ${
|
|
53
|
-
- **API:** Hono, RPC-typed. ${
|
|
54
|
-
- **Database:** Drizzle ORM + ${
|
|
55
|
-
- **Cache + jobs:** ${
|
|
56
|
-
- **Auth:** Better Auth${
|
|
57
|
-
- **Email:** ${
|
|
58
|
-
- **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}
|
|
59
55
|
|
|
60
56
|
## Where things live (extend these - don't reinvent)
|
|
61
57
|
|
|
@@ -65,8 +61,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
65
61
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
66
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\`.
|
|
67
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.
|
|
68
|
-
- \`${r}\` - the ${n} app (${
|
|
69
|
-
- \`docs/${t?"nuxt":"next"}/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${
|
|
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}.
|
|
70
66
|
|
|
71
67
|
## Code style
|
|
72
68
|
|
|
@@ -83,7 +79,7 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
83
79
|
|
|
84
80
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
85
81
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
86
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${
|
|
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.
|
|
87
83
|
- ${v}
|
|
88
84
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
89
85
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
@@ -95,14 +91,12 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
95
91
|
## This project
|
|
96
92
|
|
|
97
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\`.
|
|
98
|
-
`}async function
|
|
99
|
-
`)}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
|
|
100
96
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
101
97
|
- API: http://localhost:3010
|
|
102
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
This project ships with Dockerfiles for each app. Build images with \`docker build\` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).${a?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,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}
|
|
106
100
|
|
|
107
101
|
${s}
|
|
108
102
|
|
|
@@ -111,7 +105,7 @@ ${s}
|
|
|
111
105
|
- **Frontend:** ${r}
|
|
112
106
|
- **Backend:** Hono (TypeScript, RPC-typed)
|
|
113
107
|
- **Auth:** Better Auth
|
|
114
|
-
- **ORM / DB:** Drizzle + ${
|
|
108
|
+
- **ORM / DB:** Drizzle + ${o}
|
|
115
109
|
- **Background jobs:** Inngest
|
|
116
110
|
- **i18n:** ${n?"@nuxtjs/i18n":"next-intl"}
|
|
117
111
|
|
|
@@ -122,11 +116,11 @@ pnpm install
|
|
|
122
116
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
123
117
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
124
118
|
# reference. All apps load the single root \`.env\`.
|
|
125
|
-
${
|
|
119
|
+
${d}pnpm db:setup # first run: create the database schema (idempotent)
|
|
126
120
|
pnpm dev
|
|
127
121
|
\`\`\`
|
|
128
122
|
|
|
129
|
-
${
|
|
123
|
+
${a}
|
|
130
124
|
|
|
131
125
|
## Build your SaaS
|
|
132
126
|
|
|
@@ -158,20 +152,20 @@ pnpm dlx generatesaas eject
|
|
|
158
152
|
|
|
159
153
|
## Updates
|
|
160
154
|
|
|
161
|
-
|
|
162
|
-
`}async function
|
|
163
|
-
`)}async function Pa(e,t,n){let r=st(e,"apps/electron/dev-app-update.yml");try{await Ia(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await p(r,`provider: generic
|
|
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
|
|
164
157
|
url: ${t}
|
|
165
158
|
updaterCacheDirName: ${n}
|
|
166
|
-
`)}function
|
|
167
|
-
`)}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?`{
|
|
168
161
|
enableInDev: true,
|
|
169
162
|
chatwoot: {
|
|
170
163
|
baseUrl: "https://support.alexchelan.com",
|
|
171
164
|
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
172
165
|
}
|
|
173
|
-
}`:"{}",
|
|
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";
|
|
174
167
|
import { desktopConfig } from "./desktop.mjs";
|
|
168
|
+
import { observabilityConfig } from "./observability.mjs";
|
|
175
169
|
import { supportConfig } from "./support.mjs";
|
|
176
170
|
import { tenancyConfig } from "./tenancy-flags.mjs";
|
|
177
171
|
|
|
@@ -180,9 +174,9 @@ const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim
|
|
|
180
174
|
export const config: AppConfig = {
|
|
181
175
|
siteName: "${t}",
|
|
182
176
|
fullSiteName: "${t}",
|
|
183
|
-
domain: "${
|
|
177
|
+
domain: "${i}",
|
|
184
178
|
baseUrl: process.env.BASE_URL ?? "${r}",
|
|
185
|
-
indexable: ${
|
|
179
|
+
indexable: ${s},
|
|
186
180
|
logo: {
|
|
187
181
|
main: "/images/logo.svg",
|
|
188
182
|
square: "/images/logo-square.svg"
|
|
@@ -199,7 +193,7 @@ export const config: AppConfig = {
|
|
|
199
193
|
cookieBanner: "auto",
|
|
200
194
|
consentPolicy: "gdpr-and-unknown",
|
|
201
195
|
auth: {
|
|
202
|
-
socialProviders: ${
|
|
196
|
+
socialProviders: ${e.demo?'["google"]':"[]"}
|
|
203
197
|
},
|
|
204
198
|
social: {},
|
|
205
199
|
email: {
|
|
@@ -207,22 +201,22 @@ export const config: AppConfig = {
|
|
|
207
201
|
limitPerSecond: 3,
|
|
208
202
|
senders: {
|
|
209
203
|
transactional: {
|
|
210
|
-
email: "noreply@${
|
|
204
|
+
email: "noreply@${o}",
|
|
211
205
|
senderName: "${t}"
|
|
212
206
|
},
|
|
213
207
|
marketing: {
|
|
214
|
-
email: "hello@${
|
|
208
|
+
email: "hello@${o}",
|
|
215
209
|
senderName: "${t}",
|
|
216
210
|
signatureName: "Alex"
|
|
217
211
|
},
|
|
218
212
|
support: {
|
|
219
|
-
email: "support@${
|
|
213
|
+
email: "support@${o}",
|
|
220
214
|
senderName: "${t} Support"
|
|
221
215
|
}
|
|
222
216
|
},
|
|
223
217
|
inactiveEmailSchedule: [7, 30, 90],
|
|
224
218
|
tracking: {
|
|
225
|
-
enabled:
|
|
219
|
+
enabled: true,
|
|
226
220
|
retentionDays: 90
|
|
227
221
|
}
|
|
228
222
|
},
|
|
@@ -244,7 +238,8 @@ export const config: AppConfig = {
|
|
|
244
238
|
prefix: "key_"
|
|
245
239
|
},
|
|
246
240
|
apiDocs: true,
|
|
247
|
-
performanceMonitor: { enabled: ${
|
|
241
|
+
performanceMonitor: { enabled: ${d} },
|
|
242
|
+
observability: observabilityConfig,
|
|
248
243
|
notifications: {
|
|
249
244
|
enabled: true,
|
|
250
245
|
maxPerUser: 100,
|
|
@@ -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}"
|
|
@@ -307,11 +302,12 @@ export const config: AppConfig = {
|
|
|
307
302
|
},
|
|
308
303
|
ai: {
|
|
309
304
|
enabled: ${e.ai},
|
|
310
|
-
// Built-in AI: your app offers models under its OWN name, billed from user credits
|
|
311
|
-
//
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
305
|
+
// Built-in AI: your app offers models under its OWN name, billed from user credits (which need a
|
|
306
|
+
// payment provider to buy), so it is generated on exactly when a payment provider exists. Powered by
|
|
307
|
+
// OpenRouter - set OPENROUTER_API_KEY in your env, that is the whole setup. Flip this to change it.
|
|
308
|
+
builtin: ${n},
|
|
309
|
+
// Let users connect their own provider API keys; flip to false to disable.
|
|
310
|
+
byok: true,
|
|
315
311
|
// What every user starts on (their own choice, once made, always wins). Plain
|
|
316
312
|
// OpenRouter model ids.
|
|
317
313
|
defaults: { model: "anthropic/claude-opus-4.8" },
|
|
@@ -330,10 +326,11 @@ export const config: AppConfig = {
|
|
|
330
326
|
}
|
|
331
327
|
},
|
|
332
328
|
desktop: desktopConfig,
|
|
333
|
-
// Companion:
|
|
334
|
-
companion: ${
|
|
335
|
-
// Outward MCP server exposing the capability layer to external agents.
|
|
336
|
-
|
|
329
|
+
// Companion: the OpenCompanion daemon your users install to run their own subscription CLIs for this app. Off by default.
|
|
330
|
+
companion: ${k},
|
|
331
|
+
// Outward MCP server exposing the capability layer to external agents. Its code ships with every
|
|
332
|
+
// project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
|
|
333
|
+
mcpServer: { enabled: ${e.demo?"true":"false"} },
|
|
337
334
|
seo: {
|
|
338
335
|
description: "Production-ready SaaS application",
|
|
339
336
|
foundingDate: "${new Date().getFullYear()}-01-01"
|
|
@@ -374,7 +371,7 @@ export * from "./pricing";
|
|
|
374
371
|
export * from "./roles";
|
|
375
372
|
export * from "./section-tabs";
|
|
376
373
|
export * from "./tenancy";
|
|
377
|
-
|
|
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
|
|
378
375
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
379
376
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
380
377
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -382,9 +379,9 @@ export * from "./tenancy";
|
|
|
382
379
|
|
|
383
380
|
export const desktopConfig = {
|
|
384
381
|
enabled: ${e.desktop},
|
|
385
|
-
appId: "${
|
|
386
|
-
productName: "${
|
|
387
|
-
protocol: "${
|
|
382
|
+
appId: "${l.appId}",
|
|
383
|
+
productName: "${l.productName}",
|
|
384
|
+
protocol: "${l.protocol}",
|
|
388
385
|
baseUrl: "${r}",
|
|
389
386
|
// Name of the app's data folder (created under the OS app-data dir). Where the app
|
|
390
387
|
// and its AI agents persist files - logs, gathered data, generated artifacts. Rename
|
|
@@ -393,7 +390,12 @@ export const desktopConfig = {
|
|
|
393
390
|
// Public base URL the release workflow uploads to; electron-updater polls
|
|
394
391
|
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
395
392
|
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
396
|
-
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,
|
|
397
399
|
agents: {
|
|
398
400
|
// Feature toggles only. Agents run in the app's main process (companion supervision +
|
|
399
401
|
// the daemon transport bridge), driven through the @repo/agent-core seam - typed
|
|
@@ -418,26 +420,49 @@ export const desktopConfig = {
|
|
|
418
420
|
// connection lock). Default false: the app is local-first and connecting is an
|
|
419
421
|
// OPTIONAL, explicit user action. Set true for a structurally private product - the
|
|
420
422
|
// connect surface never renders AND the daemon refuses pairing.
|
|
421
|
-
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
|
|
422
429
|
}
|
|
423
430
|
};
|
|
424
|
-
`),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
|
|
425
432
|
// TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
|
|
426
433
|
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
427
434
|
|
|
428
435
|
export const tenancyConfig = ${e.multiTenancy?`{
|
|
429
436
|
multiTenant: true,
|
|
430
437
|
organizationLimit: 5,
|
|
431
|
-
billingScope: "${e.
|
|
438
|
+
billingScope: "${e.demo?"organization":"user"}"
|
|
432
439
|
}`:"{ multiTenant: false }"};
|
|
433
|
-
`),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
|
|
434
441
|
// the TypeScript config index reads it directly (the Electron main + renderer and
|
|
435
442
|
// the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
|
|
436
443
|
// index re-exports this as config.support.
|
|
437
444
|
|
|
438
|
-
export const supportConfig = ${
|
|
439
|
-
`),
|
|
440
|
-
|
|
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
|
|
447
|
+
// cannot import the TypeScript config index reads it directly (the Electron main +
|
|
448
|
+
// renderer, which have no env at all once packaged). Mirrors the support.mjs
|
|
449
|
+
// pattern. The config index re-exports this as config.observability.
|
|
450
|
+
//
|
|
451
|
+
// Off by default and off costs nothing: every surface checks \`sentry.enabled\` and a
|
|
452
|
+
// non-empty \`dsn\` before it dynamically imports the SDK, so nothing ships to your
|
|
453
|
+
// users' browsers and nothing loads on your server. Turn it on by flipping \`enabled\`
|
|
454
|
+
// and pasting your project DSN (Sentry: Settings -> Projects -> Client Keys) - the DSN
|
|
455
|
+
// is public by design (it only authorizes sending events, never reading them), which is
|
|
456
|
+
// why it lives here rather than in env. Server-side, SENTRY_DSN overrides it.
|
|
457
|
+
|
|
458
|
+
export const observabilityConfig = {
|
|
459
|
+
sentry: {
|
|
460
|
+
enabled: false,
|
|
461
|
+
dsn: ""
|
|
462
|
+
}
|
|
463
|
+
};
|
|
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";
|
|
441
466
|
|
|
442
467
|
export const pricingConfig: PricingConfig = {
|
|
443
468
|
defaultPlan: "free",
|
|
@@ -466,21 +491,21 @@ export const pricingConfig: PricingConfig = {
|
|
|
466
491
|
credits: { enabled: false },
|
|
467
492
|
products: { enabled: false, items: [] }
|
|
468
493
|
};
|
|
469
|
-
`;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
|
|
470
495
|
// !! USD), but your plan prices and credit purchases are denominated in ${n}. Verify that the
|
|
471
496
|
// !! ${n} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
472
497
|
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
473
|
-
`;
|
|
498
|
+
`;o&&n!=="USD"&&console.warn(`
|
|
474
499
|
!! ${n} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
475
500
|
!! plan prices and credit purchases are denominated in ${n}. At the shipped economics 1 credit
|
|
476
501
|
!! carries ~0.42 USD of AI cost - verify every ${n} price still covers it (see the comment on the
|
|
477
502
|
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
478
|
-
`);let
|
|
503
|
+
`);let k=o?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
479
504
|
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
480
505
|
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
481
506
|
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
482
507
|
// full utilization runs you at a loss.
|
|
483
|
-
${
|
|
508
|
+
${u} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",A=`import type { PricingConfig } from "@repo/config/types";
|
|
484
509
|
|
|
485
510
|
export const pricingConfig: PricingConfig = {
|
|
486
511
|
defaultPlan: "free",
|
|
@@ -504,7 +529,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
504
529
|
amounts: { ${n}: 0 }
|
|
505
530
|
}
|
|
506
531
|
],
|
|
507
|
-
${
|
|
532
|
+
${a}
|
|
508
533
|
},
|
|
509
534
|
{
|
|
510
535
|
id: "starter",
|
|
@@ -519,18 +544,18 @@ ${s}
|
|
|
519
544
|
],
|
|
520
545
|
prices: [
|
|
521
546
|
{
|
|
522
|
-
${
|
|
547
|
+
${i}
|
|
523
548
|
interval: "month",
|
|
524
549
|
amounts: { ${n}: 9 }
|
|
525
550
|
},
|
|
526
551
|
{
|
|
527
|
-
${
|
|
552
|
+
${i}
|
|
528
553
|
interval: "year",
|
|
529
554
|
amounts: { ${n}: 90 },
|
|
530
555
|
anchorAmounts: { ${n}: 109 }
|
|
531
556
|
}
|
|
532
557
|
],
|
|
533
|
-
${
|
|
558
|
+
${d}
|
|
534
559
|
},
|
|
535
560
|
{
|
|
536
561
|
id: "pro",
|
|
@@ -548,33 +573,33 @@ ${u}
|
|
|
548
573
|
],
|
|
549
574
|
prices: [
|
|
550
575
|
{
|
|
551
|
-
${
|
|
576
|
+
${i}
|
|
552
577
|
interval: "month",
|
|
553
578
|
amounts: { ${n}: 29 },
|
|
554
579
|
anchorAmounts: { ${n}: 39 },
|
|
555
580
|
featured: true
|
|
556
581
|
},
|
|
557
582
|
{
|
|
558
|
-
${
|
|
583
|
+
${i}
|
|
559
584
|
interval: "year",
|
|
560
585
|
amounts: { ${n}: 290 },
|
|
561
586
|
anchorAmounts: { ${n}: 349 }
|
|
562
587
|
}
|
|
563
588
|
],
|
|
564
|
-
${
|
|
589
|
+
${l}
|
|
565
590
|
}
|
|
566
591
|
],
|
|
567
|
-
${
|
|
592
|
+
${k},
|
|
568
593
|
products: {
|
|
569
594
|
enabled: false,
|
|
570
595
|
items: []
|
|
571
596
|
}
|
|
572
597
|
};
|
|
573
|
-
`;await
|
|
574
|
-
`)}function
|
|
575
|
-
`)}async function
|
|
576
|
-
`+
|
|
577
|
-
`+
|
|
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:
|
|
578
603
|
image: postgres:18-alpine
|
|
579
604
|
ports:
|
|
580
605
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -610,16 +635,16 @@ ${h},
|
|
|
610
635
|
image: inngest/inngest:v1.17.4
|
|
611
636
|
ports:
|
|
612
637
|
- "\${INNGEST_PORT:-8288}:8288"
|
|
613
|
-
command: inngest dev`);let
|
|
638
|
+
command: inngest dev`);let i=`services:
|
|
614
639
|
${n.join(`
|
|
615
640
|
|
|
616
641
|
`)}
|
|
617
|
-
`;
|
|
642
|
+
`;r.length>0&&(i+=`
|
|
618
643
|
volumes:
|
|
619
644
|
${r.join(`
|
|
620
645
|
`)}
|
|
621
|
-
`),await
|
|
622
|
-
`)}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";
|
|
623
648
|
import app from "@repo/api";
|
|
624
649
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
625
650
|
|
|
@@ -650,12 +675,12 @@ bootstrap().catch((error) => {
|
|
|
650
675
|
logger.error("[Backend] Fatal error", error);
|
|
651
676
|
process.exit(1);
|
|
652
677
|
});
|
|
653
|
-
`)}import{readFile as
|
|
654
|
-
export const pool = db.$client
|
|
655
|
-
import { drizzle } from "drizzle-orm/neon-
|
|
656
|
-
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";
|
|
657
682
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
658
|
-
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";
|
|
659
684
|
import { Redis } from "ioredis";
|
|
660
685
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
661
686
|
import { env } from "./env";
|
|
@@ -784,7 +809,7 @@ export async function closeRedis() {
|
|
|
784
809
|
closed = true;
|
|
785
810
|
}
|
|
786
811
|
}
|
|
787
|
-
`)}async function
|
|
812
|
+
`)}async function jo(e){await c(Tt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
788
813
|
import { redis } from "./redis";
|
|
789
814
|
|
|
790
815
|
export class MutexTimeoutError extends Error {
|
|
@@ -821,7 +846,7 @@ export async function withMutex<T>(
|
|
|
821
846
|
await mutex.release();
|
|
822
847
|
}
|
|
823
848
|
}
|
|
824
|
-
`)}async function
|
|
849
|
+
`)}async function Uo(e){await c(Tt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
825
850
|
import type { Store } from "hono-rate-limiter";
|
|
826
851
|
import { env } from "./env";
|
|
827
852
|
|
|
@@ -939,7 +964,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
939
964
|
|
|
940
965
|
/** No persistent connection to close with Upstash REST. */
|
|
941
966
|
export async function closeRedis(): Promise<void> {}
|
|
942
|
-
`)}async function
|
|
967
|
+
`)}async function Mo(e){await c(Tt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
943
968
|
import { redis } from "./redis";
|
|
944
969
|
|
|
945
970
|
export class MutexTimeoutError extends Error {
|
|
@@ -984,7 +1009,7 @@ export async function withMutex<T>(
|
|
|
984
1009
|
await lock.release();
|
|
985
1010
|
}
|
|
986
1011
|
}
|
|
987
|
-
`)}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";
|
|
988
1013
|
|
|
989
1014
|
const EnvSchema = z.object({
|
|
990
1015
|
NODE_ENV: z.enum(["development", "production"]).default("development"),
|
|
@@ -1081,7 +1106,10 @@ ${e.cacheProvider==="upstash"?` UPSTASH_REDIS_REST_URL: z.string(),
|
|
|
1081
1106
|
OPENAI_API_KEY: z.string().optional(),
|
|
1082
1107
|
OPENROUTER_API_KEY: z.string().optional(),
|
|
1083
1108
|
|
|
1084
|
-
MASTRA_TELEMETRY_DISABLED: z.string().optional()
|
|
1109
|
+
MASTRA_TELEMETRY_DISABLED: z.string().optional(),
|
|
1110
|
+
|
|
1111
|
+
/** Server-side override for \`config.observability.sentry.dsn\`. Optional: the committed config value is the default. */
|
|
1112
|
+
SENTRY_DSN: z.string().optional()
|
|
1085
1113
|
});
|
|
1086
1114
|
|
|
1087
1115
|
export const env = (() => {
|
|
@@ -1108,13 +1136,13 @@ export const env = (() => {
|
|
|
1108
1136
|
const parsedApiUrl = new URL(env.API_URL);
|
|
1109
1137
|
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1110
1138
|
export const apiOrigin = parsedApiUrl.origin;
|
|
1111
|
-
`}import{readFile as
|
|
1112
|
-
`)}function
|
|
1113
|
-
`)}var
|
|
1114
|
-
`))}}import{readFile as
|
|
1115
|
-
`);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",
|
|
1116
1144
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1117
|
-
`);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",
|
|
1118
1146
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1119
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",
|
|
1120
1148
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1135,100 +1163,26 @@ vi.mock("@upstash/lock", () => {
|
|
|
1135
1163
|
return { Lock };
|
|
1136
1164
|
});
|
|
1137
1165
|
|
|
1138
|
-
$1`),r!==n&&await
|
|
1139
|
-
|
|
1140
|
-
`,"","api
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
// forwards its root \`/.well-known/oauth-*\` paths to this app. Gated like the \`/mcp\` endpoint
|
|
1145
|
-
// itself, so the routes are absent entirely when the feature is off.
|
|
1146
|
-
if (config.mcpServer?.enabled) {
|
|
1147
|
-
app.route("/", mcpDiscoveryRoutes);
|
|
1148
|
-
}
|
|
1149
|
-
`,"","api index mcp discovery mount",n);let s=B(t,"packages/auth/src/config.ts");await I(s,` magicLink,
|
|
1150
|
-
mcp,
|
|
1151
|
-
organization,`,` magicLink,
|
|
1152
|
-
organization,`,"auth config mcp plugin import",n),await I(s,` // Outward MCP server: turns Better Auth into an OAuth 2.1 provider so an
|
|
1153
|
-
// external agent (Hermes/OpenClaw) can authenticate and drive the app's
|
|
1154
|
-
// capability layer over MCP. Brings the oauthApplication/oauthAccessToken/
|
|
1155
|
-
// oauthConsent tables (run \`pnpm auth:generate\` after toggling).
|
|
1156
|
-
...(config.mcpServer?.enabled
|
|
1157
|
-
? [mcp({ loginPage: \`\${config.baseUrl}\${config.routes.auth}/login\` })]
|
|
1158
|
-
: []),
|
|
1159
|
-
`,"","auth config mcp plugin block",n);let u=B(t,"packages/auth/package.json"),g=JSON.parse(await Ao(u,"utf-8"));if(!g.exports)throw new Error(`${n}: expected an exports map in packages/auth/package.json (boilerplate drift).`);Zt(g.exports,"./mcp",'the "./mcp" export in packages/auth/package.json',n),await p(u,JSON.stringify(g,null," ")+`
|
|
1160
|
-
`);let l=B(t,"packages/api/package.json"),h=JSON.parse(await Ao(l,"utf-8"));if(!h.dependencies)throw new Error(`${n}: expected dependencies in packages/api/package.json (boilerplate drift).`);Zt(h.dependencies,"@mastra/mcp","@mastra/mcp in packages/api dependencies",n),Zt(h.dependencies,"@modelcontextprotocol/sdk","@modelcontextprotocol/sdk in packages/api dependencies",n),await p(l,JSON.stringify(h,null," ")+`
|
|
1161
|
-
`);let y=at(e);if(await Mr(t,y,"companion-agent-mcp",`/${y}/companion-agent-mcp`,n,"MCP"),await I(B(t,`docs/${y}/configuration.mdx`),`| \`mcpServer.enabled\` | \`false\` (requires \`ai\`) | Outward MCP server URL + the **MCP** settings tab - see [external agent (MCP)](/${y}/companion-agent-mcp) |
|
|
1162
|
-
`,"","configuration.mdx mcpServer config-table row",n),e.companion){let _=B(t,`docs/${y}/companion/index.mdx`);await I(_,`It is the user-owned counterpart to the [external agent (MCP)](/${y}/companion-agent-mcp): the MCP server lets a third-party agent reach into your app, while the companion daemon runs on the user's own hardware and reaches out to your app over authenticated HTTP.
|
|
1163
|
-
|
|
1164
|
-
`,"","companion index.mdx MCP counterpart paragraph",n),await I(_,` <Card title="External Agent (MCP)" href="/${y}/companion-agent-mcp" description="The other side - expose your app's capabilities to an external always-on agent over MCP." />
|
|
1165
|
-
`,"","companion index.mdx MCP card",n)}}import{readFile as Ro,rm as O}from"fs/promises";import{join as R}from"path";import{readFile as on}from"fs/promises";import{join as Tt}from"path";async function Po(e,t){let n=Tt(e,"packages/api/src/routes/internal/index.ts");await p(n,C(await on(n,"utf-8"),"internal router","companion",t)),await Qt(n);let r=Tt(e,"packages/api/src/ai/schedule-runner.ts");await p(r,C(await on(r,"utf-8"),"schedule-runner.ts","companion",t));for(let a of["packages/api/src/routes/internal/notifications.ts","packages/api/src/routes/internal/ai/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let s=Tt(e,a);await p(s,C(await on(s,"utf-8"),a,"companion",t))}let o=Tt(e,"packages/api/src/ai/settings-store.ts");await I(o,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1166
|
-
|
|
1167
|
-
`,"","settings-store.ts relay import",t),await I(o," * - COMPANION (when `config.companion.enabled`): a well-formed companion key\n * `<connectionId>@<deviceId>[@<modelId>]` persists as-is (the run path resolves it, and the\n * daemon handles an offline device).\n","","settings-store.ts COMPANION docstring bullet",t),await I(o,` if (config.companion?.enabled === true && parseCompanionKey(key) !== null) {
|
|
1168
|
-
return key;
|
|
1169
|
-
}
|
|
1170
|
-
`,"","settings-store.ts companion-key branch",t);let i=Tt(e,"packages/api/tests/ai/settings-store.test.ts");await p(i,C(await on(i,"utf-8"),"settings-store.test.ts","companion",t))}var ps=["companion:export","companion:verify","companion:publish"];async function Bn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await O(R(t,"packages/api/src/relay"),{recursive:!0}),await O(R(t,"packages/api/src/companion"),{recursive:!0}),await O(R(t,"packages/api/src/ai/companion-model.ts")),await O(R(t,"packages/api/tests/relay"),{recursive:!0}),await O(R(t,"packages/api/tests/companion"),{recursive:!0}),await O(R(t,"packages/api/src/routes/internal/companion.ts")),await O(R(t,"packages/api/src/routes/internal/companion-transport.ts")),await O(R(t,"packages/api/tests/routes/companion.test.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-harness.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-poll.test.ts")),await O(R(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await O(R(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await O(R(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await O(R(t,"packages/api/tests/ai/companion-model.test.ts")),await O(R(t,"packages/api/tests/ai/companion-chat.test.ts")),await O(R(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await O(R(t,"packages/api/tests/helpers/redis-mock.ts"));let r=R(t,"packages/api/package.json"),o=JSON.parse(await Ro(r,"utf-8"));if(!o.exports?.["./companion"])throw new Error(`${n}: expected packages/api/package.json to carry the ./companion export`);delete o.exports["./companion"],await Xt(r,o," ",n),await Po(t,n);let i=at(e);await Br(t,i,"companion",[`/${i}/companion`,`/${i}/companion/publishing`],n,"Companions"),await I(R(t,`docs/${i}/ai.mdx`),`Runs on a paired [companion](/${i}/companion) CLI are never metered either - the user's own subscription executes them. `,"","ai.mdx companion metering sentence",n),await I(R(t,`docs/${i}/configuration.mdx`),`| \`companion.enabled\` | \`false\` (requires \`ai\`) | Companion daemon pairing + the **Companions** settings tab - see [companion](/${i}/companion) |
|
|
1171
|
-
`,"","configuration.mdx companion config-table row",n)}async function Gn(e){if(Bt(e))return;let t=e.projectDir;await O(R(t,"apps/companion"),{recursive:!0}),await O(R(t,"scripts/companion-export"),{recursive:!0}),await ls(t)}async function Kn(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="stripDesktopCompanionDoc";await O(R(t,"docs/desktop/companion.mdx"));let r=R(t,"docs/desktop/meta.json"),o=JSON.parse(await Ro(r,"utf-8"));if(!o.pages.includes("companion"))throw new Error(`${n}: expected the desktop meta.json companion nav entry, but it was missing (boilerplate drift).`);o.pages=o.pages.filter(i=>i!=="companion"),await p(r,`${JSON.stringify(o,null,2)}
|
|
1172
|
-
`),await I(R(t,"docs/desktop/index.mdx"),` <Card href="/desktop/companion" title="Companion setup" description="The companion ships inside the app and runs as a local daemon, consent-first - no separate install, and pairing is optional." />
|
|
1173
|
-
`,"","desktop index companion card",n)}async function ls(e){await Hn(e,ps)}var ds=new Set(["ci.yml","desktop-release.yml"]),us={nextjs:["apps/web-next/app/[locale]/(marketing)/download","apps/web-next/tests/routes/download-page.test.tsx"],nuxt:["apps/web-nuxt/app/pages/download.vue","apps/web-nuxt/app/middleware/desktop.ts","apps/web-nuxt/server/api/desktop-releases.get.ts","apps/web-nuxt/tests/pages/download.test.ts"]},ms=["@repo/ai","@repo/agent-core","@repo/agent-core-types","ai","@ai-sdk/react","@homebridge/node-pty-prebuilt-multiarch","@xterm/xterm","@xterm/addon-fit"],fs=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:build","playground:test:companion","ai:parity"];async function xo(e){let t=w(e.projectDir,".github/workflows"),n=await zn(t).catch(()=>[]);for(let r of n)ds.has(r)||await U(w(t,r),{recursive:!0,force:!0})}async function Hn(e,t){let n=w(e,"package.json"),r=JSON.parse(await V(n,"utf-8"));if(!r.scripts)return!1;let o=!1;for(let i of t)i in r.scripts&&(delete r.scripts[i],o=!0);return o&&await p(n,JSON.stringify(r,null," ")+`
|
|
1174
|
-
`),o}async function To(e){let t=[...fs];Mt(e)||t.push("infra","infra:stop"),await Hn(e.projectDir,t)}async function _o(e){let t=w(e.projectDir,"package.json"),n=await V(t,"utf-8"),r=JSON.parse(n);!r.scripts||!("dev"in r.scripts)||(r.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await p(t,JSON.stringify(r,null," ")+`
|
|
1175
|
-
`))}async function Oo(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await U(w(e.projectDir,t),{recursive:!0,force:!0})}async function Co(e){e.docs||await U(w(e.projectDir,"apps/docs"),{recursive:!0})}async function Do(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await U(w(e.projectDir,t),{recursive:!0,force:!0}),await U(w(e.projectDir,"docs/index.mdx")),!e.desktop)await U(w(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!(e.desktop&&e.ai)){await U(w(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=w(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await V(n,"utf-8"));r.pages=r.pages.filter(o=>o!=="ai"),await p(n,`${JSON.stringify(r,null,2)}
|
|
1176
|
-
`)}await gs(e)}async function gs(e){let t=e.projectDir,n="stripUnusedDocsSilo",r=at(e),o=w(t,`docs/${r}/configuration.mdx`),i=e.desktop&&e.ai;e.desktop||(await I(o,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",n),await I(o,"<Callout>\n**Shipping the [desktop app](/desktop)?** It needs no entry in `TRUSTED_ORIGINS`: its main process makes every backend call - dev and packaged alike - with no `Origin` header, so the backend treats it as a native client and never CORS-checks it. `TRUSTED_ORIGINS` governs your web frontends.\n</Callout>\n\n","","configuration.mdx desktop TRUSTED_ORIGINS callout",n),await I(w(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",n)),i||(await I(o,"The desktop app's AI orchestration gates on `config.desktop.agents.enabled`, which a desktop project derives from your AI option (not a separate switch) - see [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",n),e.companion&&(await I(w(t,`docs/${r}/companion/index.mdx`),`## Set up from the desktop app
|
|
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
|
|
1177
1172
|
|
|
1178
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).
|
|
1179
1174
|
|
|
1180
|
-
`,"","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
|
|
1181
1176
|
|
|
1182
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).
|
|
1183
1178
|
|
|
1184
|
-
`,"","companion terminal.mdx desktop-panel section",n)))
|
|
1185
|
-
`,"","desktop index.mdx AI card",n)}async function No(e){if(e.desktop)return;await U(w(e.projectDir,"apps/electron"),{recursive:!0});let t=w(e.projectDir,"packages/i18n/translations");for(let o of await zn(t,{withFileTypes:!0}))o.isDirectory()&&await U(w(t,o.name,"desktop.json"),{force:!0});await U(w(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of us[e.frontend])await U(w(e.projectDir,o),{recursive:!0});await U(w(e.projectDir,"packages/utils/src/desktop-download.ts")),await U(w(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=w(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await V(n,"utf-8"));if(!r.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete r.exports["./desktop-download"],await Xt(n,r," ","stripDesktopApp")}async function $o(e){Bt(e)||await U(w(e.projectDir,"packages/agent-core"),{recursive:!0})}function _t(e,t,n,r){let o=e.indexOf(t);if(o===-1)throw new Error(`stripDesktopAi: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(e.indexOf(t,o+t.length)!==-1)throw new Error(`stripDesktopAi: the ${r} seam appears more than once (boilerplate drift).`);return e.slice(0,o)+n+e.slice(o+t.length)}async function Lo(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="apps/electron";for(let a of[`${n}/src/renderer/screens/agents`,`${n}/src/renderer/screens/chat.tsx`,`${n}/src/renderer/screens/schedules.tsx`,`${n}/src/renderer/screens/settings/models.tsx`,`${n}/src/renderer/screens/settings/tasks.tsx`,`${n}/src/renderer/screens/settings/mcp.tsx`,`${n}/src/renderer/screens/settings/integrations.tsx`,`${n}/src/renderer/screens/settings/integration-add-dialog.tsx`,`${n}/src/renderer/screens/settings/integration-types.ts`,`${n}/src/renderer/screens/settings/settings-tabs.tsx`,`${n}/src/renderer/screens/settings/settings-tab-ids.ts`,`${n}/src/renderer/screens/settings/connected-cache.ts`,`${n}/src/renderer/components/section-tabs.tsx`,`${n}/src/renderer/hooks/use-ai-terminal.ts`,`${n}/src/renderer/hooks/use-xterm.ts`,`${n}/src/renderer/hooks/use-automation-lifecycle.ts`,`${n}/src/renderer/lib/companion`,`${n}/src/renderer/hooks/use-chat-controller.ts`,`${n}/src/renderer/hooks/use-local-run.ts`,`${n}/src/renderer/hooks/use-local-model-options.ts`,`${n}/src/renderer/lib/drive-chat-store.ts`,`${n}/src/renderer/lib/local-drive.ts`,`${n}/src/renderer/hooks/use-mounted.ts`,`${n}/src/renderer/lib/ai`,`${n}/src/renderer/lib/side-panel-state.ts`,`${n}/src/renderer/components/side-panel-dock.tsx`,`${n}/src/renderer/components/side-panel.tsx`,`${n}/src/renderer/config/side-panels.tsx`,`${n}/src/renderer/components/command-palette/command-palette-ai-commands.tsx`])await U(w(t,a),{recursive:!0});for(let a of[`${n}/src/preload/api-contract.ts`,`${n}/src/main/drive-transport.ts`,`${n}/src/main/companion.ts`,`${n}/src/main/companion-state.ts`,`${n}/src/main/companion-parsers.ts`,`${n}/src/main/companion-paths.ts`,`${n}/src/main/companion-drive.ts`,`${n}/src/main/companion-staging.ts`,`${n}/src/main/companion-stderr-tail.ts`,`${n}/src/main/companion-commands-pure.ts`,`${n}/src/main/companion-shared.ts`,`${n}/src/main/companion-commands.ts`,`${n}/src/main/terminal.ts`,`${n}/src/main/terminal-state.ts`])await U(w(t,a));await U(w(t,`${n}/scripts/stage-companion.mjs`));for(let a of[`${n}/tests/ai-import-boundary.test.ts`,`${n}/tests/renderer/settings-tab-ids.test.ts`,`${n}/tests/renderer/connected-cache.test.ts`,`${n}/tests/renderer/router-redirects.test.ts`,`${n}/tests/renderer/lib/side-panel-state.test.ts`,`${n}/tests/renderer/schedules-view.test.ts`,`${n}/tests/renderer/automation-status.test.ts`,`${n}/tests/renderer/consent-dialog.test.ts`,`${n}/tests/renderer/background-mode.test.ts`,`${n}/tests/renderer/connection-state.test.ts`,`${n}/tests/renderer/models-empty-view.test.ts`,`${n}/tests/renderer/models-default-reset.test.ts`,`${n}/tests/renderer/cli-catalog.test.ts`,`${n}/tests/renderer/connect-flow.test.ts`,`${n}/tests/renderer/terminal-settings-view.test.ts`,`${n}/tests/renderer/mcp-section-i18n.test.ts`,`${n}/tests/renderer/reload-on-companion-ready.test.ts`,`${n}/tests/renderer/schedule-merge.test.ts`,`${n}/tests/renderer/terminal-tools.test.ts`,`${n}/tests/renderer/terminal-hint-interpolation.test.ts`,`${n}/tests/renderer/lib/companion/consent.test.ts`,`${n}/tests/renderer/lib/companion/ensure.test.ts`,`${n}/tests/renderer/lib/companion/pairing.test.ts`,`${n}/tests/renderer/lib/companion/ensure-unpublished-brand.test.ts`,`${n}/tests/renderer/lib/companion/terminal.test.ts`,`${n}/tests/renderer/lib/companion/terminal-unpublished-brand.test.ts`,`${n}/tests/task-overrides.test.ts`,`${n}/tests/local-drive.test.ts`,`${n}/tests/drive-chat-store.test.ts`,`${n}/tests/use-local-run.test.ts`,`${n}/tests/use-local-model-options.test.ts`,`${n}/tests/renderer/chat-controller-local-seed.test.ts`,`${n}/tests/main/companion-state.test.ts`,`${n}/tests/main/companion-commands.test.ts`,`${n}/tests/main/companion-supervisor.test.ts`,`${n}/tests/main/companion-restage.test.ts`,`${n}/tests/main/companion-teardown.process.test.ts`,`${n}/tests/stage-companion.test.ts`,`${n}/tests/main/drive-preload-stream.test.ts`,`${n}/tests/main/drive-transport.test.ts`,`${n}/tests/main/ipc.test.ts`,`${n}/tests/main/terminal-cli-allowlist.test.ts`,`${n}/tests/main/terminal-manager.process.test.ts`,`${n}/tests/main/terminal-state.test.ts`,`${n}/tests/main/terminal-teardown.process.test.ts`,`${n}/tests/renderer/api-consumer-fixture.ts`])await U(w(t,a));let r=w(t,`${n}/package.json`),o=JSON.parse(await V(r,"utf-8"));for(let a of ms){if(!o.dependencies||!(a in o.dependencies))throw new Error(`stripDesktopAi: expected ${a} in ${n} dependencies (boilerplate drift).`);delete o.dependencies[a]}if(!o.scripts||!("rebuild:electron"in o.scripts))throw new Error(`stripDesktopAi: expected the rebuild:electron script in ${n} package.json (boilerplate drift).`);delete o.scripts["rebuild:electron"],hs(o,"stage:companion",n),await p(r,JSON.stringify(o,null,2)+`
|
|
1186
|
-
`),await ys(t,n);let i=w(t,"packages/i18n/translations");for(let a of await zn(i,{withFileTypes:!0})){if(!a.isDirectory())continue;let s=w(i,a.name,"desktop.json"),u=await V(s,"utf-8").catch(()=>null);if(u===null)continue;let g=JSON.parse(u),l=!1;for(let h of["agents","ai_hub","schedules","integrations"])h in g&&(delete g[h],l=!0);l&&await p(s,JSON.stringify(g,null," ")+`
|
|
1187
|
-
`)}}function hs(e,t,n){if(!e.scripts||!(t in e.scripts))throw new Error(`stripDesktopAi: expected the ${t} script in ${n} package.json (boilerplate drift).`);delete e.scripts[t];let r=`pnpm run ${t} && `;for(let o of["build:unpack","build:win","build:mac","build:linux","release"]){let i=e.scripts[o];if(i===void 0||!i.startsWith(r))throw new Error(`stripDesktopAi: expected ${o} to begin with "${r}" in ${n} package.json (boilerplate drift).`);e.scripts[o]=i.slice(r.length)}}async function ys(e,t){let n=w(e,`${t}/src/renderer/components/shell.tsx`);await p(n,C(await V(n,"utf-8"),"components/shell.tsx"));let r=w(e,`${t}/src/renderer/components/auth-gate.tsx`);await p(r,C(await V(r,"utf-8"),"components/auth-gate.tsx")),await I(r,` // The chat shell owns the ONE chat controller above the router, so a run keeps streaming as the user
|
|
1188
|
-
// moves between the \`/chat\` screen and the side-panel chat tab. Stripped to a bare RouterProvider when
|
|
1189
|
-
// the agents feature is off.
|
|
1190
|
-
return (
|
|
1191
|
-
<ChatShellProvider>
|
|
1192
|
-
<RouterProvider router={router} />
|
|
1193
|
-
</ChatShellProvider>
|
|
1194
|
-
)
|
|
1195
|
-
`,` return <RouterProvider router={router} />
|
|
1196
|
-
`,"auth-gate chat shell wrapper","stripDesktopAi");let o=w(e,`${t}/src/renderer/config/sidebar.ts`),i=C(await V(o,"utf-8"),"config/sidebar.ts");i=_t(i,`import {
|
|
1197
|
-
BuildingsIcon,
|
|
1198
|
-
ChatCircleIcon,
|
|
1199
|
-
ClockCountdownIcon,
|
|
1200
|
-
GearIcon,
|
|
1201
|
-
HouseIcon,
|
|
1202
|
-
UserCircleIcon
|
|
1203
|
-
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await p(o,i);let a=w(e,`${t}/src/renderer/lib/config.ts`),s=C(await V(a,"utf-8"),"lib/config.ts");s=s.replace(/,(\n\} as const)/,"$1"),await p(a,s);let u=w(e,`${t}/src/renderer/lib/sidebar-flags.ts`);await p(u,C(await V(u,"utf-8"),"lib/sidebar-flags.ts"));let g=w(e,`${t}/src/renderer/router.tsx`),l=C(await V(g,"utf-8"),"router.tsx");l=_t(l,`import { clientConfig } from '@/lib/config'
|
|
1204
|
-
`,"","router clientConfig import"),l=_t(l,` createRouter,
|
|
1205
|
-
redirect
|
|
1206
|
-
} from '@tanstack/react-router'`,` createRouter
|
|
1207
|
-
} from '@tanstack/react-router'`,"router redirect import specifier"),l=_t(l,`import { ChatScreen } from '@/screens/chat'
|
|
1208
|
-
import { SchedulesScreen } from '@/screens/schedules'
|
|
1209
|
-
import { ModelsSettingsScreen } from '@/screens/settings/models'
|
|
1210
|
-
import { TasksSettingsScreen } from '@/screens/settings/tasks'
|
|
1211
|
-
import { McpSettingsScreen } from '@/screens/settings/mcp'
|
|
1212
|
-
import { IntegrationsSettingsScreen } from '@/screens/settings/integrations'
|
|
1213
|
-
`,"","router AI screen imports"),l=_t(l,` ...(clientConfig.agentsEnabled ? aiRoutes : []),
|
|
1214
|
-
`,"","router ai route spread"),await p(g,l);let h=w(e,`${t}/src/renderer/screens/settings/index.tsx`);await p(h,C(await V(h,"utf-8"),"screens/settings/index.tsx"));let y=w(e,`${t}/src/main/ipc.ts`);await p(y,C(await V(y,"utf-8"),"src/main/ipc.ts"));let _=w(e,`${t}/src/main/index.ts`);await p(_,C(await V(_,"utf-8"),"src/main/index.ts"));let v=w(e,`${t}/src/preload/index.ts`);await p(v,C(await V(v,"utf-8"),"src/preload/index.ts"));let $=w(e,`${t}/electron-builder.mjs`);await p($,C(await V($,"utf-8"),"electron-builder.mjs"))}import{readFile as ws}from"fs/promises";import{join as vs}from"path";var Uo=`on:
|
|
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:
|
|
1215
1180
|
workflow_run:
|
|
1216
1181
|
workflows: ["Tag Release"]
|
|
1217
1182
|
branches: [main]
|
|
1218
1183
|
types: [completed]
|
|
1219
|
-
workflow_dispatch:`,
|
|
1220
|
-
workflow_run:
|
|
1221
|
-
workflows: ["CI"]
|
|
1222
|
-
branches: [main]
|
|
1223
|
-
types: [completed]
|
|
1224
|
-
workflow_dispatch:`,bs=`on:
|
|
1225
|
-
# Automatic release on CI success is disabled for this project to conserve
|
|
1226
|
-
# GitHub Actions minutes. Re-enable by uncommenting the workflow_run trigger.
|
|
1227
|
-
# workflow_run:
|
|
1228
|
-
# workflows: ["CI"]
|
|
1229
|
-
# branches: [main]
|
|
1230
|
-
# types: [completed]
|
|
1231
|
-
workflow_dispatch:`;async function jo(e){if(!e.desktop)return;let t=vs(e.projectDir,".github/workflows/desktop-release.yml"),n=await ws(t,"utf8");if(!n.includes(Uo))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);let r=e.desktopAutoRelease?ks:bs;await p(t,n.replace(Uo,r))}import{join as Ss}from"path";async function Mo(e){let t=Es(e);await p(Ss(e.projectDir,".github/workflows/ci.yml"),t)}function Es(e){let t=q[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",o=t?"":` services:
|
|
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:
|
|
1232
1186
|
postgres:
|
|
1233
1187
|
image: postgres:18-alpine
|
|
1234
1188
|
env:
|
|
@@ -1242,14 +1196,13 @@ import { IntegrationsSettingsScreen } from '@/screens/settings/integrations'
|
|
|
1242
1196
|
--health-interval 10s
|
|
1243
1197
|
--health-timeout 5s
|
|
1244
1198
|
--health-retries 5
|
|
1245
|
-
`,
|
|
1199
|
+
`,o=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",s=n?`
|
|
1246
1200
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1247
|
-
UPSTASH_REDIS_REST_TOKEN: test-token`:"",
|
|
1201
|
+
UPSTASH_REDIS_REST_TOKEN: test-token`:"",a=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1248
1202
|
STRIPE_SECRET_KEY: test
|
|
1249
1203
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1250
1204
|
POLAR_ACCESS_TOKEN: test
|
|
1251
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1252
|
-
${y.name}: test`).join("")).join("");return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
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.)
|
|
1253
1206
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1254
1207
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1255
1208
|
|
|
@@ -1273,8 +1226,8 @@ jobs:
|
|
|
1273
1226
|
name: Checks
|
|
1274
1227
|
runs-on: ubuntu-latest
|
|
1275
1228
|
timeout-minutes: 20
|
|
1276
|
-
${
|
|
1277
|
-
CONTENT_API_KEY: test-contentapi-key-16chars${
|
|
1229
|
+
${i} env:
|
|
1230
|
+
CONTENT_API_KEY: test-contentapi-key-16chars${s}${a}
|
|
1278
1231
|
STORAGE_REGION: test
|
|
1279
1232
|
STORAGE_ENDPOINT: http://test
|
|
1280
1233
|
STORAGE_ACCESS_KEY_ID: test
|
|
@@ -1295,51 +1248,53 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1295
1248
|
NODE_OPTIONS: --max-old-space-size=6144`:" - run: pnpm check-types"}
|
|
1296
1249
|
|
|
1297
1250
|
- name: Write root env
|
|
1298
|
-
run: echo "DATABASE_URL=${
|
|
1251
|
+
run: echo "DATABASE_URL=${o}" > .env
|
|
1299
1252
|
|
|
1300
1253
|
- run: pnpm test
|
|
1301
|
-
`}import{readFile as
|
|
1302
|
-
`))}async function
|
|
1303
|
-
`))}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
|
|
1304
1257
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1305
1258
|
export { ops } from "./${n}/index";
|
|
1306
|
-
`;await
|
|
1307
|
-
`).filter(
|
|
1308
|
-
`)}import{readdir as
|
|
1309
|
-
`).filter(
|
|
1310
|
-
`).length&&await
|
|
1311
|
-
`))}async function
|
|
1312
|
-
`),await
|
|
1313
|
-
`)}import{relative as
|
|
1314
|
-
`);
|
|
1315
|
-
${
|
|
1316
|
-
`),
|
|
1317
|
-
`),
|
|
1318
|
-
`),Q.yellow("Deployment"))}function ac(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function sc(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function ft(e){let n=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function He(e,t){let n=ft(e),r=ft(t);if(!n||!r)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function pn(e,t){return e.versions.find(n=>n.version===t)?.cli}function ui(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ft(e)===null}function ln(e,t,n="2.1.0"){if(ui(n))return{ok:!0};let r=pn(e,e.latest);return!r||ft(r)===null?{ok:!0}:He(n,r)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${n}) is too old for template v${e.latest}, which needs CLI v${r} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function mi(e,t,n="2.1.0"){if(ui(n))return{ok:!0};let r=pn(e,t);return!r||ft(r)===null?{ok:!0}:He(n,r)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${r} exactly (the CLI whose generators produced that release). Run npx generatesaas@${r} init.`}}import mc from"picocolors";var fc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function gc(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),n=[...new Uint8Array(t).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}function fi(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new W("--frontend <type>","frontend framework").choices([...$e])).addOption(new W("--architecture <type>","fullstack or separate").choices([...We])).addOption(new W("--payment <provider>","payment provider").choices([...Xe])).addOption(new W("--email <provider>","email provider").choices([...Ze])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new W("--billing-scope <scope>","billing scope (requires --org)").choices([...tt])).option("--blog","enable blog").option("--no-blog","disable blog").option("--email-tracking","enable email analytics (open/click tracking + admin analytics page)").option("--no-email-tracking","disable email analytics").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--desktop-auto","auto-trigger the desktop release workflow on CI success (default: manual-only)").option("--no-desktop-auto","manual-only desktop releases (workflow_dispatch)").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion + MCP server").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - a daemon your users install to run their own AI subscriptions for this app (shared repo or vendored)").option("--no-companion","exclude the backend companion feature").addOption(new W("--companion-source <source>","companion source: point at an existing shared companion repo, or vendor your own branded daemon").choices([...Le])).option("--companion-repo-url <url>","GitHub URL of the shared companion repo (with --companion-source shared; default: OpenCompanion)").option("--companion-local-path <path>","path to your local checkout of the shared companion (optional, for developing it alongside)").option("--mcp-server","include the outward MCP server (the /mcp route + Better Auth mcp() provider)").option("--no-mcp-server","exclude the outward MCP server").option("--ai-builtin","built-in AI: models under your app's name via OpenRouter, billed from credits (default)").option("--no-ai-builtin","no built-in AI").option("--ai-byok","let end-users connect their own provider API keys (default)").option("--no-ai-byok","no user-supplied API keys").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").option("--docker <services>","comma-separated: postgres,redis,inngest,mailpit").option("--ai-tools <tools>","comma-separated: claude-code,cursor,codex,gemini-cli,windsurf").option("--social-providers <providers>","comma-separated: google,github,facebook,discord,x").addOption(new W("--currency <code>","default currency for billing").choices([...fe])).addOption(new W("--deploy <target>","deployment target").choices([...ge])).addOption(new W("--database <provider>","database provider").choices([...he])).addOption(new W("--cache <provider>","cache provider").choices([...ye])).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new W("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new W("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await hc(t?{...n,apiKey:t}:n)})}async function hc(e){let t=performance.now();ur("2.1.0");let n;try{n=Rr(e)}catch(k){A.cancel(T(k)),process.exit(1)}let r=A.spinner(),o;try{o=await ot({apiKey:e.apiKey,prompt:!e.yes})}catch(k){A.cancel(T(k)),process.exit(1)}e.demo&&qn(o)!==fc&&(A.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=ke(o),a,s=async()=>{a=await Re(i);let k=ln(a,"init");if(!k.ok)throw new Error(k.message);return{latestVersion:a.latest,selectedVersion:a.latest,desktopAllowed:a.entitlements?.desktopAllowed??!0,companionAllowed:a.entitlements?.companionAllowed??!0}};r.start("Verifying access...");let u,g,l=!0,h=!0;try{({latestVersion:u,selectedVersion:g,desktopAllowed:l,companionAllowed:h}=await s()),r.stop("Access verified."),Me(o)}catch(k){if(r.stop("Access verification failed."),k instanceof F&&k.status===401){e.yes&&(A.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),A.log.warning("Invalid API key."),o=await It(),i=ke(o),r.start("Verifying access...");try{({latestVersion:u,selectedVersion:g,desktopAllowed:l,companionAllowed:h}=await s()),r.stop("Access verified."),Me(o)}catch(x){r.stop("Access verification failed."),A.cancel(x instanceof F&&x.status===401?"Invalid API key.":T(x)),process.exit(1)}}else A.cancel(T(k)),process.exit(1)}A.log.success(`Latest version: ${u}`),n.desktop===!0&&!l&&(A.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),n.companion===!0&&!h&&(A.cancel("The companion is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let y;e.yes?y=xr({...n,...l?{}:{desktop:!1},...h?{}:{companion:!1}}):y=await Tr(n,{desktopAllowed:l,companionAllowed:h});let _;r.start("Activating license...");try{let k=e.demo&&y.baseUrl?await gc(y.baseUrl):crypto.randomUUID(),x=()=>({frontend:y.frontend,version:g,installId:k,projectName:y.projectName,options:Nr(y)}),ue;try{ue=await Rn(i,x())}catch(M){let b=Jt(M);if(!b?.lastAllowedVersion||!a)throw M;r.stop("License activation failed.");let L=mi(a,b.lastAllowedVersion);if(L.ok||(A.cancel(`${b.message} ${L.message}`),process.exit(1)),e.yes){let oe=pn(a,b.lastAllowedVersion);A.cancel(`${b.message} Re-run ${oe?`npx generatesaas@${oe} init`:"init"} without --yes to continue with v${b.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let Ce=await A.confirm({message:`Your update window has ended. Continue with v${b.lastAllowedVersion} (the last version your license covers)?`});(A.isCancel(Ce)||!Ce)&&(A.cancel("Setup cancelled."),process.exit(0)),g=b.lastAllowedVersion,r.start(`Activating license for v${g}...`),ue=await Rn(i,x())}_={token:ue.token,keyHash:qn(o),installId:ue.installId??k},r.stop("License activated.")}catch(k){r.stop("License activation failed."),A.cancel(T(k)),process.exit(1)}let v=uc(y.projectDir);if(cc(v)&&pc(v).length>0)if(e.yes)A.log.info(`Directory ${v} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let x=await A.select({message:`Directory ${v} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(A.isCancel(x)||x==="cancel")&&(A.cancel("Setup cancelled."),process.exit(0)),x==="overwrite"&&lc(v,{recursive:!0,force:!0})}let $={...y,projectDir:v,version:g,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await qt(i,g,v),r.stop("Template downloaded.")}catch(k){r.stop("Download failed."),A.cancel(T(k)),process.exit(1)}let ne;r.start("Generating project files...");try{if({dockerComposeGenerated:ne}=await sn($),!e.demo){let k=await Be(v);await p(dc(v,Ht),JSON.stringify(k,null," ")+`
|
|
1319
|
-
`),await ti(v,v)}await oi(v,$.aiTools),await Qo($,_),r.stop("Project files generated.")}catch(k){r.stop("Generation failed."),A.cancel(T(k)),process.exit(1)}!await ai(v)&&$.demo===!0&&(A.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let re=await si(v);re&&$.demo!==!0&&e.dbMigration!==!1&&await ci(v),await pi(v),re&&await li(v);let _e=Ke("docker"),qe=An($).map(k=>k.key).filter(k=>!$.credentials?.[k]);di($,{pnpmInstalled:re,dockerComposeGenerated:ne,dockerAvailable:_e,skippedCredentials:qe}),mr(),A.log.info(mc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as nr}from"fs";import{readFile as rr}from"fs/promises";import{join as gt,resolve as Ic}from"path";import*as P from"@clack/prompts";import J from"picocolors";import{mkdtemp as yc,rm as wc}from"fs/promises";import{tmpdir as vc}from"os";import{join as kc}from"path";async function er(e,t,n,r){let o=await yc(kc(vc(),"generatesaas-stage-"));try{await qt(e,t,o),await sn({...n,projectDir:o}),await Yn(o,r)}finally{await wc(o,{recursive:!0,force:!0})}}import{readFile as bc,rm as Sc}from"fs/promises";import{join as tr}from"path";var gi=tr(z,"companion-release.json"),Ec=["apps/companion/","packages/companion-protocol/","packages/agent-core-types/","packages/agent-core/","scripts/companion-export/"];async function hi(e){let t;try{t=await bc(tr(e,gi),"utf-8")}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&r.code==="ENOENT")return null;throw r}let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"version"in n&&typeof n.version=="string"&&n.version.length>0?{version:n.version}:null}async function yi(e){try{return await Sc(tr(e,gi)),!0}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function wi(e){return e.some(t=>Ec.some(n=>t.startsWith(n)))}function ki(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,n)=>{let r=t==="auto"?"auto":void 0,o=Ic(n.cwd??process.cwd()),i=gt(o,Ie),a;try{a=JSON.parse(await rr(i,"utf-8"))}catch{P.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s;try{s=await ot()}catch(l){P.cancel(T(l)),process.exit(1)}let u=ke(s),g=P.spinner();try{g.start("Verifying access...");let l;try{l=await Re(u)}catch(b){throw b instanceof F&&b.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):b}let h=ln(l,"update");if(!h.ok)throw new Error(h.message);g.stop("Access verified."),Me(s),g.start("Fetching latest skill files...");let y=await Dr(u,l.latest);await Zn(o,y.skillMd,y.scripts,a.aiTools);let _=Xn(a.aiTools);if(g.stop("Skills updated."),P.log.success(`Skill files installed to ${J.cyan(_.length.toString())} locations.`),a.version===l.latest){P.log.info(`Already on the latest version (${a.version}).`);return}let v=JSON.stringify(a);Ir(a),Ar(a),await Ac(a,Pr(a),r);let $=yr(a),ne=wr(a),Se=JSON.stringify(ne)!==v;if(a=ne,a.licenseToken)try{let b=await $r(u,{currentToken:a.licenseToken,newVersion:l.latest});a.licenseToken=b.token,b.licenseKeyHash&&(a.licenseKeyHash=b.licenseKeyHash),await p(i,JSON.stringify(a,null," ")+`
|
|
1320
|
-
`),
|
|
1321
|
-
`);let
|
|
1322
|
-
`)}if(
|
|
1323
|
-
`),
|
|
1324
|
-
`),
|
|
1325
|
-
|
|
1326
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1327
|
-
|
|
1328
|
-
${
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
`),
|
|
1333
|
-
`).
|
|
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";
|
|
1334
1289
|
`,` licenseHeartbeatFunction,
|
|
1335
1290
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1336
1291
|
`,` .route("/license", licenseRoutes)
|
|
1337
|
-
`]}];function
|
|
1338
|
-
`).filter(
|
|
1339
|
-
`);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",`
|
|
1340
1295
|
Examples:
|
|
1341
1296
|
$ generatesaas init Interactive setup
|
|
1342
1297
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1343
1298
|
$ generatesaas status Check for updates
|
|
1344
1299
|
$ generatesaas auth Set or update API key
|
|
1345
|
-
`);
|
|
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)});
|