generatesaas 1.23.1 → 2.0.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 +287 -383
- package/dist/skill/content/SKILL.md +36 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,15 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as ic}from"commander";import*as Ki from"@clack/prompts";import{existsSync as bs,readdirSync as ks,rmSync as ws}from"fs";import{join as Ss,resolve as Es}from"path";import{Option as Z}from"commander";import*as I from"@clack/prompts";import*as vt from"@clack/prompts";import Jt from"picocolors";function Un(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";vt.intro(Jt.bgYellow(Jt.black(t)))}function Mn(){vt.outro(Jt.yellow("Happy building!"))}import*as g from"@clack/prompts";import h from"picocolors";var nt={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},rt={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)"}},bt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},kt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},wt={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},$e={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}},it={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Ee={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 re={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}},J={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"}]}},ie={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"}]}},ot=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],at=[{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)."}],Vn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function St(e){let t=J[e.databaseProvider].managed,n=ie[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var se={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 Ae=["nextjs","nuxt"],je=["fullstack","separate"],Ue=["stripe","polar","none"],Me=["smtp","ses","resend"],Ve=["postgres","redis","inngest","mailpit"],Be=["claude-code","cursor","codex","gemini-cli","windsurf"],Fe=["user","organization"],ce=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],le=["node","vercel"],pe=["postgres","neon","supabase"],de=["redis","upstash"],Ke=["google","github","facebook","discord","x"];function Et(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Ge(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function At(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function Ie(e){let t=e?.trim();return t?`${Ge(t)} Companion`:"My Companion"}var Bn=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ae,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:je,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:le,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:de,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ue,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ce,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Me,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:Fe,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:"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/tauri, built with Tauri).",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:"desktopAi",label:"Desktop AI orchestration",hint:"Adds the desktop AI agents layer (requires the desktop app).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",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, knowledge base, and BYOK options. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config"},{key:"rag",label:"Server-side knowledge base",hint:"Adds a keyword knowledge base over your `knowledge/` docs.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companion",label:"Companion daemon",hint:"Vendors a brandable device companion your users install to run their own AI subscriptions (and any device-side work you add). You own it: source lives in this repo; one command publishes it to a public GitHub repo YOU own; releases and driver updates are your job; unsigned builds work out of the box (signing is optional and paid).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>Ie(e.projectName),adoptable:!0,impact:"config",requires:e=>e.companion===!0,requiresLabel:"requires the companion"},{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:"aiByok",label:"AI billing mode (BYOK)",hint:"BYOK: end-users bring their own provider key, no credit metering. Off: operator-keyed, credit-metered platform mode.",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=>e.paymentProvider!==void 0&&e.paymentProvider!=="none",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:Ke,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Ve,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:Be,adoptable:!1,impact:"config"}];function Hi(e,t){return e[t]!==void 0}function Fn(e){return Bn.filter(t=>t.adoptable&&!Hi(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 Kn(e){let t={};for(let n of Bn)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}}var Gn=["companion","mcpServer","rag"];function Wt(e){if(!Gn.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server / --rag require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Hn(e){return Gn.some(n=>e[n]===!0)&&(e.ai=!0),e}function zn(e){let t={};if(e.name!==void 0){if(!At(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(!Ae.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ae.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.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.desktopAi!==void 0){if(e.desktopAi===!0&&e.desktop!==!0)throw new Error("--desktop-ai requires --desktop to be enabled.");t.desktopAi=e.desktopAi}if(e.ai!==void 0&&(t.ai=e.ai),e.rag!==void 0&&(t.rag=e.rag),e.companion!==void 0&&(t.companion=e.companion),e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiByok!==void 0&&(t.aiByok=e.aiByok),Wt(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.docker!==void 0&&(t.dockerServices=qt(e.docker,Ve,"docker service")),e.aiTools!==void 0&&(t.aiTools=qt(e.aiTools,Be,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=qt(e.socialProviders,Ke,"social provider")),e.currency!==void 0){if(!ce.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ce.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!le.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${le.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!de.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${de.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 ue={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,desktopAi:!1,ai:!1,rag:!1,companion:!1,mcpServer:!1,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function Yn(e){let t=e.projectName??ue.projectName,n=e.projectDir??`./${t}`,r=e.appName??Ge(t),i=e.deploymentTarget??ue.deploymentTarget,o=re[i]?.edgeRuntime??!1,a=e.databaseProvider??(o?"neon":ue.databaseProvider),s=e.cacheProvider??(o?"upstash":ue.cacheProvider),d=e.emailProvider??(o?"resend":ue.emailProvider),m=e.dockerServices??(o?ue.dockerServices.filter(f=>f!=="postgres"&&f!=="redis"):ue.dockerServices),p={...ue,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:i,databaseProvider:a,cacheProvider:s,emailProvider:d,dockerServices:m};p.paymentProvider==="none"&&(p.credits=!1),p.multiTenancy||(p.billingScope="user"),p.ai||(p.aiByok=ue.aiByok),p.companion&&p.companionName===void 0&&(p.companionName=Ie(p.projectName));for(let f of ot){if(p.deploymentTarget!==f.target)continue;let S=p.databaseProvider===f.provider?"database":"cache";if(p.databaseProvider===f.provider||p.cacheProvider===f.provider)throw new Error(`Incompatible: --deploy ${f.target} + --${S} ${f.provider}. ${f.reason}`)}for(let f of at)if(p.architecture===f.architecture&&p.deploymentTarget===f.target)throw new Error(`Incompatible: --architecture ${f.architecture} + --deploy ${f.target}. ${f.reason}`);return p}function qt(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(o=>o.trim()).filter(Boolean),i=r.filter(o=>!t.includes(o));if(i.length>0)throw new Error(`Invalid ${n}(s): ${i.join(", ")}. Valid values: ${t.join(", ")}`);return r}function E(e){g.isCancel(e)&&(g.cancel("Setup cancelled."),process.exit(0))}function Xt(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=se[n];for(let i of r.envVars)t.push({key:i.name,message:`${i.name} (${r.label}, optional):`,secret:i.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Jn(e,t){let n=!1;e&&Wt(e),g.log.info(h.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await g.text({message:"Project name:",placeholder:"my-saas",validate:u=>{if(!u?.trim())return"Project name is required.";if(!At(u))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return E(c),c})(),i=e?.appName??await(async()=>{n=!0;let c=await g.text({message:"App name:",initialValue:Ge(r),validate:u=>{if(!u?.trim())return"App name is required."}});return E(c),c})(),o=e?.projectDir??await(async()=>{n=!0;let c=await g.text({message:"Project location:",initialValue:`./${r}`});return E(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(nt),u=await g.select({message:"Frontend framework:",options:c.map(k=>({value:k,label:nt[k].label,hint:nt[k].hint}))});return E(u),u})();g.log.info(h.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await g.select({message:"Deployment target:",options:le.map(u=>({value:u,label:re[u].label,hint:re[u].hint}))});E(c),s=c}let d=e?.architecture?at.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let m=new Set(at.filter(c=>c.target===s).map(c=>c.architecture)),p=je.filter(c=>!m.has(c)),f=e?.architecture??await(async()=>{if(p.length===1){let u=p[0];return g.log.info(`Auto-selected ${rt[u].label} architecture (only compatible option for ${re[s].label}).`),u}n=!0;let c=await g.select({message:"Architecture:",options:p.map(u=>({value:u,label:rt[u].label,hint:rt[u].hint}))});return E(c),c})(),S=e?.databaseProvider??await(async()=>{n=!0;let c=pe.filter(k=>!ot.some(G=>G.target===s&&G.provider===k));if(c.length===1){let k=c[0];return g.log.info(`Auto-selected ${J[k].label} (only compatible option for ${re[s].label}).`),k}let u=await g.select({message:"Database provider:",options:c.map(k=>({value:k,label:J[k].label,hint:J[k].hint}))});return E(u),u})(),b=e?.cacheProvider??await(async()=>{n=!0;let c=de.filter(k=>!ot.some(G=>G.target===s&&G.provider===k));if(c.length===1){let k=c[0];return g.log.info(`Auto-selected ${ie[k].label} (only compatible option for ${re[s].label}).`),k}let u=await g.select({message:"Cache provider:",options:c.map(k=>({value:k,label:ie[k].label,hint:ie[k].hint}))});return E(u),u})();if(re[s]?.edgeRuntime){let c=Vn.map(u=>` - ${u}`).join(`
|
|
3
|
-
`);
|
|
4
|
-
`),
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`))}
|
|
11
|
-
|
|
12
|
-
|
|
2
|
+
import{Command as zc}from"commander";import*as xi from"@clack/prompts";import{existsSync as ac,readdirSync as sc,rmSync as cc}from"fs";import{join as pc,resolve as lc}from"path";import{Option as ee}from"commander";import*as A from"@clack/prompts";import*as Nt from"@clack/prompts";import hn from"picocolors";function lr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Nt.intro(hn.bgYellow(hn.black(t)))}function dr(){Nt.outro(hn.yellow("Happy building!"))}import*as f from"@clack/prompts";import h from"picocolors";var ht={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},yt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},$t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Lt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Ut={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},qe={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}},wt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var 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 se={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}},X={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"}]}},ce={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},vt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],kt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ur=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function jt(e){let t=X[e.databaseProvider].managed,n=ce[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var ge={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"],Ye=["fullstack","separate"],We=["stripe","polar","none"],Xe=["smtp","ses","resend"],Ze=["postgres","redis","inngest","mailpit"],Qe=["claude-code","cursor","codex","gemini-cli","windsurf"],et=["user","organization"],he=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ye=["node","vercel"],we=["postgres","neon","supabase"],ve=["redis","upstash"],tt=["google","github","facebook","discord","x"],Le=["shared","vendored"];function Mt(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function nt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Vt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function T(e){return e instanceof Error?e.message:String(e)}function re(e){let t=e?.trim();return t?`${nt(t)} Companion`:"My Companion"}var Ue="https://github.com/Duzbee/OpenCompanion";function pe(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function mr(e){return e.desktop===!0&&e.ai===!0}function Z(e){if(mr(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 pe(e)}function Q(e){return mr(e)?!0:e.companion===!0&&pe(e)==="vendored"}function Ee(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var fr=[{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:Ye,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ye,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:we,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ve,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:We,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:he,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Xe,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:et,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"emailTracking",label:"Email analytics",hint:"Tracks opens and clicks of marketing emails and adds an admin analytics page.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config"},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, and BYOK options. On a desktop project it also ships the app's local AI stack and bundles a companion daemon inside the packaged app. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"companion",label:"Companion daemon",hint:"Lets your users install a companion daemon that runs their own AI subscriptions (and any device-side work you add) on their hardware. Point it at an existing shared companion like OpenCompanion (default, nothing to maintain), or vendor and publish your own branded daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionSource",label:"Companion source",hint:"Point at an existing shared companion repo (like OpenCompanion), or vendor a branded daemon you own and publish yourself.",category:"Features",kind:"enum",default:e=>Z(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&&pe(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&&pe(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=>re(e.projectName),adoptable:!0,impact:"config",requires:e=>Q(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:tt,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Ze,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:Qe,adoptable:!1,impact:"config"}];function _i(e,t){return e[t]!==void 0}function gr(e){return fr.filter(t=>t.adoptable&&!_i(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 hr(e){let t={};for(let n of fr)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 wn}from"fs/promises";import{join as yr}from"path";var yn="GENERATESAAS_COMPANION_BRAND_JSON",Ft=["daemon/brand.json","apps/companion/brand.json"];function le(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 wr(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function Bt(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 Oi(e,t){let n=yr(e,"apps/companion/brand.json"),r;try{r=await wn(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=le(o)}catch{return null}return wr(i,t)?Bt(r,`the template (${n})`):null}async function Ci(e,t){for(let n of Ft){let r=yr(e,n),o;try{o=await wn(r,"utf8")}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;throw s}let i=Bt(o,r),a=JSON.parse(o).repoUrl;if(typeof a=="string"&&a.trim()!==""){let s;try{s=le(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(!wr(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 ${Ft.join(" and ")}). Point --companion-local-path at a checkout of the companion repo, or remove it to fetch the identity from GitHub.`)}async function Di(e){for(let t of Ft){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 Bt(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Ft.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function vr(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=le(t),r=await Oi(e.projectDir,n);if(r)return r;let o=e.companionLocalPath?.trim();if(o)return await Ci(o,n);let i=process.env[yn]?.trim();if(i){let a;try{a=await wn(i,"utf8")}catch(s){throw new Error(`Could not read ${yn} (${i}): ${T(s)}.`)}return Bt(a,`${yn} (${i})`)}return await Di(n)}var kr=["companion","mcpServer"];function kn(e){if(!kr.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 br(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 bn(e){if(!br(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 Sr(e){return kr.some(n=>e[n]===!0)&&(e.ai=!0),e}function Er(e){return e.ai!==!0||(e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1),Ee(e)||(e.aiBuiltin=!1),br(e)||(e.aiByok=!0)),e}function Ir(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=Ni(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&Sn(e),n}function Sn(e){return Q(e)&&(e.companionSource=Z(e),e.companionName===void 0&&(e.companionName=re(e.projectName))),e}function Ni(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 Ar(e){let t={};if(e.name!==void 0){if(!Vt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.frontend!==void 0){if(!$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=le(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),kn(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=vn(e.docker,Ze,"docker service")),e.aiTools!==void 0&&(t.aiTools=vn(e.aiTools,Qe,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=vn(e.socialProviders,tt,"social provider")),e.currency!==void 0){if(!he.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${he.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ye.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ye.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!we.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${we.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ve.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ve.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 de={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 Pr(e){let t=e.projectName??de.projectName,n=e.projectDir??`./${t}`,r=e.appName??nt(t),o=e.deploymentTarget??de.deploymentTarget,i=se[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":de.databaseProvider),s=e.cacheProvider??(i?"upstash":de.cacheProvider),u=e.emailProvider??(i?"resend":de.emailProvider),g=e.dockerServices??(i?de.dockerServices.filter(m=>m!=="postgres"&&m!=="redis"):de.dockerServices),l={...de,...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=de.aiBuiltin,l.aiByok=de.aiByok),l.paymentProvider==="none"&&(l.aiBuiltin=!1),l.desktop&&l.ai&&(l.companionSource=Z(l)),Q(l)&&l.companionName===void 0&&(l.companionName=re(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=pe(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=re(l.projectName)):(l.companionRepoUrl===void 0&&(l.companionRepoUrl=Ue),l.companionLocalPath===void 0&&(l.companionLocalPath=""))),bn(l);for(let m of vt){if(l.deploymentTarget!==m.target)continue;let w=l.databaseProvider===m.provider?"database":"cache";if(l.databaseProvider===m.provider||l.cacheProvider===m.provider)throw new Error(`Incompatible: --deploy ${m.target} + --${w} ${m.provider}. ${m.reason}`)}for(let m of kt)if(l.architecture===m.architecture&&l.deploymentTarget===m.target)throw new Error(`Incompatible: --architecture ${m.architecture} + --deploy ${m.target}. ${m.reason}`);return l}function vn(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(i=>i.trim()).filter(Boolean),o=r.filter(i=>!t.includes(i));if(o.length>0)throw new Error(`Invalid ${n}(s): ${o.join(", ")}. Valid values: ${t.join(", ")}`);return r}function S(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function En(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=ge[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 Rr(e,t){let n=!1;e&&kn(e),f.log.info(h.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Vt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await f.text({message:"App name:",initialValue:nt(r),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await f.text({message:"Project location:",initialValue:`./${r}`});return S(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(ht),d=await f.select({message:"Frontend framework:",options:c.map(b=>({value:b,label:ht[b].label,hint:ht[b].hint}))});return S(d),d})();f.log.info(h.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await f.select({message:"Deployment target:",options:ye.map(d=>({value:d,label:se[d].label,hint:se[d].hint}))});S(c),s=c}let u=e?.architecture?kt.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(u)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);let g=new Set(kt.filter(c=>c.target===s).map(c=>c.architecture)),l=Ye.filter(c=>!g.has(c)),m=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return f.log.info(`Auto-selected ${yt[d].label} architecture (only compatible option for ${se[s].label}).`),d}n=!0;let c=await f.select({message:"Architecture:",options:l.map(d=>({value:d,label:yt[d].label,hint:yt[d].hint}))});return S(c),c})(),w=e?.databaseProvider??await(async()=>{n=!0;let c=we.filter(b=>!vt.some(H=>H.target===s&&H.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${X[b].label} (only compatible option for ${se[s].label}).`),b}let d=await f.select({message:"Database provider:",options:c.map(b=>({value:b,label:X[b].label,hint:X[b].hint}))});return S(d),d})(),v=e?.cacheProvider??await(async()=>{n=!0;let c=ve.filter(b=>!vt.some(H=>H.target===s&&H.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${ce[b].label} (only compatible option for ${se[s].label}).`),b}let d=await f.select({message:"Cache provider:",options:c.map(b=>({value:b,label:ce[b].label,hint:ce[b].hint}))});return S(d),d})();if(se[s]?.edgeRuntime){let c=ur.map(d=>` - ${d}`).join(`
|
|
3
|
+
`);f.note(c,"Unavailable on edge runtime")}f.log.info(h.bold("Features"));let x=e?.paymentProvider??await(async()=>{n=!0;let c=await f.select({message:"Payment provider:",options:We.map(d=>({value:d,label:$t[d].label,hint:$t[d].hint}))});return S(c),c})(),Y=e?.defaultCurrency??await(async()=>{if(x==="none")return"USD";n=!0;let c=await f.select({message:"Default currency:",options:he.map(d=>({value:d,label:d,hint:Ne[d].name}))});return S(c),c})(),ne=e?.emailProvider??await(async()=>{n=!0;let c=await f.select({message:"Email provider:",options:Xe.map(d=>({value:d,label:Lt[d].label,hint:Lt[d].hint}))});return S(c),c})(),fe=e?.multiTenancy??await(async()=>{n=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return S(c),c})(),_e=fe?e?.billingScope??"user":"user";if(fe&&e?.billingScope===void 0){n=!0;let c=await f.select({message:"Billing scope:",options:et.map(d=>({value:d,label:Ut[d].label,hint:Ut[d].hint}))});S(c),_e=c}let Oe=e?.blog??await(async()=>{n=!0;let c=await f.confirm({message:"Enable blog?",initialValue:!0});return S(c),c})(),E=e?.emailTracking??await(async()=>{n=!0;let c=await f.confirm({message:"Enable email analytics? (open/click tracking + admin analytics page)",initialValue:!0});return S(c),c})(),M=e?.docs??await(async()=>{n=!0;let c=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return S(c),c})(),W=t?.desktopAllowed!==!1,j=e?.desktop??(W?await(async()=>{n=!0;let c=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 and bundles its own companion daemon.",initialValue:!1});return S(c),c})():(f.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),K=j?e?.desktopAutoRelease??await(async()=>{n=!0;let c=await f.select({message:"Desktop release trigger:",options:[{value:!1,label:"Manual only",hint:"run from the Actions tab (saves CI minutes)"},{value:!0,label:"Automatic",hint:"release on every CI success on main"}],initialValue:!1});return S(c),c})():!1,L=e?.ai??await(async()=>{n=!0;let c=await f.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion + MCP server)",initialValue:!1});return S(c),c})(),k=L?e?.companion??await(async()=>{n=!0;let c=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 S(c),c})():!1,B=j&&L,Ce=B?Z({desktop:j,ai:L,companion:k,companionSource:e?.companionSource,companionName:e?.companionName}):k?e?.companionSource??await(async()=>{n=!0;let c=await f.select({message:"Companion source:",options:[{value:"shared",label:"Shared companion",hint:"point at an existing companion repo (OpenCompanion by default) - nothing to publish or maintain"},{value:"vendored",label:"Vendored companion",hint:"own a branded daemon: source in this repo, published to your own GitHub repo"}],initialValue:"shared"});return S(c),c})():void 0;B&&f.log.info(h.dim("Companion source: your desktop app bundles its own daemon, so it is vendored into this repo. Nothing to publish - it ships inside the app."));let ln=Ce!=="shared"?void 0:e?.companionRepoUrl??await(async()=>{n=!0;let c=await f.text({message:"Companion repo URL (GitHub):",initialValue:Ue,validate:d=>{if(!d?.trim())return"A companion repo URL is required for a shared companion.";try{le(d)}catch(b){return T(b)}}});return S(c),le(c).canonicalUrl})(),ir=Ce!=="shared"?void 0:e?.companionLocalPath??await(async()=>{n=!0;let c=await f.text({message:"Path to your local checkout of this companion (leave empty otherwise):",placeholder:"only if you develop the companion alongside this project",defaultValue:""});return S(c),c.trim()})(),Ot=Ce!=="vendored"?void 0:e?.companionName??await(async()=>{n=!0;let c=await f.text({message:B&&!k?"Companion name (your app's bundled daemon - names its binary, service and data folder):":"Companion name (what your users install):",initialValue:re(r),validate:d=>{if(!d?.trim())return"Companion name is required."}});return S(c),c})(),ar=L?e?.mcpServer??await(async()=>{n=!0;let c=await f.confirm({message:"Add the outward MCP server? Lets external agents (Claude Code, Codex, Hermes, OpenClaw) control the app on a user's behalf over an authenticated MCP endpoint.",initialValue:!1});return S(c),c})():!1,dn=x==="none"?!1:L?e?.aiBuiltin??await(async()=>{n=!0;let c=await f.confirm({message:"Built-in AI? (models under your app's name via OpenRouter, billed from user credits)",initialValue:!0});return S(c),c})():!0,un=L?e?.aiByok??await(async()=>{n=!0;let c=await f.confirm({message:"Allow users to bring their own API keys? (their runs never use credits)",initialValue:!0});return S(c),c})():!0;bn({ai:L,aiBuiltin:dn,aiByok:un,companion:k,desktop:j,paymentProvider:x});let sr=e?.revenueSharing??await(async()=>{n=!0;let c=await f.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return S(c),c})(),cr=x==="none"?!1:e?.credits??await(async()=>{n=!0;let c=await f.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return S(c),c})(),Ct=e?.socialProviders??await(async()=>{n=!0;let c=tt.map(b=>({value:b,label:ge[b].label,hint:`requires ${ge[b].envVars.map(H=>H.name).join(" / ")}`})),d=await f.multiselect({message:"Which social login providers should the sign-in screen show?",options:c,initialValues:[],required:!1});return S(d),d})();f.log.info(h.bold("Tooling"));let mn=e?.dockerServices??await(async()=>{n=!0;let c=[...Ze].filter(z=>z!=="mailpit");ne==="smtp"&&c.push("mailpit");let d=c.map(z=>({value:z,label:qe[z].label,hint:qe[z].hint})),b=d.map(z=>z.value).filter(z=>!(z==="postgres"&&(w==="neon"||w==="supabase")||z==="redis"&&v==="upstash")),H=await f.multiselect({message:"Which services should we set up in Docker for you?",options:d,initialValues:b,required:!1});return S(H),H})(),fn=e?.aiTools??await(async()=>{n=!0;let c=Qe.map(b=>({value:b,label:wt[b].label})),d=await f.multiselect({message:"Which AI coding tools do you use?",options:c,initialValues:[],required:!1});return S(d),d})(),gn=e?.demo,Dt=En({databaseProvider:w,cacheProvider:v,paymentProvider:x,emailProvider:ne,socialProviders:Ct,demo:gn}),gt={};if(Dt.length>0&&n){f.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Dt)if(n=!0,c.secret){let d=await f.password({message:c.message,mask:"*"});S(d),typeof d=="string"&&d.trim()&&(gt[c.key]=d.trim())}else{let d=await f.text({message:c.message,placeholder:c.placeholder});S(d),typeof d=="string"&&d.trim()&&(gt[c.key]=d.trim())}}if(n){let c=[` Name: ${h.cyan(r)}`,` App name: ${h.cyan(o)}`,` Location: ${h.cyan(i)}`,` Frontend: ${h.cyan(ht[a].label)}`,` Architecture: ${h.cyan(yt[m].label)}`].join(`
|
|
4
|
+
`),d=[` Deploy target: ${h.cyan(se[s]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(X[w].label)}`,` Cache: ${h.cyan(ce[v].label)}`,mn.length>0?` Docker: ${h.cyan(mn.map(De=>qe[De].label).join(", "))}`:` Docker: ${h.dim("none")}`].filter(Boolean).join(`
|
|
5
|
+
`),b=[x!=="none"?` Payment: ${h.cyan($t[x].label)} (${Y})`:` Payment: ${h.dim("none")}`,` Credits: ${cr?h.cyan("Yes"):h.dim("No")}`,` AI features: ${L?h.cyan("Yes"):h.dim("No")}`,...L?[` AI sources: ${h.cyan([dn?"Built-in (credits)":null,un?"User keys":null].filter(Boolean).join(" + ")||"none")}`,` Companion: ${k?h.cyan("Yes"):h.dim("No")}`,...k?[` Comp. source: ${h.cyan(Ce==="shared"?"Shared":"Vendored")}`,Ce==="shared"?` Comp. repo: ${h.cyan(ln??"")}`:` Comp. name: ${h.cyan(Ot??"")}`]:[],` MCP server: ${ar?h.cyan("Yes"):h.dim("No")}`]:[],` Email: ${h.cyan(Lt[ne].label)}`,` Email stats: ${E?h.cyan("Yes"):h.dim("No")}`,` Multi-tenancy: ${fe?h.cyan("Yes")+` (billing: ${Ut[_e].label})`:h.dim("No")}`,` Blog: ${Oe?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${M?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${j?h.cyan("Yes"):h.dim("No")}`,...j?[` Releases: ${h.cyan(K?"Automatic on CI":"Manual only")}`]:[],...B&&!k?[` Desktop AI: ${h.cyan("Yes")} (bundles ${Ot??""})`]:[],` Rev. sharing: ${sr?h.cyan("Yes"):h.dim("No")}`,Ct.length>0?` Social login: ${h.cyan(Ct.map(De=>ge[De].label).join(", "))}`:` Social login: ${h.dim("none")}`,fn.length>0?` AI tools: ${h.cyan(fn.map(De=>wt[De].label).join(", "))}`:` AI tools: ${h.dim("none")}`].join(`
|
|
6
|
+
`),H=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),b];if(Dt.length>0){let De=Dt.map(pr=>{let Ti=gt[pr.key]?h.green("provided"):h.dim("skipped");return` ${pr.key}: ${Ti}`}).join(`
|
|
7
|
+
`);H.push("",h.bold("Credentials"),De)}f.note(H.join(`
|
|
8
|
+
`),"Summary");let z=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(z)||!z)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:r,appName:o,projectDir:i,frontend:a,architecture:m,deploymentTarget:s,databaseProvider:w,cacheProvider:v,paymentProvider:x,emailProvider:ne,multiTenancy:fe,billingScope:_e,blog:Oe,emailTracking:E,docs:M,desktop:j,desktopAutoRelease:K,ai:L,companion:k,...Ot!==void 0?{companionName:Ot}:{},...Ce!==void 0?{companionSource:Ce}:{},...ln!==void 0?{companionRepoUrl:ln}:{},...ir!==void 0?{companionLocalPath:ir}:{},mcpServer:ar,aiBuiltin:dn,aiByok:un,revenueSharing:sr,credits:cr,dockerServices:mn,aiTools:fn,socialProviders:Ct,defaultCurrency:Y,...Object.keys(gt).length>0?{credentials:gt}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...gn!==void 0?{demo:gn}:{}}}import{createReadStream as $r,existsSync as zi}from"fs";import{mkdir as Ji}from"fs/promises";import{join as qi}from"path";import{Readable as Yi}from"stream";import{pipeline as _n}from"stream/promises";import{extract as Wi}from"tar";import{join as je}from"path";import{homedir as $i}from"os";var bt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",J=".generatesaas",Ie=je(J,"manifest.json"),xr=je(J,"hashes.json"),Gt=je(J,"template-hashes.json"),Kt=je(J,"template"),Tr=je(J,"staging"),_r=je(J,"staging.json"),ke=je($i(),".generatesaas");var V=class extends Error{constructor(n,r,o){super(r);this.status=n;this.body=o}status;body;name="ApiError"};function be(e){return{apiKey:e,baseUrl:bt}}async function Ae(e,t,n){let r=`${e.baseUrl}${t}`,o=await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/2.0.0"}});if(!o.ok){let i,a;try{a=await o.json(),i=a.error??`API ${o.status}: ${t}`}catch{i=`API ${o.status}: ${t}`}throw new V(o.status,i,a)}return o}import{existsSync as Li,readFileSync as Ui,writeFileSync as ji,mkdirSync as Mi}from"fs";import{dirname as Vi}from"path";import*as Pe from"@clack/prompts";function St(){if(!Li(ke))return null;try{let e=JSON.parse(Ui(ke,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Pe.log.warning(`Found old GitHub token in ${ke}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Me(e){Mi(Vi(ke),{recursive:!0}),ji(ke,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function rt(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=St();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 Fi}from"fs/promises";async function Re(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Fi(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await Ae(e,"/versions")).json()}async function In(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Ae(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(n){if(n instanceof V&&n.status===404)return null;throw n}}async function Or(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await Ae(e,`/skill/${encodeURIComponent(t)}`)).json()}function Ht(e){if(!(e instanceof V)||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 Cr(e){return{frontend:e.frontend,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,credits:e.credits,revenueSharing:e.revenueSharing,socialProviders:e.socialProviders,aiTools:e.aiTools,currency:e.defaultCurrency}}async function An(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Ae(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Dr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Ae(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Pn(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 Nr(e,t,n){let r=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});if(!r.ok){let o=await r.json().catch(()=>null);throw new Error(o?.error??`Inspect endpoint returned ${r.status}`)}return await r.json()}var Rn=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),xn=new Set(["pnpm-lock.yaml"]);function ot(e){if(Tn(e))return!0;for(let t of e.split("/"))if(xn.has(t))return!0;return!1}var Bi=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","README.md","TODO.md","OVERVIEW.md"]),Gi=["scripts/docs-lint.ts"],Ki=["scripts/companion-export/"],Hi=["docs/superpowers","packages/cli","packages/cli-api","docs/opencompanion","infra/docker-compose.yml",".claude/commands",".claude/skills/web-next-port",".claude/skills/web-next-port-workspace",".claude/settings.local.json",".claude/worktrees"];function Tn(e){let t=e.split("/");for(let n of t)if(Rn.has(n))return!0;if(Gi.includes(e))return!1;for(let n of Ki)if(e.startsWith(n)||`${e}/`===n)return!1;if(Bi.has(t[0]))return!0;for(let n of Hi)if(e===n||e.startsWith(n+"/"))return!0;return!1}async function zt(e,t,n){await Ji(n,{recursive:!0});let r=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(r){let s=qi(r,`v${t}.tar.gz`);if(!zi(s))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${s} does not exist.`);await _n($r(s),On(n));return}let o=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(o){await _n($r(o),On(n));return}let i=await Ae(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let a=Yi.fromWeb(i.body);await _n(a,On(n))}function On(e){return Wi({cwd:e,strip:1,filter:t=>{let n=t.replace(/^[^/]+\//,"");return n?!Tn(n):!0},sync:!1})}import{readdir as aa,readFile as At,rm as Dn,writeFile as Pt}from"fs/promises";import{join as Se}from"path";import{readFile as It,rm as Lr}from"fs/promises";import{join as xe}from"path";import{mkdir as Xi,readdir as Zi,rm as Qi,rmdir as ea,writeFile as ta}from"fs/promises";import{dirname as Jt,join as na,relative as ra,sep as oa}from"path";function Ve(e){return e.split(oa).join("/")}async function qt(e){await Xi(e,{recursive:!0})}async function p(e,t){await qt(Jt(e)),await ta(e,t,"utf-8")}async function Cn(e,t){await Qi(e,{force:!0});let n=Jt(e);for(;n!==t&&n!==Jt(n);){try{await ea(n)}catch{return}n=Jt(n)}}async function Fe(e,t,n){let r=[],o=await Zi(e,{withFileTypes:!0});for(let i of o){let a=na(e,i.name),s=Ve(ra(t,a));n(s)||(i.isDirectory()?r.push(...await Fe(a,t,n)):i.isFile()&&r.push(a))}return r}function ia(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function O(e,t,n="ai",r="stripDesktopAi"){let o=ia(n);if(e.match(o)===null)throw new Error(`${r}: expected gsaas ${n} markers in ${t}, but found none (boilerplate drift).`);let i=e.replace(o,"");if(i.includes(`gsaas:${n}-start`)||i.includes(`gsaas:${n}-end`))throw new Error(`${r}: an unbalanced gsaas ${n} marker is left in ${t} (boilerplate drift).`);return i.replace(/\n{3,}/g,`
|
|
11
|
+
|
|
12
|
+
`)}async function I(e,t,n,r,o){let i=await It(e,"utf-8"),a=i.indexOf(t);if(a===-1)throw new Error(`${o}: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(i.indexOf(t,a+t.length)!==-1)throw new Error(`${o}: the ${r} seam appears more than once (boilerplate drift).`);await p(e,i.slice(0,a)+n+i.slice(a+t.length))}async function Yt(e,t,n,r){let o=/\n([\t ]+)"/.exec(await It(e,"utf-8"))?.[1];if(o!==n){let i=a=>a===" "?"tab":`${a.length}-space`;throw new Error(`${r}: expected ${e} to be ${i(n)}-indented, but it is ${o===void 0?"not indented":i(o)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await p(e,`${JSON.stringify(t,null,n)}
|
|
13
|
+
`)}function Wt(e,t,n,r){if(!(t in e))throw new Error(`${r}: expected ${n} (boilerplate drift).`);delete e[t]}function it(e){return e.frontend==="nextjs"?"next":"nuxt"}async function Ur(e,t,n,r,o,i){let a=xe(e,"docs",t);await Lr(xe(a,`${n}.mdx`)),await I(xe(a,"meta.json"),` "${n}",
|
|
14
|
+
`,"",`${t} meta.json ${n} nav entry`,o),await jr(a,t,r,o),i!==void 0&&await Mr(a,t,i,o)}async function jr(e,t,n,r){let o=xe(e,"ai.mdx"),a=(await It(o,"utf-8")).split(`
|
|
15
|
+
`).find(s=>s.includes(`href="${n}"`));if(a===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${n} (boilerplate drift).`);await I(o,`${a}
|
|
16
|
+
`,"",`${t} ai.mdx ${n} card`,r)}async function Mr(e,t,n,r){let o=xe(e,"ai.mdx"),i=`| **${n}** |`,s=(await It(o,"utf-8")).split(`
|
|
17
|
+
`).find(u=>u.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${n}" hub-table row (boilerplate drift).`);await I(o,`${s}
|
|
18
|
+
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function Vr(e,t,n,r,o,i){let a=xe(e,"docs",t);await Lr(xe(a,n),{recursive:!0}),await I(xe(a,"meta.json"),` "${n}",
|
|
19
|
+
`,"",`${t} meta.json ${n} nav entry`,o);for(let s of r)await jr(a,t,s,o);i!==void 0&&await Mr(a,t,i,o)}async function Xt(e){let t=`import { config } from "@repo/config";
|
|
20
|
+
`,n=await It(e,"utf-8");if(!n.includes(t))return;let r=n.replace(t,""),o=r.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(o)||await p(e,r)}var sa=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function Br(e){await Promise.all(sa.map(t=>Dn(Se(e,t),{recursive:!0,force:!0})))}var ca=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function Gr(e){let t="removeDesktopDemoScreen";await Dn(Se(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let n of ca){let r=Se(e,n);await Pt(r,O(await At(r,"utf-8"),n,"demo",t))}}var pa="packages/config/src/blog.ts";async function Kr(e){let t=Se(e,pa),n=await At(t,"utf-8"),r=Fr(Fr(n,"blogCategories",t),"blogAuthors",t);await Pt(t,r)}function Fr(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 Hr(e){let t=Se(e,"packages/i18n/translations"),n;try{n=await aa(t)}catch{return}for(let r of n){let o=Se(t,r,"web.json"),i;try{i=await At(o,"utf-8")}catch{continue}let a=JSON.parse(i);!a.blog||a.blog.categories===void 0||(a.blog.categories={},await Pt(o,JSON.stringify(a,null," ")+`
|
|
21
|
+
`))}}var la="packages/config/src/ai/tasks.ts";async function zr(e){let t=Se(e,la),n=await At(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 Pt(t,r)}async function Jr(e,t){t.includes("claude-code")||await Dn(Se(e,".claude"),{recursive:!0,force:!0})}async function qr(e,t){let n=Se(e,".claude","settings.json"),r;try{r=await At(n,"utf8")}catch{return}let o=JSON.parse(r);delete o.alwaysThinkingEnabled,delete o.enableAllProjectMcpServers,o.env&&(delete o.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(o.env).length===0&&delete o.env),o.permissions?.allow&&(o.permissions.allow=o.permissions.allow.filter(i=>da(i,t))),await Pt(n,JSON.stringify(o,null," ")+`
|
|
22
|
+
`)}function da(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as Yr}from"path";var ua={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},ma={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},fa={redis:"Redis",upstash:"Upstash Redis"},ga={node:"Node.js / Docker",vercel:"Vercel"},ha={stripe:"Stripe",polar:"Polar"};function ya(e){let t=e.frontend==="nuxt",n=t?"Nuxt 4":"Next.js 16",r=t?"apps/web-nuxt":"apps/web-next",o=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",i=e.architecture==="fullstack",a=i?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",s=i?`Mounted inside \`${r}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",u=fa[e.cacheProvider],g=ga[e.deploymentTarget],l=e.paymentProvider==="none"?"":`
|
|
23
|
+
- **Payments:** ${ha[e.paymentProvider]}`,m=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",w="";e.companion&&(pe(e)==="vendored"?w=`
|
|
24
|
+
- \`apps/companion\` - the source of **${e.companionName??re(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?w=`
|
|
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).`:w=`
|
|
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 v=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`.",x=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
|
|
13
27
|
|
|
14
28
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
15
29
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -37,11 +51,11 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
37
51
|
|
|
38
52
|
- **Frontend:** ${n} ${a}
|
|
39
53
|
- **API:** Hono, RPC-typed. ${s}
|
|
40
|
-
- **Database:** Drizzle ORM + ${
|
|
41
|
-
- **Cache + jobs:** ${
|
|
42
|
-
- **Auth:** Better Auth${
|
|
43
|
-
- **Email:** ${
|
|
44
|
-
- **Deploy:** ${
|
|
54
|
+
- **Database:** Drizzle ORM + ${ua[e.databaseProvider]}
|
|
55
|
+
- **Cache + jobs:** ${u} + Inngest
|
|
56
|
+
- **Auth:** Better Auth${l}
|
|
57
|
+
- **Email:** ${ma[e.emailProvider]}
|
|
58
|
+
- **Deploy:** ${g}
|
|
45
59
|
|
|
46
60
|
## Where things live (extend these - don't reinvent)
|
|
47
61
|
|
|
@@ -51,12 +65,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
51
65
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
52
66
|
- \`packages/runtime/src/env.ts\` - the validated (Zod) env schema. New env var \u2192 add it here **and** to \`.env.example\` (the committed reference); set the local value in \`.env\`.
|
|
53
67
|
- \`packages/{payments,mail,sms,storage,notifications}\` - config-gated integrations. Every provider's files stay even when its feature is off, so flipping a flag is enough to enable it.
|
|
54
|
-
- \`${r}\` - the ${n} app (${
|
|
55
|
-
- \`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/\`${
|
|
56
|
-
|
|
57
|
-
## Knowledge
|
|
58
|
-
|
|
59
|
-
\`knowledge/\` is the product knowledge that grounds the AI: read-only markdown entries, confidential, never user-facing - injected into the model's context so it answers from your facts. When you add or maintain an entry, FOLLOW THE RULES in \`knowledge/AGENTS.md\` (one concept per entry, frontmatter, \`[[wikilinks]]\`) and run \`pnpm knowledge:lint\` to validate. \`pnpm knowledge:build\` seeds the web knowledge base (gated by \`config.rag.enabled\`); the desktop app self-indexes its bundled copy. See \`docs/${t?"nuxt":"next"}/knowledge.mdx\`.
|
|
68
|
+
- \`${r}\` - the ${n} app (${o}).${w}
|
|
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/\`${m}.
|
|
60
70
|
|
|
61
71
|
## Code style
|
|
62
72
|
|
|
@@ -73,8 +83,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
73
83
|
|
|
74
84
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
75
85
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
76
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${
|
|
77
|
-
- ${
|
|
86
|
+
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${v} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
87
|
+
- ${x}
|
|
78
88
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
79
89
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
80
90
|
|
|
@@ -85,14 +95,14 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
85
95
|
## This project
|
|
86
96
|
|
|
87
97
|
Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
|
|
88
|
-
`}async function
|
|
89
|
-
`)}import{join as
|
|
98
|
+
`}async function Wr(e){await p(Yr(e.projectDir,"AGENTS.md"),ya(e)),await p(Yr(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
99
|
+
`)}import{join as wa}from"path";var va={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ka(e){let t=e.appName.trim()||e.projectName,n=e.frontend==="nuxt",r=n?"Nuxt 4":"Next.js 16",o=n?"apps/web-nuxt":"apps/web-next",i=va[e.databaseProvider],a=jt(e),s=e.architecture==="fullstack"?`${r} app at \`${o}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${r} app at \`${o}/\` and a separate Hono backend at \`apps/backend/\`.`,u=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
90
100
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
91
101
|
- API: http://localhost:3010
|
|
92
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
93
|
-
`:"",
|
|
102
|
+
- Inngest dev server: http://127.0.0.1:8288`,g=a?`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
103
|
+
`:"",l=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":`### Deployment
|
|
94
104
|
|
|
95
|
-
This project ships with Dockerfiles for each app. Build images with \`docker build\` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).${a?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,
|
|
105
|
+
This project ships with Dockerfiles for each app. Build images with \`docker build\` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).${a?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,m=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}
|
|
96
106
|
|
|
97
107
|
${s}
|
|
98
108
|
|
|
@@ -101,7 +111,7 @@ ${s}
|
|
|
101
111
|
- **Frontend:** ${r}
|
|
102
112
|
- **Backend:** Hono (TypeScript, RPC-typed)
|
|
103
113
|
- **Auth:** Better Auth
|
|
104
|
-
- **ORM / DB:** Drizzle + ${
|
|
114
|
+
- **ORM / DB:** Drizzle + ${i}
|
|
105
115
|
- **Background jobs:** Inngest
|
|
106
116
|
- **i18n:** ${n?"@nuxtjs/i18n":"next-intl"}
|
|
107
117
|
|
|
@@ -112,11 +122,11 @@ pnpm install
|
|
|
112
122
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
113
123
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
114
124
|
# reference. All apps load the single root \`.env\`.
|
|
115
|
-
${
|
|
125
|
+
${g}pnpm db:setup # first run: create the database schema (idempotent)
|
|
116
126
|
pnpm dev
|
|
117
127
|
\`\`\`
|
|
118
128
|
|
|
119
|
-
${
|
|
129
|
+
${u}
|
|
120
130
|
|
|
121
131
|
## Build your SaaS
|
|
122
132
|
|
|
@@ -136,7 +146,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
|
|
|
136
146
|
pnpm auth:generate # regenerate Better Auth schema after config changes
|
|
137
147
|
\`\`\`
|
|
138
148
|
|
|
139
|
-
${
|
|
149
|
+
${l}
|
|
140
150
|
|
|
141
151
|
## Removing the GenerateSaaS license
|
|
142
152
|
|
|
@@ -148,16 +158,21 @@ pnpm dlx generatesaas eject
|
|
|
148
158
|
|
|
149
159
|
## Updates
|
|
150
160
|
|
|
151
|
-
${
|
|
152
|
-
`}async function
|
|
153
|
-
`)}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
161
|
+
${m}
|
|
162
|
+
`}async function Xr(e){await p(wa(e.projectDir,"README.md"),ka(e))}import{access as Sa,readFile as Ea}from"fs/promises";import{join as at}from"path";import{join as ba}from"path";function Nn(e,t){let n=Mt(e,"companion"),r=t?new URL(t).hostname.split(".").reverse().join("."):"com",o=n.toUpperCase().replace(/-/g,"_");return{name:e,binary:n,scope:`@${n}`,serviceLabel:`${r}.${n}`,appDirName:n,envPrefix:/^[0-9]/.test(o)?`_${o}`:o,docsUrl:"",repoUrl:"",installBase:""}}async function Zr(e){if(!Q(e)||e.demo||Z(e)==="shared")return;if(!e.companionName)throw new Error("generateCompanionBrand: this project ships a companion daemon but options.companionName is missing.");let t=Nn(e.companionName,e.baseUrl);await p(ba(e.projectDir,"apps/companion/brand.json"),JSON.stringify(t,null,2)+`
|
|
163
|
+
`)}async function Ia(e,t,n){let r=at(e,"apps/electron/dev-app-update.yml");try{await Sa(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await p(r,`provider: generic
|
|
164
|
+
url: ${t}
|
|
165
|
+
updaterCacheDirName: ${n}
|
|
166
|
+
`)}function Aa(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Pa(e,t){let n=Mt(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${n.replace(/-/g,"")}`,productName:e,protocol:n}}async function Ra(e){if(!e.companion&&!Q(e))return'{ enabled: false, clientId: "companion" }';let t;if(e.demo)t=JSON.parse(await Ea(at(e.projectDir,"apps/companion/brand.json"),"utf8"));else if(Z(e)==="shared"){let r=await vr(e),o=le(e.companionRepoUrl??"").canonicalUrl;t={name:r.name,binary:r.binary,envPrefix:r.envPrefix,repoUrl:o,installBase:`${o}/releases/latest/download`}}else{if(!e.companionName)throw new Error("generateConfig: this project ships a companion daemon but options.companionName is missing.");t=Nn(e.companionName,e.baseUrl)}let n={name:t.name,binary:t.binary,envPrefix:t.envPrefix,repoUrl:t.repoUrl,installBase:t.installBase};return["{",` enabled: ${e.companion},`,' clientId: "companion",'," daemon: {",` name: ${JSON.stringify(n.name)},`,` binary: ${JSON.stringify(n.binary)},`,` envPrefix: ${JSON.stringify(n.envPrefix)},`,` repoUrl: ${JSON.stringify(n.repoUrl)},`,` installBase: ${JSON.stringify(n.installBase)}`," }"," }"].join(`
|
|
167
|
+
`)}async function Qr(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=e.paymentProvider!=="none",r=e.baseUrl??"http://localhost:3000",o=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",i=Aa(o),a=e.demo?"false":"true",s=e.demo?`{
|
|
168
|
+
enableInDev: true,
|
|
169
|
+
chatwoot: {
|
|
170
|
+
baseUrl: "https://support.alexchelan.com",
|
|
171
|
+
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
172
|
+
}
|
|
173
|
+
}`:"{}",u=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",g=Pa(t,i),l=`https://cdn.${i}/desktop`,m=await Ra(e),w=`{ enabled: ${e.mcpServer} }`,v=`import type { AppConfig } from "@repo/config/types";
|
|
160
174
|
import { desktopConfig } from "./desktop.mjs";
|
|
175
|
+
import { supportConfig } from "./support.mjs";
|
|
161
176
|
import { tenancyConfig } from "./tenancy-flags.mjs";
|
|
162
177
|
|
|
163
178
|
const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean);
|
|
@@ -165,7 +180,7 @@ const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim
|
|
|
165
180
|
export const config: AppConfig = {
|
|
166
181
|
siteName: "${t}",
|
|
167
182
|
fullSiteName: "${t}",
|
|
168
|
-
domain: "${
|
|
183
|
+
domain: "${o}",
|
|
169
184
|
baseUrl: process.env.BASE_URL ?? "${r}",
|
|
170
185
|
indexable: ${a},
|
|
171
186
|
logo: {
|
|
@@ -192,20 +207,24 @@ export const config: AppConfig = {
|
|
|
192
207
|
limitPerSecond: 3,
|
|
193
208
|
senders: {
|
|
194
209
|
transactional: {
|
|
195
|
-
email: "noreply@${
|
|
210
|
+
email: "noreply@${i}",
|
|
196
211
|
senderName: "${t}"
|
|
197
212
|
},
|
|
198
213
|
marketing: {
|
|
199
|
-
email: "hello@${
|
|
214
|
+
email: "hello@${i}",
|
|
200
215
|
senderName: "${t}",
|
|
201
216
|
signatureName: "Alex"
|
|
202
217
|
},
|
|
203
218
|
support: {
|
|
204
|
-
email: "support@${
|
|
219
|
+
email: "support@${i}",
|
|
205
220
|
senderName: "${t} Support"
|
|
206
221
|
}
|
|
207
222
|
},
|
|
208
|
-
inactiveEmailSchedule: [7, 30, 90]
|
|
223
|
+
inactiveEmailSchedule: [7, 30, 90],
|
|
224
|
+
tracking: {
|
|
225
|
+
enabled: ${e.emailTracking},
|
|
226
|
+
retentionDays: 90
|
|
227
|
+
}
|
|
209
228
|
},
|
|
210
229
|
storage: {
|
|
211
230
|
enabled: true,
|
|
@@ -225,7 +244,7 @@ export const config: AppConfig = {
|
|
|
225
244
|
prefix: "key_"
|
|
226
245
|
},
|
|
227
246
|
apiDocs: true,
|
|
228
|
-
performanceMonitor: { enabled: ${
|
|
247
|
+
performanceMonitor: { enabled: ${u} },
|
|
229
248
|
notifications: {
|
|
230
249
|
enabled: true,
|
|
231
250
|
maxPerUser: 100,
|
|
@@ -243,7 +262,8 @@ export const config: AppConfig = {
|
|
|
243
262
|
enabled: true,
|
|
244
263
|
provider: "turnstile",
|
|
245
264
|
siteKey: "0x4AAAAAACJo9y9FxH8lqkGu"
|
|
246
|
-
}`:"{ enabled: false }"}
|
|
265
|
+
}`:"{ enabled: false }"},
|
|
266
|
+
support: supportConfig,
|
|
247
267
|
currency: ${e.demo?`{
|
|
248
268
|
// Demo mirrors the boilerplate's showcase config so geo\u2192currency
|
|
249
269
|
// switching can be demonstrated. Real users get a single-currency
|
|
@@ -263,7 +283,7 @@ export const config: AppConfig = {
|
|
|
263
283
|
}`:`{
|
|
264
284
|
base: "${e.defaultCurrency}",
|
|
265
285
|
list: [
|
|
266
|
-
{ symbol: "${
|
|
286
|
+
{ symbol: "${Ne[e.defaultCurrency].symbol}", name: "${Ne[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Ne[e.defaultCurrency].place}", space: ${Ne[e.defaultCurrency].space} }
|
|
267
287
|
],
|
|
268
288
|
countryMap: {
|
|
269
289
|
default: "${e.defaultCurrency}"
|
|
@@ -287,33 +307,33 @@ export const config: AppConfig = {
|
|
|
287
307
|
},
|
|
288
308
|
ai: {
|
|
289
309
|
enabled: ${e.ai},
|
|
290
|
-
// AI
|
|
291
|
-
//
|
|
292
|
-
|
|
310
|
+
// Built-in AI: your app offers models under its OWN name, billed from user credits.
|
|
311
|
+
// Powered by OpenRouter - set OPENROUTER_API_KEY in your env, that is the whole setup.
|
|
312
|
+
builtin: ${e.aiBuiltin},
|
|
313
|
+
// Let users connect their own provider API keys; runs on their key never use credits.
|
|
293
314
|
byok: ${e.aiByok},
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
// NOT maintained by the boilerplate.
|
|
298
|
-
"claude-opus-4-8": {
|
|
299
|
-
provider: "anthropic",
|
|
300
|
-
modelId: "claude-opus-4-8",
|
|
301
|
-
inputPerMTok: 5,
|
|
302
|
-
outputPerMTok: 25
|
|
303
|
-
}
|
|
304
|
-
},
|
|
305
|
-
credits: { creditsPerUsd: 100, margin: 1, fallbackRatePerMTok: { input: 5, output: 25 } },
|
|
315
|
+
// What every user starts on (their own choice, once made, always wins). Plain
|
|
316
|
+
// OpenRouter model ids.
|
|
317
|
+
defaults: { model: "anthropic/claude-opus-4.8" },
|
|
306
318
|
// Let end-users author their own AI schedules. Set to false to ship only the
|
|
307
319
|
// create-disabled view (existing schedules still list/run/edit/delete).
|
|
308
|
-
userSchedules: true
|
|
320
|
+
userSchedules: true,
|
|
321
|
+
// Server-side chat thread limits: at most \`cap\` stored threads per user (chat history lives in
|
|
322
|
+
// Mastra Memory threads; the server evicts the oldest-by-activity beyond the cap).
|
|
323
|
+
chats: {
|
|
324
|
+
cap: 20
|
|
325
|
+
},
|
|
326
|
+
// \`/chat\` page presentation. \`suggestions\` are prompt-starter chips shown on the empty chat;
|
|
327
|
+
// empty by default (starters are product copy you write for your users).
|
|
328
|
+
chat: {
|
|
329
|
+
suggestions: []
|
|
330
|
+
}
|
|
309
331
|
},
|
|
310
332
|
desktop: desktopConfig,
|
|
311
|
-
// Server-side keyword knowledge base over your knowledge/ docs. Off by default.
|
|
312
|
-
rag: ${p},
|
|
313
333
|
// Companion: your vendored companion daemon (apps/companion) that your users install to run their own subscription CLIs. Off by default.
|
|
314
|
-
companion: ${
|
|
334
|
+
companion: ${m},
|
|
315
335
|
// Outward MCP server exposing the capability layer to external agents. Off by default.
|
|
316
|
-
mcpServer: ${
|
|
336
|
+
mcpServer: ${w},
|
|
317
337
|
seo: {
|
|
318
338
|
description: "Production-ready SaaS application",
|
|
319
339
|
foundingDate: "${new Date().getFullYear()}-01-01"
|
|
@@ -326,6 +346,12 @@ export const config: AppConfig = {
|
|
|
326
346
|
pricing: "/pricing",
|
|
327
347
|
onboarding: "/onboarding",
|
|
328
348
|
settings: "/settings/profile",
|
|
349
|
+
chat: "/chat",
|
|
350
|
+
schedules: "/schedules",
|
|
351
|
+
settingsModels: "/settings/models",
|
|
352
|
+
settingsIntegrations: "/settings/integrations",
|
|
353
|
+
settingsCompanions: "/settings/companions",
|
|
354
|
+
settingsMcp: "/settings/mcp",
|
|
329
355
|
notifications: "/notifications",
|
|
330
356
|
admin: "/admin/users"
|
|
331
357
|
}
|
|
@@ -343,35 +369,36 @@ export * from "./companion";
|
|
|
343
369
|
export * from "./footer";
|
|
344
370
|
export * from "./i18n";
|
|
345
371
|
export * from "./landing";
|
|
372
|
+
export * from "./nav-active";
|
|
346
373
|
export * from "./pricing";
|
|
347
374
|
export * from "./roles";
|
|
348
375
|
export * from "./section-tabs";
|
|
349
376
|
export * from "./tenancy";
|
|
350
|
-
`,
|
|
351
|
-
// TypeScript config index reads it directly: the
|
|
352
|
-
//
|
|
353
|
-
//
|
|
354
|
-
//
|
|
355
|
-
// index re-exports this as config.desktop.
|
|
377
|
+
`,x=at(e.projectDir,"packages/config/src/index.ts");await p(x,v),await p(at(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
378
|
+
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
379
|
+
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
380
|
+
// values once to rebrand - they are the same in dev and production, so they live in
|
|
381
|
+
// committed config, not env. The config index re-exports this as config.desktop.
|
|
356
382
|
|
|
357
383
|
export const desktopConfig = {
|
|
358
384
|
enabled: ${e.desktop},
|
|
359
|
-
appId: "${
|
|
360
|
-
productName: "${
|
|
361
|
-
protocol: "${
|
|
385
|
+
appId: "${g.appId}",
|
|
386
|
+
productName: "${g.productName}",
|
|
387
|
+
protocol: "${g.protocol}",
|
|
362
388
|
baseUrl: "${r}",
|
|
363
389
|
// Name of the app's data folder (created under the OS app-data dir). Where the app
|
|
364
390
|
// and its AI agents persist files - logs, gathered data, generated artifacts. Rename
|
|
365
391
|
// it freely; it is a plain folder name, not a path.
|
|
366
392
|
dataFolder: "data",
|
|
367
|
-
// Public base URL the release workflow uploads to;
|
|
368
|
-
// \`<url>/latest.
|
|
369
|
-
|
|
393
|
+
// Public base URL the release workflow uploads to; electron-updater polls
|
|
394
|
+
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
395
|
+
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
396
|
+
autoUpdate: { url: "${l}" },
|
|
370
397
|
agents: {
|
|
371
|
-
// Feature toggles only. Agents
|
|
372
|
-
// through the @repo/agent-
|
|
373
|
-
// markdown prompt files you tune.
|
|
374
|
-
enabled: ${e.
|
|
398
|
+
// Feature toggles only. Agents run in the app's main process (companion supervision +
|
|
399
|
+
// the daemon transport bridge), driven through the @repo/agent-core seam - typed
|
|
400
|
+
// TypeScript wiring next to the markdown prompt files you tune.
|
|
401
|
+
enabled: ${e.desktop&&e.ai},
|
|
375
402
|
modelRegistry: { enabled: true },
|
|
376
403
|
// Provider ids that ship in this app (catalog ids like "anthropic", "openai").
|
|
377
404
|
// Omitted here, which ships them ALL; add \`providers: ["anthropic", ...]\` to trim
|
|
@@ -386,11 +413,16 @@ export const desktopConfig = {
|
|
|
386
413
|
userSchedules: true,
|
|
387
414
|
// Cap how many chat conversations are kept per agent on the user's machine;
|
|
388
415
|
// creating a new chat past this limit deletes the oldest. Set to 0 for no limit.
|
|
389
|
-
maxChatsPerAgent: 20
|
|
416
|
+
maxChatsPerAgent: 20,
|
|
417
|
+
// Forbid the bundled companion daemon from connecting to your backend (the buyer
|
|
418
|
+
// connection lock). Default false: the app is local-first and connecting is an
|
|
419
|
+
// OPTIONAL, explicit user action. Set true for a structurally private product - the
|
|
420
|
+
// connect surface never renders AND the daemon refuses pairing.
|
|
421
|
+
connectionLock: false
|
|
390
422
|
}
|
|
391
423
|
};
|
|
392
|
-
`),await
|
|
393
|
-
// TypeScript config index reads it directly (the
|
|
424
|
+
`),await p(at(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
|
|
425
|
+
// TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
|
|
394
426
|
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
395
427
|
|
|
396
428
|
export const tenancyConfig = ${e.multiTenancy?`{
|
|
@@ -398,8 +430,14 @@ export const tenancyConfig = ${e.multiTenancy?`{
|
|
|
398
430
|
organizationLimit: 5,
|
|
399
431
|
billingScope: "${e.billingScope}"
|
|
400
432
|
}`:"{ multiTenant: false }"};
|
|
401
|
-
`),
|
|
402
|
-
|
|
433
|
+
`),await p(at(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
|
|
434
|
+
// the TypeScript config index reads it directly (the Electron main + renderer and
|
|
435
|
+
// the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
|
|
436
|
+
// index re-exports this as config.support.
|
|
437
|
+
|
|
438
|
+
export const supportConfig = ${s};
|
|
439
|
+
`),e.desktop&&await Ia(e.projectDir,l,`${g.protocol}-updater`)}import{join as xa}from"path";function Ta(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function $n(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxSchedules!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxSchedules: ${e.maxSchedules}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
|
|
440
|
+
`)}async function eo(e){let t=xa(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let v=`import type { PricingConfig } from "@repo/config/types";
|
|
403
441
|
|
|
404
442
|
export const pricingConfig: PricingConfig = {
|
|
405
443
|
defaultPlan: "free",
|
|
@@ -428,7 +466,21 @@ export const pricingConfig: PricingConfig = {
|
|
|
428
466
|
credits: { enabled: false },
|
|
429
467
|
products: { enabled: false, items: [] }
|
|
430
468
|
};
|
|
431
|
-
`;await
|
|
469
|
+
`;await p(t,v);return}let r=e.paymentProvider,o=Ta(r),i=e.credits,a=!!e.ai,s=$n({credits:5,rateLimit:100,withCredits:i,...a&&{maxSchedules:3}}),u=$n({credits:10,rateLimit:1e3,withCredits:i,...a&&{maxSchedules:10}}),g=$n({credits:50,rateLimit:5e3,withCredits:i}),l=n==="USD"?"":` // !! ${n} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
470
|
+
// !! USD), but your plan prices and credit purchases are denominated in ${n}. Verify that the
|
|
471
|
+
// !! ${n} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
472
|
+
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
473
|
+
`;i&&n!=="USD"&&console.warn(`
|
|
474
|
+
!! ${n} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
475
|
+
!! plan prices and credit purchases are denominated in ${n}. At the shipped economics 1 credit
|
|
476
|
+
!! carries ~0.42 USD of AI cost - verify every ${n} price still covers it (see the comment on the
|
|
477
|
+
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
478
|
+
`);let m=i?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
479
|
+
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
480
|
+
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
481
|
+
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
482
|
+
// full utilization runs you at a loss.
|
|
483
|
+
${l} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",w=`import type { PricingConfig } from "@repo/config/types";
|
|
432
484
|
|
|
433
485
|
export const pricingConfig: PricingConfig = {
|
|
434
486
|
defaultPlan: "free",
|
|
@@ -452,7 +504,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
452
504
|
amounts: { ${n}: 0 }
|
|
453
505
|
}
|
|
454
506
|
],
|
|
455
|
-
${
|
|
507
|
+
${s}
|
|
456
508
|
},
|
|
457
509
|
{
|
|
458
510
|
id: "starter",
|
|
@@ -467,18 +519,18 @@ ${a}
|
|
|
467
519
|
],
|
|
468
520
|
prices: [
|
|
469
521
|
{
|
|
470
|
-
${
|
|
522
|
+
${o}
|
|
471
523
|
interval: "month",
|
|
472
524
|
amounts: { ${n}: 9 }
|
|
473
525
|
},
|
|
474
526
|
{
|
|
475
|
-
${
|
|
527
|
+
${o}
|
|
476
528
|
interval: "year",
|
|
477
529
|
amounts: { ${n}: 90 },
|
|
478
530
|
anchorAmounts: { ${n}: 109 }
|
|
479
531
|
}
|
|
480
532
|
],
|
|
481
|
-
${
|
|
533
|
+
${u}
|
|
482
534
|
},
|
|
483
535
|
{
|
|
484
536
|
id: "pro",
|
|
@@ -496,33 +548,33 @@ ${s}
|
|
|
496
548
|
],
|
|
497
549
|
prices: [
|
|
498
550
|
{
|
|
499
|
-
${
|
|
551
|
+
${o}
|
|
500
552
|
interval: "month",
|
|
501
553
|
amounts: { ${n}: 29 },
|
|
502
554
|
anchorAmounts: { ${n}: 39 },
|
|
503
555
|
featured: true
|
|
504
556
|
},
|
|
505
557
|
{
|
|
506
|
-
${
|
|
558
|
+
${o}
|
|
507
559
|
interval: "year",
|
|
508
560
|
amounts: { ${n}: 290 },
|
|
509
561
|
anchorAmounts: { ${n}: 349 }
|
|
510
562
|
}
|
|
511
563
|
],
|
|
512
|
-
${
|
|
564
|
+
${g}
|
|
513
565
|
}
|
|
514
566
|
],
|
|
515
|
-
${
|
|
567
|
+
${m},
|
|
516
568
|
products: {
|
|
517
569
|
enabled: false,
|
|
518
570
|
items: []
|
|
519
571
|
}
|
|
520
572
|
};
|
|
521
|
-
`;await
|
|
522
|
-
`)}function
|
|
523
|
-
`)}async function
|
|
524
|
-
`+
|
|
525
|
-
`+
|
|
573
|
+
`;await p(t,w)}var _a={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]};function Oa(e){let t=ge[e];return t.envVars.map((n,r)=>({key:n.name,...r===0?{comment:`# TODO: Add your ${t.label} OAuth credentials`}:{}}))}var Ca={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 st(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 Ln(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function no(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function Da(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 Zt(e,t,n,r){e.push(r==="example"?`${t}=`:`${t}=${n}`)}function to(e,t){let n=t==="example"?void 0:e.credentials,{apiUrl:r,baseUrl:o}=no(e),i=[];e.architecture==="separate"?i.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${r}`,`BASE_URL=${o}`):i.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${o}`),i.push("","# Database"),ct(st(X[e.databaseProvider].envVars,n),i),i.push("","# Cache"),ct(st(ce[e.cacheProvider].envVars,n),i),i.push("","# Authentication"),t==="example"&&i.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Zt(i,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),i.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Zt(i,"CONTENT_API_KEY",Ln(32),t),i.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Zt(i,"INNGEST_EVENT_KEY",Ln(32),t),Zt(i,"INNGEST_SIGNING_KEY",Ln(32),t),i.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(i.push("","# API Port (standalone backend)","API_PORT=3010"),i.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let a=_a[e.emailProvider];if(a&&(i.push("","# Email"),ct(st(a,n),i)),e.paymentProvider!=="none"){let s=Ca[e.paymentProvider];s&&(i.push("","# Payment"),ct(st(s,n),i))}if(e.socialProviders.length>0){i.push("","# Social auth");for(let s of e.socialProviders)ct(st(Oa(s),n),i)}return e.demo&&(i.push("","# Captcha (Cloudflare Turnstile)"),ct(st([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],n),i)),i.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY="),i.push("","# AI base - provider API keys (optional)","# Enable config.ai in packages/config and set the key for your chosen provider.","# OPENROUTER_API_KEY above also works as an AI provider key.","#ANTHROPIC_API_KEY=","#OPENAI_API_KEY="),i.push(""),i.join(`
|
|
574
|
+
`)}function Na(e){let{apiUrl:t}=no(e),n=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",r=["# API Configuration",`${n}=${t}`],o=Da(e);return o&&e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${n}=${o.backend}`),r.push(""),r.join(`
|
|
575
|
+
`)}async function ro(e){let t=Na(e);await p(`${e.projectDir}/.env`,t+`
|
|
576
|
+
`+to(e,"env")),await p(`${e.projectDir}/.env.example`,t+`
|
|
577
|
+
`+to(e,"example"))}import{join as $a}from"path";async function oo(e){let t=[...e.dockerServices];if(X[e.databaseProvider].managed&&(t=t.filter(i=>i!=="postgres")),ce[e.cacheProvider].managed&&(t=t.filter(i=>i!=="redis")),t.length===0)return!1;let n=[],r=[];t.includes("postgres")&&(n.push(` postgres:
|
|
526
578
|
image: postgres:18-alpine
|
|
527
579
|
ports:
|
|
528
580
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -558,16 +610,16 @@ ${o?" credits: { enabled: true }":" credits: { enabled: false }"},
|
|
|
558
610
|
image: inngest/inngest:v1.17.4
|
|
559
611
|
ports:
|
|
560
612
|
- "\${INNGEST_PORT:-8288}:8288"
|
|
561
|
-
command: inngest dev`);let
|
|
613
|
+
command: inngest dev`);let o=`services:
|
|
562
614
|
${n.join(`
|
|
563
615
|
|
|
564
616
|
`)}
|
|
565
|
-
`;return r.length>0&&(
|
|
617
|
+
`;return r.length>0&&(o+=`
|
|
566
618
|
volumes:
|
|
567
619
|
${r.join(`
|
|
568
620
|
`)}
|
|
569
|
-
`),await
|
|
570
|
-
`)}import{join as
|
|
621
|
+
`),await p($a(e.projectDir,"infra/docker-compose.yml"),o),!0}import{join as La}from"path";function Ua(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 ja(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 io(e){let t={version:"0.2.0",configurations:Ua(e),compounds:ja(e)};await p(La(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
622
|
+
`)}import{join as Ma}from"path";async function ao(e){if(e.architecture!=="separate")return;await p(Ma(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
|
|
571
623
|
import app from "@repo/api";
|
|
572
624
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
573
625
|
|
|
@@ -598,12 +650,12 @@ bootstrap().catch((error) => {
|
|
|
598
650
|
logger.error("[Backend] Fatal error", error);
|
|
599
651
|
process.exit(1);
|
|
600
652
|
});
|
|
601
|
-
`)}import{readFile as
|
|
602
|
-
export const pool = db.$client;`,
|
|
653
|
+
`)}import{readFile as Va}from"fs/promises";import{join as Fa}from"path";var Un='import { drizzle } from "drizzle-orm/node-postgres";',jn=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
654
|
+
export const pool = db.$client;`,Ba={postgres:{importLine:Un,instantiation:jn},neon:{importLine:`import { neon } from "@neondatabase/serverless";
|
|
603
655
|
import { drizzle } from "drizzle-orm/neon-http";`,instantiation:`const sql = neon(parsed.data.DATABASE_URL);
|
|
604
656
|
export const db = drizzle(sql, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
605
657
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
606
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
658
|
+
export const db = drizzle(client, { schema });`}};async function so(e){let t=Fa(e.projectDir,"packages/database/src/index.ts"),n=await Va(t,"utf-8");if(!n.includes(Un)||!n.includes(jn))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=Ba[e.databaseProvider],o=n.replace(Un,r.importLine).replace(jn,r.instantiation);await p(t,o)}import{join as Qt}from"path";async function co(e){switch(e.cacheProvider){case"redis":await Ga(e),await Ka(e);break;case"upstash":await Ha(e),await za(e);break}}async function Ga(e){await p(Qt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
607
659
|
import { Redis } from "ioredis";
|
|
608
660
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
609
661
|
import { env } from "./env";
|
|
@@ -732,7 +784,7 @@ export async function closeRedis() {
|
|
|
732
784
|
closed = true;
|
|
733
785
|
}
|
|
734
786
|
}
|
|
735
|
-
`)}async function
|
|
787
|
+
`)}async function Ka(e){await p(Qt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
736
788
|
import { redis } from "./redis";
|
|
737
789
|
|
|
738
790
|
export class MutexTimeoutError extends Error {
|
|
@@ -769,7 +821,7 @@ export async function withMutex<T>(
|
|
|
769
821
|
await mutex.release();
|
|
770
822
|
}
|
|
771
823
|
}
|
|
772
|
-
`)}async function
|
|
824
|
+
`)}async function Ha(e){await p(Qt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
773
825
|
import type { Store } from "hono-rate-limiter";
|
|
774
826
|
import { env } from "./env";
|
|
775
827
|
|
|
@@ -887,7 +939,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
887
939
|
|
|
888
940
|
/** No persistent connection to close with Upstash REST. */
|
|
889
941
|
export async function closeRedis(): Promise<void> {}
|
|
890
|
-
`)}async function
|
|
942
|
+
`)}async function za(e){await p(Qt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
891
943
|
import { redis } from "./redis";
|
|
892
944
|
|
|
893
945
|
export class MutexTimeoutError extends Error {
|
|
@@ -932,7 +984,7 @@ export async function withMutex<T>(
|
|
|
932
984
|
await lock.release();
|
|
933
985
|
}
|
|
934
986
|
}
|
|
935
|
-
`)}async function
|
|
987
|
+
`)}async function po(e){await p(`${e.projectDir}/packages/runtime/src/env.ts`,Ja(e))}function Ja(e){return`import { z } from "zod";
|
|
936
988
|
|
|
937
989
|
const EnvSchema = z.object({
|
|
938
990
|
NODE_ENV: z.enum(["development", "production"]).default("development"),
|
|
@@ -943,6 +995,7 @@ const EnvSchema = z.object({
|
|
|
943
995
|
TRUSTED_ORIGINS: z.string().optional(),
|
|
944
996
|
AUTH_COOKIE_DOMAIN: z.string().optional(),
|
|
945
997
|
|
|
998
|
+
DATABASE_URL: z.url(),
|
|
946
999
|
${e.cacheProvider==="upstash"?` UPSTASH_REDIS_REST_URL: z.string(),
|
|
947
1000
|
UPSTASH_REDIS_REST_TOKEN: z.string(),`:" REDIS_URL: z.string(),"}
|
|
948
1001
|
|
|
@@ -1026,7 +1079,9 @@ ${e.cacheProvider==="upstash"?` UPSTASH_REDIS_REST_URL: z.string(),
|
|
|
1026
1079
|
|
|
1027
1080
|
ANTHROPIC_API_KEY: z.string().optional(),
|
|
1028
1081
|
OPENAI_API_KEY: z.string().optional(),
|
|
1029
|
-
OPENROUTER_API_KEY: z.string().optional()
|
|
1082
|
+
OPENROUTER_API_KEY: z.string().optional(),
|
|
1083
|
+
|
|
1084
|
+
MASTRA_TELEMETRY_DISABLED: z.string().optional()
|
|
1030
1085
|
});
|
|
1031
1086
|
|
|
1032
1087
|
export const env = (() => {
|
|
@@ -1053,13 +1108,13 @@ export const env = (() => {
|
|
|
1053
1108
|
const parsedApiUrl = new URL(env.API_URL);
|
|
1054
1109
|
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1055
1110
|
export const apiOrigin = parsedApiUrl.origin;
|
|
1056
|
-
`}import{readFile as
|
|
1057
|
-
`)}function
|
|
1058
|
-
`)}var
|
|
1059
|
-
`))}}import{readFile as
|
|
1060
|
-
`);let
|
|
1111
|
+
`}import{readFile as qa}from"fs/promises";import{join as ue}from"path";var en={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function lt(e){let t=await qa(e,"utf-8");return JSON.parse(t)}async function dt(e,t){await p(e,JSON.stringify(t,null," ")+`
|
|
1112
|
+
`)}function Rt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function pt(e,t,n,r=!1){let o=r?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=n}async function lo(e){await Ya(e),await Wa(e),await Xa(e),await Za(e),e.frontend==="nextjs"?await es(e):await Qa(e)}async function Ya(e){let t=ue(e.projectDir,"packages/api/package.json"),n=await lt(t);Rt(n,["sharp","@types/sharp"]),await dt(t,n)}async function Wa(e){let t=ue(e.projectDir,"packages/runtime/package.json"),n=await lt(t);e.cacheProvider==="upstash"&&(Rt(n,["ioredis","rate-limit-redis","redis-semaphore"]),pt(n,"@upstash/redis",en["@upstash/redis"]),pt(n,"@upstash/lock",en["@upstash/lock"])),await dt(t,n)}async function Xa(e){let t=ue(e.projectDir,"packages/database/package.json"),n=await lt(t);e.databaseProvider==="neon"?(Rt(n,["pg","@types/pg"]),pt(n,"@neondatabase/serverless",en["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Rt(n,["pg","@types/pg"]),pt(n,"postgres",en.postgres)),await dt(t,n)}async function Za(e){if(e.architecture!=="separate")return;let t=ue(e.projectDir,"apps/backend/package.json"),n=await lt(t);e.deploymentTarget!=="node"&&Rt(n,["@hono/node-server"]),await dt(t,n)}async function Qa(e){if(e.architecture!=="separate")return;let t=ue(e.projectDir,"apps/web-nuxt");await Cn(ue(t,"server/api/[...paths].ts"),t);let n=ue(t,"package.json"),r=await lt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],pt(r,"@repo/api",o,!0)),await dt(n,r)}async function es(e){if(e.architecture!=="separate")return;let t=ue(e.projectDir,"apps/web-next");await Cn(ue(t,"app/api/[[...rest]]/route.ts"),t);let n=ue(t,"package.json"),r=await lt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],pt(r,"@repo/api",o,!0)),await dt(n,r)}import{readFile as mo}from"fs/promises";import{join as fo}from"path";async function go(e){let t=fo(e.projectDir,"turbo.json"),n;try{n=await mo(t,"utf-8")}catch{return}let r=JSON.parse(n),o=r.tasks?.build;if(!o)return;let i=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",a=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),s=!1;if(Array.isArray(o.env)){let u=o.env.filter(g=>g!==i);u.length!==o.env.length&&(o.env=u,s=!0)}if(Array.isArray(o.outputs)){let u=o.outputs.filter(g=>!a.has(g));u.length!==o.outputs.length&&(o.outputs=u,s=!0)}s&&await p(t,JSON.stringify(r,null," ")+`
|
|
1113
|
+
`)}var ts=["base.json","node.json","next.json"],uo="GenerateSaaS ";async function ho(e){if(!e.demo)for(let t of ts){let n=fo(e.projectDir,"tooling/typescript",t),r;try{r=await mo(n,"utf-8")}catch{continue}let o=JSON.parse(r);typeof o.display!="string"||!o.display.startsWith(uo)||(o.display=o.display.slice(uo.length),await p(n,JSON.stringify(o,null," ")+`
|
|
1114
|
+
`))}}import{readFile as ns,rm as rs}from"fs/promises";import{existsSync as yo}from"fs";import{join as wo}from"path";async function vo(e){if(e.frontend==="nuxt")return;let t=wo(e.projectDir,"packages/i18n/package.json");if(!yo(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await ns(t,"utf-8")),r=!!(n.exports?.["./module"]??n.exports?.["./nuxt"]),o=!1;if(n.exports)for(let a of["./module","./nuxt"])a in n.exports&&(delete n.exports[a],o=!0);n.devDependencies&&"@nuxt/kit"in n.devDependencies&&(delete n.devDependencies["@nuxt/kit"],o=!0),o&&await p(t,JSON.stringify(n,null," ")+`
|
|
1115
|
+
`);let i=wo(e.projectDir,"packages/i18n/nuxt");if(r&&!yo(i))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${i} is missing - did the i18n Nuxt module move?`);await rs(i,{recursive:!0,force:!0})}import{readFile as bo,rm as os}from"fs/promises";import{join as tn}from"path";async function So(e){e.cacheProvider==="upstash"&&await Promise.all([ko(tn(e.projectDir,"packages/runtime/tests/setup.ts")),ko(tn(e.projectDir,"packages/mail/tests/setup.ts")),is(e.projectDir),os(tn(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function ko(e){let t;try{t=await bo(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",
|
|
1061
1116
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1062
|
-
`);
|
|
1117
|
+
`);n!==t&&await p(e,n)}async function is(e){let t=tn(e,"packages/api/tests/setup.ts"),n;try{n=await bo(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",
|
|
1063
1118
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1064
1119
|
`),r=r.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1065
1120
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1080,253 +1135,100 @@ vi.mock("@upstash/lock", () => {
|
|
|
1080
1135
|
return { Lock };
|
|
1081
1136
|
});
|
|
1082
1137
|
|
|
1083
|
-
$1`),r!==n&&await
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1138
|
+
$1`),r!==n&&await p(t,r)}import{readdir as Kn,readFile as U,rm as N}from"fs/promises";import{join as y}from"path";import{readFile as Eo,readdir as as,rm as Te}from"fs/promises";import{join as F}from"path";async function Mn(e){if(e.mcpServer)return;let t=e.projectDir,n="stripMcpServer";await Te(F(t,"packages/api/src/routes/internal/ai/mcp.ts")),await Te(F(t,"packages/api/tests/routes/mcp.test.ts")),await Te(F(t,"packages/auth/src/mcp.ts"));let r=e.frontend==="nextjs",o=F(t,r?"apps/web-next/app/.well-known":"apps/web-nuxt/server/routes/.well-known");await Te(F(o,"oauth-authorization-server"),{recursive:!0}),await Te(F(o,"oauth-protected-resource"),{recursive:!0}),r||(await Te(F(o,"oauth-authorization-server.ts")),await Te(F(o,"oauth-protected-resource.ts"))),(await as(o)).length===0&&await Te(o,{recursive:!0});let i=F(t,"packages/api/src/routes/internal/index.ts");await I(i,`import mcpRoutes from "./ai/mcp";
|
|
1139
|
+
`,"","internal router mcp import",n),await I(i,'\n// Outward MCP server: the protected `/mcp` JSON-RPC endpoint, gated on `config.mcpServer`. Off by\n// default, so the route is absent entirely when disabled. Its OAuth `.well-known` discovery is NOT\n// here: agents resolve those documents against the site origin, so they mount at the app root (see\n// `mcpDiscoveryRoutes` in `src/index.ts`). It is not chained into the typed router above: external\n// agents (not the typed RPC client) call it, so it needs no `AppType` inference, and gating it\n// keeps the feature truly inert when off.\nif (config.mcpServer?.enabled) {\n app.route("/", mcpRoutes);\n}\n',"","internal router mcp mount",n),await Xt(i);let a=F(t,"packages/api/src/index.ts");await I(a,`import { mcpDiscoveryRoutes } from "./routes/internal/ai/mcp";
|
|
1140
|
+
`,"","api index mcp discovery import",n),await I(a,`
|
|
1141
|
+
// The outward MCP server's OAuth discovery documents, mounted at the APP ROOT (not under the API
|
|
1142
|
+
// base path): an MCP agent resolves \`/.well-known/oauth-*\` against the site origin (RFC 8414 /
|
|
1143
|
+
// RFC 9728). A standalone backend serves them at its origin directly, and each web frontend
|
|
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=F(t,"packages/auth/src/config.ts");await I(s,` magicLink,
|
|
1093
1150
|
mcp,
|
|
1094
1151
|
organization,`,` magicLink,
|
|
1095
|
-
organization,`,"auth config mcp plugin import",n),await
|
|
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
|
|
1096
1153
|
// external agent (Hermes/OpenClaw) can authenticate and drive the app's
|
|
1097
1154
|
// capability layer over MCP. Brings the oauthApplication/oauthAccessToken/
|
|
1098
1155
|
// oauthConsent tables (run \`pnpm auth:generate\` after toggling).
|
|
1099
1156
|
...(config.mcpServer?.enabled
|
|
1100
1157
|
? [mcp({ loginPage: \`\${config.baseUrl}\${config.routes.auth}/login\` })]
|
|
1101
1158
|
: []),
|
|
1102
|
-
`,"","auth config mcp plugin block",n);let
|
|
1103
|
-
`);let
|
|
1104
|
-
`);let
|
|
1105
|
-
|
|
1106
|
-
`,"","settings-store.ts relay import",t),await x(i," * - COMPANION (when `config.companion.enabled`): a well-formed companion key\n * `<connectionId>@<deviceId>@<modelId>` is also accepted, so a default/fallback model that points\n * at a paired CLI persists (the run path resolves it, and the daemon handles an offline device).\n * Without this, the `@`-separated key is neither a registry key nor a `provider::modelId` key, so\n * it would silently clear to `null` on save and vanish on reload.\n","","settings-store.ts COMPANION docstring bullet",t),await x(i," *\n * When `opts.allowCompanion` is `false`, a companion key is REJECTED even when the companion is\n * enabled - used by the builder-task surfaces, whose runs are background/cloud-only and can never\n * dispatch to a device-bound CLI.\n","","settings-store.ts opts.allowCompanion docstring paragraph",t),await x(i," * @param opts - `allowCompanion` (default `true`) controls companion-key acceptance.\n","","settings-store.ts @param opts",t),await x(i,`export function validModelKey(
|
|
1107
|
-
key: string | null | undefined,
|
|
1108
|
-
opts: { allowCompanion?: boolean } = {}
|
|
1109
|
-
): string | null {
|
|
1110
|
-
`,`export function validModelKey(key: string | null | undefined): string | null {
|
|
1111
|
-
`,"settings-store.ts validModelKey signature",t),await x(i,` if (
|
|
1112
|
-
opts.allowCompanion !== false &&
|
|
1113
|
-
config.companion?.enabled === true &&
|
|
1114
|
-
parseCompanionKey(key) !== null
|
|
1115
|
-
) {
|
|
1116
|
-
return key;
|
|
1117
|
-
}
|
|
1118
|
-
`,"","settings-store.ts companion-key branch",t);let o=mt(e,"packages/api/src/ai/task-run.ts");await x(o,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1119
|
-
`,"","task-run.ts relay import",t),await x(o,`/** Whether a chain link is usable for a task run: present and not a companion (device) key. */
|
|
1120
|
-
`,`/** Whether a chain link is usable for a task run: a present, non-empty key. */
|
|
1121
|
-
`,"task-run.ts usableTaskModelKey docstring",t),await x(o,` return typeof key === "string" && key.length > 0 && parseCompanionKey(key) === null;
|
|
1122
|
-
`,` return typeof key === "string" && key.length > 0;
|
|
1123
|
-
`,"task-run.ts usableTaskModelKey body",t),await x(o,` * override, then the builder's \`defaults.web.model\`, then the acting user's account default -
|
|
1124
|
-
* skipping companion (device-bound) links, which are valid for chat but never for a background
|
|
1125
|
-
* task - and delegating the final resolution to {@link resolveChatRun}, which owns BYOK/platform
|
|
1126
|
-
`," * override, then the builder's `defaults.web.model`, then the acting user's account default,\n * delegating the final resolution to {@link resolveChatRun}, which owns BYOK/platform\n","task-run.ts resolveTaskRun docstring model chain",t);let a=mt(e,"packages/api/src/routes/internal/ai/tasks-router.ts");await x(a,` modelKey: validModelKey(override?.modelKey ?? null, { allowCompanion: false }),
|
|
1127
|
-
`,` modelKey: validModelKey(override?.modelKey ?? null),
|
|
1128
|
-
`,"tasks-router.ts listTaskOverrides validModelKey",t),await x(a,` if (typeof body.modelKey === "string" && validModelKey(body.modelKey, { allowCompanion: false }) === null) {
|
|
1129
|
-
`,` if (typeof body.modelKey === "string" && validModelKey(body.modelKey) === null) {
|
|
1130
|
-
`,"tasks-router.ts putTask validModelKey",t)}var va=["companion:export","companion:verify","companion:publish"];async function yn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await ke(we(t,"apps/companion"),{recursive:!0}),await ke(we(t,"scripts/companion-export"),{recursive:!0}),await ba(t),await ke(we(t,"packages/api/src/relay"),{recursive:!0}),await ke(we(t,"packages/api/tests/relay"),{recursive:!0}),await ke(we(t,"packages/api/src/routes/internal/companion.ts")),await ke(we(t,"packages/api/src/routes/internal/companion-transport.ts")),await ke(we(t,"packages/api/tests/routes/companion.test.ts")),await ke(we(t,"packages/api/tests/routes/companion-transport.test.ts")),await Fr(t,n);let r=Ut(e);await ut(t,r,"companion",`/${r}/companion`,n,"Companions"),await ut(t,r,"companion-publish",`/${r}/companion-publish`,n)}async function ba(e){await vn(e,va)}var ka=new Set(["ci.yml","tauri-release.yml"]),wa=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:units","playground:test:build","playground:test:companion"];async function Kr(e){let t=y(e.projectDir,".github/workflows"),n=await bn(t).catch(()=>[]);for(let r of n)ka.has(r)||await _(y(t,r),{recursive:!0,force:!0})}async function vn(e,t){let n=y(e,"package.json"),r=JSON.parse(await j(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 l(n,JSON.stringify(r,null," ")+`
|
|
1131
|
-
`),i}async function Gr(e){let t=[...wa];St(e)||t.push("infra","infra:stop"),await vn(e.projectDir,t)}async function Hr(e){let t=y(e.projectDir,"package.json"),n=await j(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 l(t,JSON.stringify(r,null," ")+`
|
|
1132
|
-
`))}async function zr(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await _(y(e.projectDir,t),{recursive:!0,force:!0})}async function Yr(e){e.docs||await _(y(e.projectDir,"apps/docs"),{recursive:!0})}async function Jr(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await _(y(e.projectDir,t),{recursive:!0,force:!0}),await _(y(e.projectDir,"docs/index.mdx")),!e.desktop)await _(y(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!e.desktopAi){await _(y(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=y(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await j(n,"utf-8"));r.pages=r.pages.filter(i=>i!=="ai"),await l(n,`${JSON.stringify(r,null,2)}
|
|
1133
|
-
`)}}async function qr(e){if(e.desktop)return;await _(y(e.projectDir,"apps/tauri"),{recursive:!0});let t=y(e.projectDir,"packages/i18n/translations");for(let n of await bn(t,{withFileTypes:!0}))n.isDirectory()&&await _(y(t,n.name,"desktop.json"),{force:!0});await _(y(e.projectDir,".github/workflows/tauri-release.yml"))}async function Wr(e){let t=e.desktop&&e.desktopAi,n=t||e.companion;t||await _(y(e.projectDir,"packages/agent-runtime"),{recursive:!0}),n||await _(y(e.projectDir,"packages/agent-core"),{recursive:!0})}function C(e,t,n,r){let i=e.indexOf(t);if(i===-1)throw new Error(`stripDesktopAi: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(e.indexOf(t,i+t.length)!==-1)throw new Error(`stripDesktopAi: the ${r} seam appears more than once (boilerplate drift).`);return e.slice(0,i)+n+e.slice(i+t.length)}async function Xr(e){if(!e.desktop||e.desktopAi)return;let t=e.projectDir;await _(y(t,"apps/tauri/sidecar"),{recursive:!0}),await _(y(t,"apps/tauri/tsconfig.sidecar.json")),await _(y(t,"apps/tauri/tsup.sidecar.config.ts")),await _(y(t,"apps/tauri/tests/sidecar"),{recursive:!0}),await _(y(t,"apps/tauri/src-tauri/src/daemon.rs")),await _(y(t,"apps/tauri/scripts/stage-sidecar.mjs")),await _(y(t,"apps/tauri/scripts/sign-nested.mjs")),await _(y(t,"apps/tauri/resources/ai-skills"),{recursive:!0}),await _(y(t,"apps/tauri/src-tauri/resources"),{recursive:!0,force:!0});for(let a of["apps/tauri/src/screens/agents","apps/tauri/src/screens/integrations","apps/tauri/src/screens/ai","apps/tauri/src/screens/schedules.tsx","apps/tauri/src/hooks/use-ai.ts","apps/tauri/src/hooks/use-ai-chat.ts","apps/tauri/src/hooks/use-ai-resources.ts","apps/tauri/src/hooks/use-ai-scope.ts","apps/tauri/src/hooks/use-ai-terminal.ts","apps/tauri/src/hooks/use-xterm.ts","apps/tauri/src/hooks/use-async-resource.ts","apps/tauri/src/lib/ai.ts","apps/tauri/src/lib/ai-tab-state.ts","apps/tauri/src/lib/chat-prefs.ts","apps/tauri/src/lib/side-panel-state.ts","apps/tauri/src/lib/task-settings-sync.ts","apps/tauri/src/lib/bridge/ai.ts","apps/tauri/src/lib/bridge/events.ts","apps/tauri/src/lib/bridge/http.ts","apps/tauri/src/lib/bridge/wire-types.ts","apps/tauri/src/lib/bridge/control-info.ts","apps/tauri/src/lib/bridge/status.ts","apps/tauri/src/lib/bridge/types.ts","apps/tauri/src/lib/bridge/deps.ts","apps/tauri/src/components/side-panel-dock.tsx","apps/tauri/src/components/side-panel.tsx","apps/tauri/src/config/side-panels.tsx"])await _(y(t,a),{recursive:!0});for(let a of["apps/tauri/tests/ai-import-boundary.test.ts","apps/tauri/tests/bridge/ai-surface.test.ts","apps/tauri/tests/bridge/control-info.test.ts","apps/tauri/tests/bridge/events.test.ts","apps/tauri/tests/bridge/http.test.ts","apps/tauri/tests/bridge/reconnect.test.ts","apps/tauri/tests/renderer/lib/ai.test.ts","apps/tauri/tests/renderer/lib/ai-tab-state.test.ts","apps/tauri/tests/renderer/lib/chat-prefs.test.ts","apps/tauri/tests/renderer/lib/side-panel-state.test.ts","apps/tauri/tests/renderer/lib/task-settings-sync.test.ts","apps/tauri/tests/renderer/terminal-tools.test.ts","apps/tauri/tests/renderer/use-model-picker.test.ts"])await _(y(t,a));let n=y(t,"apps/tauri/package.json"),r=JSON.parse(await j(n,"utf-8")),i=["@repo/ai","@repo/agent-runtime","@homebridge/node-pty-prebuilt-multiarch","@xterm/xterm","@xterm/addon-fit","ws","@hono/node-server"];for(let a of i){if(!r.dependencies||!(a in r.dependencies))throw new Error(`stripDesktopAi: expected ${a} in apps/tauri dependencies (boilerplate drift).`);delete r.dependencies[a]}for(let a of["@types/ws","tsup"]){if(!r.devDependencies||!(a in r.devDependencies))throw new Error(`stripDesktopAi: expected ${a} in apps/tauri devDependencies (boilerplate drift).`);delete r.devDependencies[a]}if(!r.scripts||!("sidecar:stage"in r.scripts))throw new Error("stripDesktopAi: expected the sidecar:stage script in apps/tauri package.json (boilerplate drift).");if(delete r.scripts["sidecar:stage"],r.scripts["check-types"]!=="tsc -p tsconfig.json --noEmit && tsc -p tsconfig.sidecar.json --noEmit")throw new Error("stripDesktopAi: expected the two-tsconfig check-types script in apps/tauri package.json (boilerplate drift).");r.scripts["check-types"]="tsc -p tsconfig.json --noEmit",await l(n,JSON.stringify(r,null,2)+`
|
|
1134
|
-
`),await _a(t);let o=y(t,"packages/i18n/translations");for(let a of await bn(o,{withFileTypes:!0})){if(!a.isDirectory())continue;let s=y(o,a.name,"desktop.json"),d=await j(s,"utf-8").catch(()=>null);if(d===null)continue;let m=JSON.parse(d),p=!1;for(let f of["agents","ai_hub","schedules","integrations"])f in m&&(delete m[f],p=!0);p&&await l(s,JSON.stringify(m,null," ")+`
|
|
1135
|
-
`)}}var Sa=`/**
|
|
1136
|
-
* Assembles a full bridge over the injected {@link BridgeDeps} seams. Wires the control-info source,
|
|
1137
|
-
* the engine HTTP transport, the shared status store, the event hub, the host auth-token sync, the
|
|
1138
|
-
* native surface (registering the reconnect auth resync via the hub), and the ai surface (folding in
|
|
1139
|
-
* the native workspace picker). The four \`@tauri-apps\` primitives are injected so a bridge can be built
|
|
1140
|
-
* against fake transports in tests; this factory imports the real plugin functions directly, which the
|
|
1141
|
-
* shell webview satisfies.
|
|
1142
|
-
*
|
|
1143
|
-
* @param deps - The \`fetch\`, \`WebSocket\`, \`invoke\`, and \`listen\` seams.
|
|
1144
|
-
* @returns The assembled bridge and its status store.
|
|
1145
|
-
*/
|
|
1146
|
-
export function createBridge(deps: BridgeDeps): { bridge: Bridge; status: StatusStore } {
|
|
1147
|
-
const clientId = crypto.randomUUID()
|
|
1148
|
-
const source = createControlSource(deps)
|
|
1149
|
-
const http = createEngineHttp({ source, fetchFn: deps.fetchFn, clientId })
|
|
1150
|
-
const status = createStatusStore()
|
|
1151
|
-
const events = createEngineEvents({
|
|
1152
|
-
source,
|
|
1153
|
-
http,
|
|
1154
|
-
WebSocketCtor: deps.WebSocketCtor,
|
|
1155
|
-
clientId,
|
|
1156
|
-
status
|
|
1157
|
-
})
|
|
1158
|
-
const hostAuthSync = createHostAuthSync({ source, fetchFn: deps.fetchFn, clientId })
|
|
1159
|
-
const { native, pickWorkspace } = createNativeBridge({
|
|
1160
|
-
invoke: deps.invoke,
|
|
1161
|
-
listen: deps.listen,
|
|
1162
|
-
openUrl,
|
|
1163
|
-
isPermissionGranted,
|
|
1164
|
-
requestPermission,
|
|
1165
|
-
sendNotification: (options) => sendNotification(options),
|
|
1166
|
-
checkUpdate: () => check(),
|
|
1167
|
-
relaunch,
|
|
1168
|
-
openDialog: (options) => open(options),
|
|
1169
|
-
hostAuthSync,
|
|
1170
|
-
registerAuthResync: events.syncAuthToken,
|
|
1171
|
-
isDev: import.meta.env.DEV
|
|
1172
|
-
})
|
|
1173
|
-
const ai = createAiBridge({ http, events, pickWorkspace })
|
|
1174
|
-
return { bridge: { ...native, ai }, status }
|
|
1175
|
-
}`,Ea=`/**
|
|
1176
|
-
* Assembles the native bridge over the injected Tauri command/event seams. The \`invoke\` and \`listen\`
|
|
1177
|
-
* primitives are injected so a bridge can be built against fakes in tests; this factory imports the
|
|
1178
|
-
* real plugin functions (opener / notification / updater / process / dialog) directly, which the
|
|
1179
|
-
* shell webview satisfies.
|
|
1180
|
-
*
|
|
1181
|
-
* @param deps - The \`invoke\` and \`listen\` seams.
|
|
1182
|
-
* @returns The assembled native bridge.
|
|
1183
|
-
*/
|
|
1184
|
-
export function createBridge(deps: {
|
|
1185
|
-
invoke: <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>
|
|
1186
|
-
listen: (event: string, handler: (event: { payload: unknown }) => void) => Promise<() => void>
|
|
1187
|
-
}): { bridge: Bridge } {
|
|
1188
|
-
const { native } = createNativeBridge({
|
|
1189
|
-
invoke: deps.invoke,
|
|
1190
|
-
listen: deps.listen,
|
|
1191
|
-
openUrl,
|
|
1192
|
-
isPermissionGranted,
|
|
1193
|
-
requestPermission,
|
|
1194
|
-
sendNotification: (options) => sendNotification(options),
|
|
1195
|
-
checkUpdate: () => check(),
|
|
1196
|
-
relaunch,
|
|
1197
|
-
openDialog: (options) => open(options),
|
|
1198
|
-
isDev: import.meta.env.DEV
|
|
1199
|
-
})
|
|
1200
|
-
return { bridge: native }
|
|
1201
|
-
}`,Aa=`/** The four production seams: \`globalThis\` fetch/WebSocket + the real Tauri command/event primitives. */
|
|
1202
|
-
function productionDeps(): BridgeDeps {
|
|
1203
|
-
return {
|
|
1204
|
-
fetchFn: (input, init) => fetch(input, init),
|
|
1205
|
-
WebSocketCtor: WebSocket,
|
|
1206
|
-
invoke,
|
|
1207
|
-
listen: (event, handler) => tauriListen(event, handler)
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1159
|
+
`,"","auth config mcp plugin block",n);let u=F(t,"packages/auth/package.json"),g=JSON.parse(await Eo(u,"utf-8"));if(!g.exports)throw new Error(`${n}: expected an exports map in packages/auth/package.json (boilerplate drift).`);Wt(g.exports,"./mcp",'the "./mcp" export in packages/auth/package.json',n),await p(u,JSON.stringify(g,null," ")+`
|
|
1160
|
+
`);let l=F(t,"packages/api/package.json"),m=JSON.parse(await Eo(l,"utf-8"));if(!m.dependencies)throw new Error(`${n}: expected dependencies in packages/api/package.json (boilerplate drift).`);Wt(m.dependencies,"@mastra/mcp","@mastra/mcp in packages/api dependencies",n),Wt(m.dependencies,"@modelcontextprotocol/sdk","@modelcontextprotocol/sdk in packages/api dependencies",n),await p(l,JSON.stringify(m,null," ")+`
|
|
1161
|
+
`);let w=it(e);if(await Ur(t,w,"companion-agent-mcp",`/${w}/companion-agent-mcp`,n,"MCP"),await I(F(t,`docs/${w}/configuration.mdx`),`| \`mcpServer.enabled\` | \`false\` (requires \`ai\`) | Outward MCP server URL + the **MCP** settings tab - see [external agent (MCP)](/${w}/companion-agent-mcp) |
|
|
1162
|
+
`,"","configuration.mdx mcpServer config-table row",n),e.companion){let v=F(t,`docs/${w}/companion/index.mdx`);await I(v,`It is the user-owned counterpart to the [external agent (MCP)](/${w}/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.
|
|
1210
1163
|
|
|
1211
|
-
|
|
1164
|
+
`,"","companion index.mdx MCP counterpart paragraph",n),await I(v,` <Card title="External Agent (MCP)" href="/${w}/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 Ao,rm as _}from"fs/promises";import{join as R}from"path";import{readFile as nn}from"fs/promises";import{join as xt}from"path";async function Io(e,t){let n=xt(e,"packages/api/src/routes/internal/index.ts");await p(n,O(await nn(n,"utf-8"),"internal router","companion",t)),await Xt(n);let r=xt(e,"packages/api/src/ai/schedule-runner.ts");await p(r,O(await nn(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=xt(e,a);await p(s,O(await nn(s,"utf-8"),a,"companion",t))}let o=xt(e,"packages/api/src/ai/settings-store.ts");await I(o,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1212
1166
|
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
let instance: { bridge: Bridge } | null = null
|
|
1247
|
-
|
|
1248
|
-
/** Builds the production bridge exactly once, on first use (never at module load). */
|
|
1249
|
-
function productionInstance(): { bridge: Bridge } {
|
|
1250
|
-
if (!instance) instance = createBridge(productionDeps())
|
|
1251
|
-
return instance
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
/**
|
|
1255
|
-
* Forwards every property access to a lazily-built target, so importing this module triggers no
|
|
1256
|
-
* \`invoke\` / \`listen\` work. The first property access builds and memoizes the instance; every later
|
|
1257
|
-
* access returns the same member (stable identities).
|
|
1258
|
-
*/
|
|
1259
|
-
function lazyForward<T extends object>(build: () => T): T {
|
|
1260
|
-
return new Proxy(Object.create(null) as T, {
|
|
1261
|
-
get: (_target, prop) => (build() as Record<PropertyKey, unknown>)[prop]
|
|
1262
|
-
})
|
|
1263
|
-
}
|
|
1264
|
-
|
|
1265
|
-
/** The production bridge singleton, lazily built on first property access. */
|
|
1266
|
-
export const bridge: Bridge = lazyForward(() => productionInstance().bridge)`,Pa=`/// The control-server coordinates the renderer needs: the loopback URL (absent until the
|
|
1267
|
-
/// sidecar reports ready) and the bearer token (always present, minted at shell startup).
|
|
1268
|
-
#[derive(serde::Serialize)]
|
|
1269
|
-
struct ControlInfo {
|
|
1270
|
-
url: Option<String>,
|
|
1271
|
-
token: String,
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
/// Returns the current control-server URL and bearer. Callable before the sidecar is ready
|
|
1275
|
-
/// (\`url\` is \`None\` until then; \`token\` is always the minted control token).
|
|
1276
|
-
#[tauri::command]
|
|
1277
|
-
fn get_control_info(state: tauri::State<'_, daemon::DaemonHandle>) -> ControlInfo {
|
|
1278
|
-
let guard = state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
1279
|
-
ControlInfo {
|
|
1280
|
-
url: guard.url.clone(),
|
|
1281
|
-
token: guard.control_token.clone(),
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
|
|
1285
|
-
`,Ta="//! Long-lived secret storage for the shell's two secrets: the app bearer token\n//! (set on sign-in, cleared on sign-out) and the engine's AES-256-GCM master key\n//! (created once on first run). Both ride the stdin handshake to the sidecar;\n//! neither is ever passed on argv or in the environment.\n//!\n//! Packaged (release) builds store both in the OS credential store (macOS\n//! Keychain, Windows Credential Manager, Linux Secret Service) under the app\n//! identifier as the service name (`tauri.conf.json`'s `identifier`, which the\n//! CLI and `sync-identity.mjs` rewrite on a rebrand, so rebranded apps never\n//! share entries), users `auth-token` and `engine-master-key`.",Ra="//! Long-lived secret storage for the app bearer token (set on sign-in, cleared\n//! on sign-out). It is never passed on argv or in the environment.\n//!\n//! Packaged (release) builds store it in the OS credential store (macOS\n//! Keychain, Windows Credential Manager, Linux Secret Service) under the app\n//! identifier as the service name (`tauri.conf.json`'s `identifier`, which the\n//! CLI and `sync-identity.mjs` rewrite on a rebrand, so rebranded apps never\n//! share entries), user `auth-token`.";async function _a(e){let t=y(e,"apps/tauri/src/components/shell.tsx");await l(t,F(await j(t,"utf-8"),"components/shell.tsx"));let n=y(e,"apps/tauri/src/components/sidebar/app-sidebar.tsx"),r=F(await j(n,"utf-8"),"components/sidebar/app-sidebar.tsx");r=C(r,"import { useCallback, useMemo, useSyncExternalStore } from 'react'","import { useCallback, useMemo } from 'react'","app-sidebar useSyncExternalStore import"),await l(n,r);let i=y(e,"apps/tauri/src/config/sidebar.ts"),o=F(await j(i,"utf-8"),"config/sidebar.ts");o=C(o,`import {
|
|
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=xt(e,"packages/api/tests/ai/settings-store.test.ts");await p(i,O(await nn(i,"utf-8"),"settings-store.test.ts","companion",t))}var ss=["companion:export","companion:verify","companion:publish"];async function Vn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await _(R(t,"packages/api/src/relay"),{recursive:!0}),await _(R(t,"packages/api/src/companion"),{recursive:!0}),await _(R(t,"packages/api/src/ai/companion-model.ts")),await _(R(t,"packages/api/tests/relay"),{recursive:!0}),await _(R(t,"packages/api/tests/companion"),{recursive:!0}),await _(R(t,"packages/api/src/routes/internal/companion.ts")),await _(R(t,"packages/api/src/routes/internal/companion-transport.ts")),await _(R(t,"packages/api/tests/routes/companion.test.ts")),await _(R(t,"packages/api/tests/routes/companion-transport-harness.ts")),await _(R(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await _(R(t,"packages/api/tests/routes/companion-transport-poll.test.ts")),await _(R(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await _(R(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await _(R(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await _(R(t,"packages/api/tests/ai/companion-model.test.ts")),await _(R(t,"packages/api/tests/ai/companion-chat.test.ts")),await _(R(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await _(R(t,"packages/api/tests/helpers/redis-mock.ts"));let r=R(t,"packages/api/package.json"),o=JSON.parse(await Ao(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 Yt(r,o," ",n),await Io(t,n);let i=it(e);await Vr(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 Fn(e){if(Q(e)||e.demo&&e.companion)return;let t=e.projectDir;await _(R(t,"apps/companion"),{recursive:!0}),await _(R(t,"scripts/companion-export"),{recursive:!0}),await cs(t)}async function Bn(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="stripDesktopCompanionDoc";await _(R(t,"docs/desktop/companion.mdx"));let r=R(t,"docs/desktop/meta.json"),o=JSON.parse(await Ao(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 cs(e){await Gn(e,ss)}var ps=new Set(["ci.yml","desktop-release.yml"]),ls={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"]},ds=["@repo/ai","@repo/agent-core","@repo/agent-core-types","ai","@ai-sdk/react","@homebridge/node-pty-prebuilt-multiarch","@xterm/xterm","@xterm/addon-fit"],us=["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 Po(e){let t=y(e.projectDir,".github/workflows"),n=await Kn(t).catch(()=>[]);for(let r of n)ps.has(r)||await N(y(t,r),{recursive:!0,force:!0})}async function Gn(e,t){let n=y(e,"package.json"),r=JSON.parse(await U(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 Ro(e){let t=[...us];jt(e)||t.push("infra","infra:stop"),await Gn(e.projectDir,t)}async function xo(e){let t=y(e.projectDir,"package.json"),n=await U(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 To(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await N(y(e.projectDir,t),{recursive:!0,force:!0})}async function _o(e){e.docs||await N(y(e.projectDir,"apps/docs"),{recursive:!0})}async function Oo(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await N(y(e.projectDir,t),{recursive:!0,force:!0}),await N(y(e.projectDir,"docs/index.mdx")),!e.desktop)await N(y(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!(e.desktop&&e.ai)){await N(y(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=y(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await U(n,"utf-8"));r.pages=r.pages.filter(o=>o!=="ai"),await p(n,`${JSON.stringify(r,null,2)}
|
|
1176
|
+
`)}await ms(e)}async function ms(e){let t=e.projectDir,n="stripUnusedDocsSilo",r=it(e),o=y(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(y(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(y(t,`docs/${r}/companion/index.mdx`),`## Set up from the desktop app
|
|
1177
|
+
|
|
1178
|
+
If your product also ships the [desktop app](/desktop), it runs the companion for each user as a local daemon on their own machine - consent-first, with no terminal, no pairing, and no code to copy. It attaches to any daemon already serving the machine - including the user's own always-on service - and starts its own only when none is running, so one daemon serves both the app and any paired backend. It supervises that daemon while the app is open and, on quit, stops only the one it started - never the user's service. See [Companion setup](/desktop/companion).
|
|
1179
|
+
|
|
1180
|
+
`,"","companion index.mdx desktop-setup section",n),await I(y(t,`docs/${r}/companion/terminal.mdx`),`## In the desktop app
|
|
1181
|
+
|
|
1182
|
+
If your product ships the [desktop app](/desktop), its **Terminal** side-panel tab is this same session, in an embedded terminal: the app spawns the daemon's \`terminal\` command in a real pty, and its folder picker **grants** the folder it picked (the durable, per-app grant above) before the session opens. See [Terminal and side panel](/desktop/ai/terminal).
|
|
1183
|
+
|
|
1184
|
+
`,"","companion terminal.mdx desktop-panel section",n))),e.desktop&&!e.ai&&await I(y(t,"docs/desktop/index.mdx"),` <Card href="/desktop/ai" title="AI agents" description="Turn the user's own AI subscription or API key into a workspace-scoped agent." />
|
|
1185
|
+
`,"","desktop index.mdx AI card",n)}async function Co(e){if(e.desktop)return;await N(y(e.projectDir,"apps/electron"),{recursive:!0});let t=y(e.projectDir,"packages/i18n/translations");for(let o of await Kn(t,{withFileTypes:!0}))o.isDirectory()&&await N(y(t,o.name,"desktop.json"),{force:!0});await N(y(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of ls[e.frontend])await N(y(e.projectDir,o),{recursive:!0});await N(y(e.projectDir,"packages/utils/src/desktop-download.ts")),await N(y(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=y(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await U(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 Yt(n,r," ","stripDesktopApp")}async function Do(e){Q(e)||await N(y(e.projectDir,"packages/agent-core"),{recursive:!0})}function Tt(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 No(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 N(y(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 N(y(t,a));await N(y(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 N(y(t,a));let r=y(t,`${n}/package.json`),o=JSON.parse(await U(r,"utf-8"));for(let a of ds){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"],fs(o,"stage:companion",n),await p(r,JSON.stringify(o,null,2)+`
|
|
1186
|
+
`),await gs(t,n);let i=y(t,"packages/i18n/translations");for(let a of await Kn(i,{withFileTypes:!0})){if(!a.isDirectory())continue;let s=y(i,a.name,"desktop.json"),u=await U(s,"utf-8").catch(()=>null);if(u===null)continue;let g=JSON.parse(u),l=!1;for(let m of["agents","ai_hub","schedules","integrations"])m in g&&(delete g[m],l=!0);l&&await p(s,JSON.stringify(g,null," ")+`
|
|
1187
|
+
`)}}function fs(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 gs(e,t){let n=y(e,`${t}/src/renderer/components/shell.tsx`);await p(n,O(await U(n,"utf-8"),"components/shell.tsx"));let r=y(e,`${t}/src/renderer/components/auth-gate.tsx`);await p(r,O(await U(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=y(e,`${t}/src/renderer/config/sidebar.ts`),i=O(await U(o,"utf-8"),"config/sidebar.ts");i=Tt(i,`import {
|
|
1286
1197
|
BuildingsIcon,
|
|
1198
|
+
ChatCircleIcon,
|
|
1199
|
+
ClockCountdownIcon,
|
|
1287
1200
|
GearIcon,
|
|
1288
1201
|
HouseIcon,
|
|
1289
|
-
RobotIcon,
|
|
1290
1202
|
UserCircleIcon
|
|
1291
|
-
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await
|
|
1292
|
-
`,"","router clientConfig import"),
|
|
1203
|
+
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await p(o,i);let a=y(e,`${t}/src/renderer/lib/config.ts`),s=O(await U(a,"utf-8"),"lib/config.ts");s=s.replace(/,(\n\} as const)/,"$1"),await p(a,s);let u=y(e,`${t}/src/renderer/lib/sidebar-flags.ts`);await p(u,O(await U(u,"utf-8"),"lib/sidebar-flags.ts"));let g=y(e,`${t}/src/renderer/router.tsx`),l=O(await U(g,"utf-8"),"router.tsx");l=Tt(l,`import { clientConfig } from '@/lib/config'
|
|
1204
|
+
`,"","router clientConfig import"),l=Tt(l,` createRouter,
|
|
1293
1205
|
redirect
|
|
1294
1206
|
} from '@tanstack/react-router'`,` createRouter
|
|
1295
|
-
} from '@tanstack/react-router'`,"router redirect import specifier"),
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
`,"","lib.rs handle binding"),R=C(R,` if let Err(err) = daemon::init(&handle) {
|
|
1309
|
-
eprintln!("[shell] sidecar init failed: {err}");
|
|
1310
|
-
}
|
|
1311
|
-
`,"","lib.rs daemon::init call"),R=C(R," let dl_handle = handle.clone();"," let dl_handle = app.handle().clone();","lib.rs macos deep-link handle"),R=C(R,` .run(|app_handle, event| {
|
|
1312
|
-
if let tauri::RunEvent::Exit = event {
|
|
1313
|
-
daemon::shutdown(app_handle);
|
|
1314
|
-
}
|
|
1315
|
-
});`," .run(|_app_handle, _event| {});","lib.rs daemon::shutdown exit hook"),await l(V,R);let te=y(e,"apps/tauri/src-tauri/src/keyring_store.rs"),B=await j(te,"utf-8");B=C(B,Ta,Ra,"keyring_store module doc"),B=F(B,"src-tauri/src/keyring_store.rs"),await l(te,B);let v=y(e,"apps/tauri/src-tauri/capabilities/default.json"),P=JSON.parse(await j(v,"utf-8")),O=P.permissions.length;if(P.permissions=P.permissions.filter(w=>w!=="dialog:default"),P.permissions.length===O)throw new Error("stripDesktopAi: expected the dialog:default capability in capabilities/default.json (boilerplate drift).");await l(v,JSON.stringify(P,null,2)+`
|
|
1316
|
-
`);let Y=y(e,"apps/tauri/src-tauri/tauri.conf.json"),T=JSON.parse(await j(Y,"utf-8"));if(!T.bundle)throw new Error("stripDesktopAi: expected a bundle block in tauri.conf.json (boilerplate drift).");if(Ze(T.bundle,"externalBin","the tauri.conf bundle.externalBin key","stripDesktopAi"),Ze(T.bundle,"resources","the tauri.conf bundle.resources key","stripDesktopAi"),!T.build||T.build.beforeDevCommand!=="pnpm sidecar:stage && pnpm dev:vite")throw new Error("stripDesktopAi: expected the sidecar-staged beforeDevCommand in tauri.conf.json (boilerplate drift).");if(T.build.beforeBuildCommand!=="pnpm sidecar:stage && pnpm build:vite")throw new Error("stripDesktopAi: expected the sidecar-staged beforeBuildCommand in tauri.conf.json (boilerplate drift).");T.build.beforeDevCommand="node scripts/sync-identity.mjs && pnpm dev:vite",T.build.beforeBuildCommand="node scripts/sync-identity.mjs && pnpm build:vite",await l(Y,JSON.stringify(T,null,2)+`
|
|
1317
|
-
`)}import{readFile as Oa}from"fs/promises";import{join as xa}from"path";var Zr=`on:
|
|
1207
|
+
} from '@tanstack/react-router'`,"router redirect import specifier"),l=Tt(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=Tt(l,` ...(clientConfig.agentsEnabled ? aiRoutes : []),
|
|
1214
|
+
`,"","router ai route spread"),await p(g,l);let m=y(e,`${t}/src/renderer/screens/settings/index.tsx`);await p(m,O(await U(m,"utf-8"),"screens/settings/index.tsx"));let w=y(e,`${t}/src/main/ipc.ts`);await p(w,O(await U(w,"utf-8"),"src/main/ipc.ts"));let v=y(e,`${t}/src/main/index.ts`);await p(v,O(await U(v,"utf-8"),"src/main/index.ts"));let x=y(e,`${t}/src/preload/index.ts`);await p(x,O(await U(x,"utf-8"),"src/preload/index.ts"));let Y=y(e,`${t}/electron-builder.mjs`);await p(Y,O(await U(Y,"utf-8"),"electron-builder.mjs"))}import{readFile as hs}from"fs/promises";import{join as ys}from"path";var $o=`on:
|
|
1215
|
+
workflow_run:
|
|
1216
|
+
workflows: ["Tag Release"]
|
|
1217
|
+
branches: [main]
|
|
1218
|
+
types: [completed]
|
|
1219
|
+
workflow_dispatch:`,ws=`on:
|
|
1318
1220
|
workflow_run:
|
|
1319
1221
|
workflows: ["CI"]
|
|
1320
1222
|
branches: [main]
|
|
1321
1223
|
types: [completed]
|
|
1322
|
-
workflow_dispatch:`,
|
|
1224
|
+
workflow_dispatch:`,vs=`on:
|
|
1323
1225
|
# Automatic release on CI success is disabled for this project to conserve
|
|
1324
1226
|
# GitHub Actions minutes. Re-enable by uncommenting the workflow_run trigger.
|
|
1325
1227
|
# workflow_run:
|
|
1326
1228
|
# workflows: ["CI"]
|
|
1327
1229
|
# branches: [main]
|
|
1328
1230
|
# types: [completed]
|
|
1329
|
-
workflow_dispatch:`;async function
|
|
1231
|
+
workflow_dispatch:`;async function Lo(e){if(!e.desktop)return;let t=ys(e.projectDir,".github/workflows/desktop-release.yml"),n=await hs(t,"utf8");if(!n.includes($o))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?ws:vs;await p(t,n.replace($o,r))}import{join as ks}from"path";async function Uo(e){let t=bs(e);await p(ks(e.projectDir,".github/workflows/ci.yml"),t)}function bs(e){let t=X[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",o=t?"":` services:
|
|
1330
1232
|
postgres:
|
|
1331
1233
|
image: postgres:18-alpine
|
|
1332
1234
|
env:
|
|
@@ -1340,14 +1242,14 @@ export interface Bridge extends NativeBridgeParts {
|
|
|
1340
1242
|
--health-interval 10s
|
|
1341
1243
|
--health-timeout 5s
|
|
1342
1244
|
--health-retries 5
|
|
1343
|
-
`,
|
|
1245
|
+
`,i=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",a=n?`
|
|
1344
1246
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1345
1247
|
UPSTASH_REDIS_REST_TOKEN: test-token`:"",s=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1346
1248
|
STRIPE_SECRET_KEY: test
|
|
1347
1249
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1348
1250
|
POLAR_ACCESS_TOKEN: test
|
|
1349
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1350
|
-
${
|
|
1251
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let m=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(m)}"`)}}})(),u=e.socialProviders.map(m=>ge[m].envVars.map(w=>`
|
|
1252
|
+
${w.name}: test`).join("")).join("");return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1351
1253
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1352
1254
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1353
1255
|
|
|
@@ -1371,8 +1273,8 @@ jobs:
|
|
|
1371
1273
|
name: Checks
|
|
1372
1274
|
runs-on: ubuntu-latest
|
|
1373
1275
|
timeout-minutes: 20
|
|
1374
|
-
${
|
|
1375
|
-
CONTENT_API_KEY: test-contentapi-key-16chars${a}${s}${
|
|
1276
|
+
${o} env:
|
|
1277
|
+
CONTENT_API_KEY: test-contentapi-key-16chars${a}${s}${u}
|
|
1376
1278
|
STORAGE_REGION: test
|
|
1377
1279
|
STORAGE_ENDPOINT: http://test
|
|
1378
1280
|
STORAGE_ACCESS_KEY_ID: test
|
|
@@ -1393,49 +1295,51 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1393
1295
|
NODE_OPTIONS: --max-old-space-size=6144`:" - run: pnpm check-types"}
|
|
1394
1296
|
|
|
1395
1297
|
- name: Write root env
|
|
1396
|
-
run: echo "DATABASE_URL=${
|
|
1298
|
+
run: echo "DATABASE_URL=${i}" > .env
|
|
1397
1299
|
|
|
1398
1300
|
- run: pnpm test
|
|
1399
|
-
`}import{readFile as
|
|
1400
|
-
`))}async function
|
|
1401
|
-
`))}async function
|
|
1301
|
+
`}import{readFile as jo}from"fs/promises";import{existsSync as Ss}from"fs";import{join as Hn}from"path";var Mo="@repo/database";function Es(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function Is(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 As(e,t,n){let r=await jo(e,"utf-8"),o=JSON.parse(r),i=o.scripts?.[t];if(!i)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);i.includes(Mo)||(o.scripts={...o.scripts,[t]:`${n} && ${i}`},await p(e,JSON.stringify(o,null," ")+`
|
|
1302
|
+
`))}async function Ps(e,t){let n=Ss(e)?JSON.parse(await jo(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},r=n.buildCommand?.trim()||"pnpm build";r.includes(Mo)||(n.buildCommand=`${t} && ${r}`,await p(e,JSON.stringify(n,null," ")+`
|
|
1303
|
+
`))}async function Vo(e){let t=Es(e.demo===!0),n=Is(e.architecture,e.frontend),r=Hn(e.projectDir,"apps",n);switch(e.deploymentTarget){case"node":await As(Hn(r,"package.json"),"start",t);return;case"vercel":await Ps(Hn(r,"vercel.json"),t);return;default:{let o=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(o)}"`)}}}import{readFile as Rs}from"fs/promises";import{existsSync as xs}from"fs";import{join as rn}from"path";var Ts=["stripe","polar"];async function Fo(e){let t=rn(e.projectDir,"packages/payments/src"),n=e.paymentProvider,r=`// Active payment provider. To switch, change the path below to
|
|
1402
1304
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1403
1305
|
export { ops } from "./${n}/index";
|
|
1404
|
-
`;await
|
|
1405
|
-
`).filter(a=>!
|
|
1406
|
-
`)}import{readdir as
|
|
1407
|
-
`).filter(
|
|
1408
|
-
`).length&&await
|
|
1409
|
-
`))}async function
|
|
1410
|
-
`),await
|
|
1411
|
-
`)}import{relative as
|
|
1412
|
-
`);
|
|
1413
|
-
${
|
|
1414
|
-
`),
|
|
1415
|
-
`),
|
|
1416
|
-
`),
|
|
1417
|
-
`),await
|
|
1418
|
-
`),
|
|
1419
|
-
`);let
|
|
1420
|
-
`)}if(
|
|
1421
|
-
`),
|
|
1422
|
-
`),
|
|
1423
|
-
|
|
1424
|
-
${
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
`),
|
|
1429
|
-
`).
|
|
1306
|
+
`;await p(rn(t,"providers/index.ts"),r),await p(rn(t,"index.ts"),await _s(t,n))}async function _s(e,t){let n=rn(e,"index.ts");if(!xs(n))throw new Error(`generatePaymentBarrel: expected ${n} to exist - did packages/payments move?`);let r=await Rs(n,"utf-8"),o=Ts.filter(a=>a!==t);return r.split(`
|
|
1307
|
+
`).filter(a=>!o.some(s=>a.includes(`./providers/${s}/`))).join(`
|
|
1308
|
+
`)}import{readdir as Os,readFile as Cs}from"fs/promises";import{join as Bo}from"path";async function Go(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,n=JSON.stringify(t).slice(1,-1),r=Bo(e.projectDir,"packages/i18n/translations"),o;try{o=await Os(r)}catch{return}for(let i of o){let a=Bo(r,i,"web.json"),s;try{s=await Cs(a,"utf-8")}catch{continue}let u=s.replaceAll("GenerateSaaS",n);u!==s&&await p(a,u)}}import{readFile as Ds}from"fs/promises";import{join as Ko}from"path";var Ns=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],$s=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function zo(e){let n=e.frontend==="nuxt"?$s:Ns;await Ho(Ko(e.projectDir,".gitignore"),n),await Ho(Ko(e.projectDir,".dockerignore"),n)}async function Ho(e,t){let n;try{n=await Ds(e,"utf-8")}catch{return}let r=new Set(t),o=n.split(`
|
|
1309
|
+
`).filter(i=>!r.has(i.trim()));o.length!==n.split(`
|
|
1310
|
+
`).length&&await p(e,o.join(`
|
|
1311
|
+
`))}async function on(e){let t=e.projectDir;e.demo||(await Br(t),await Kr(t),await Hr(t),await zr(t),e.desktop&&await Gr(t)),await Jr(t,e.aiTools),await qr(t,e.frontend),await Wr(e),await Xr(e),await Qr(e),await Zr(e),e.demo||await eo(e),await ro(e);let n=await oo(e);return await io(e),await ao(e),await so(e),await co(e),await po(e),await lo(e),await go(e),await ho(e),await vo(e),await So(e),await Po(e),await Uo(e),await Ro(e),await xo(e),await To(e),await _o(e),await Oo(e),await Co(e),await No(e),await Do(e),await Lo(e),await Mn(e),await Vn(e),await Fn(e),await Bn(e),await Vo(e),await Fo(e),await Go(e),await zo(e),{dockerComposeGenerated:n}}import{basename as qo,join as Yo,relative as Us}from"path";import{createHash as Jo}from"crypto";import{readFile as Ls}from"fs/promises";async function an(e){let t=await Ls(e);return Jo("sha256").update(t).digest("hex")}function zn(e){return Jo("sha256").update(e).digest("hex")}var js=new Set(["data",J]);function Ms(e){let t=e.split("/");for(let n of t)if(Rn.has(n)||xn.has(n)||js.has(n)||n.startsWith(".env")&&!n.includes("example"))return!0;return!1}function Wo(e,t){return{projectName:e.projectName??qo(t),appName:e.appName??e.projectName??qo(t),projectDir:t,frontend:e.frontend==="nextjs"?"nextjs":"nuxt",architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,billingScope:e.billingScope??"user",blog:e.blog??!1,emailTracking:e.emailTracking??!0,docs:e.docs??!1,desktop:e.desktop??!1,desktopAutoRelease:e.desktopAutoRelease??!0,ai:e.ai??!1,companion:e.companion??!1,companionSource:Z(e),companionRepoUrl:e.companionRepoUrl??Ue,companionLocalPath:e.companionLocalPath??"",companionName:e.companionName??re(e.projectName),mcpServer:e.mcpServer??!1,aiBuiltin:Ee(e)&&(e.aiBuiltin??!0),aiByok:e.aiByok??!0,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,dockerServices:e.dockerServices??[],aiTools:e.aiTools??[],socialProviders:e.socialProviders??[],defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Vs(e,t){return{version:e.version,initialVersion:e.version,repo:"Duzbee/GenerateSaaS",appName:e.appName,projectName:e.projectName,frontend:e.frontend,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,desktopAutoRelease:e.desktopAutoRelease,ai:e.ai,companion:e.companion,mcpServer:e.mcpServer,...e.companionName?{companionName:e.companionName}:{},...e.companionSource?{companionSource:e.companionSource}:{},...e.companionRepoUrl?{companionRepoUrl:e.companionRepoUrl}:{},...e.companionLocalPath!==void 0?{companionLocalPath:e.companionLocalPath}:{},aiBuiltin:e.aiBuiltin,aiByok:e.aiByok,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,dockerServices:e.dockerServices,socialProviders:e.socialProviders,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,aiTools:e.aiTools,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Xo(e,t){let r=(await Fe(e.projectDir,e.projectDir,Ms)).sort(),o=await Promise.all(r.map(async s=>[Ve(Us(e.projectDir,s)),await an(s)])),i=Object.fromEntries(o),a=Vs(e,t);await p(Yo(e.projectDir,Ie),JSON.stringify(a,null," ")+`
|
|
1312
|
+
`),await p(Yo(e.projectDir,xr),JSON.stringify(i,null," ")+`
|
|
1313
|
+
`)}import{relative as Fs}from"path";async function Be(e){let n=(await Fe(e,e,ot)).sort(),r=await Promise.all(n.map(async o=>[Ve(Fs(e,o)),await an(o)]));return Object.fromEntries(r)}import{copyFile as Bs,mkdir as Gs,rm as Ks}from"fs/promises";import{dirname as Hs,join as Zo,relative as zs}from"path";import{existsSync as Js}from"fs";async function Jn(e,t){Js(t)&&await Ks(t,{recursive:!0,force:!0});let n=await Fe(e,e,ot);for(let r of n){let o=Ve(zs(e,r)),i=Zo(t,o);await Gs(Hs(i),{recursive:!0}),await Bs(r,i)}}async function Qo(e,t){await Jn(e,Zo(t,Kt))}import{existsSync as qs}from"fs";import{readFile as ei,readdir as Ys}from"fs/promises";import{join as me,dirname as Ws,resolve as Xs,sep as Zs}from"path";import{fileURLToPath as Qs}from"url";var _t={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},ym=Object.values(_t),qn="generatesaas-update",ti=Ws(Qs(import.meta.url));function ec(){let e=me(ti,"skill","content");return qs(e)?e:me(ti,"content")}function Yn(e){return!e||e.length===0?[]:e.map(t=>_t[t])}async function Wn(e,t,n,r){let o=Yn(r);for(let i of o){let a=me(e,i,qn),s=me(a,"scripts"),u=me(a,"references");await qt(s),await qt(u),await p(me(a,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",i)),await p(me(u,".gitkeep"),"");for(let[g,l]of Object.entries(n)){let m=Xs(s,g);m.startsWith(s+Zs)&&await p(m,l)}}}async function ni(e,t){let n=ec(),r=await ei(me(n,"SKILL.md"),"utf-8"),o=me(n,"scripts"),i=await Ys(o),a={};for(let s of i)s!==".gitkeep"&&(a[s]=await ei(me(o,s),"utf-8"));await Wn(e,r,a,t)}import{execFile as tc,execFileSync as nc}from"child_process";import{access as ri,readFile as rc}from"fs/promises";import{join as Xn}from"path";import*as $ from"@clack/prompts";function Ke(e){try{let t=process.platform==="win32"?"where":"which";return nc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Ge(e,t,n,r=3e5){return new Promise((o,i)=>{tc(e,t,{cwd:n,timeout:r,maxBuffer:50*1024*1024},(a,s,u)=>{if(a){let g=String(s||"").trim(),m=[String(u||"").trim(),g].filter(Boolean).join(`
|
|
1314
|
+
`);i(new Error(m?`${a.message}
|
|
1315
|
+
${m}`:a.message))}else o()})})}async function oi(e){if(!Ke("pnpm"))return $.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Ge("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let n=t instanceof Error?t.message:String(t);return $.log.warn(`Lockfile regeneration failed: ${n}`),$.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function ii(e){if(!Ke("pnpm"))return $.log.warn("pnpm not found. Skipping dependency installation."),$.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=$.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Ge("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(n){t.stop("Dependency installation failed.");let r=n instanceof Error?n.message:String(n);return $.log.warn(`pnpm install failed: ${r}`),$.log.warn("You can run it manually later."),!1}}async function ai(e){if(!Ke("pnpm"))return!1;let t=$.spinner();t.start("Generating baseline database migration...");try{return await Ge("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(n){t.stop("Baseline migration generation failed.");let r=n instanceof Error?n.message:String(n);return $.log.warn(`Could not generate baseline migration: ${r}`),$.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function si(e){try{return await ri(Xn(e,".git")),$.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ke("git"))return $.log.warn("git not found. Skipping repository initialization."),!1;let t=$.spinner();t.start("Initializing git repository...");try{return await Ge("git",["init"],e),await Ge("git",["add","-A"],e),await Ge("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),$.log.warn("You can run git init manually later."),!1}}async function ci(e){if(!Ke("pnpm"))return!1;try{await ri(Xn(e,".git"))}catch{return!1}try{let t=JSON.parse(await rc(Xn(e,"package.json"),"utf-8")),n=!!t.devDependencies?.["simple-git-hooks"],r=!!t["simple-git-hooks"];if(!n||!r)return!1}catch{return!1}try{return await Ge("pnpm",["exec","simple-git-hooks"],e),!0}catch{return $.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as ut from"@clack/prompts";import oe from"picocolors";function pi(e,t){t.dockerComposeGenerated&&!t.dockerAvailable&&ut.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];if(n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),t.dockerComposeGenerated){let i=e.dockerServices.map(a=>qe[a].label).join(", ");n.push(`pnpm infra ${oe.dim(`# ${i}`)}`)}if(n.push(`pnpm dev ${oe.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(oe.dim("Fill in remaining TODO values in .env"))),ut.note(n.join(`
|
|
1316
|
+
`),oe.yellow("Start Development")),t.dockerComposeGenerated){let i=[];i.push(`App ${oe.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${oe.cyan("http://localhost:3010")}`),e.dockerServices.includes("mailpit")&&i.push(`Mailpit ${oe.cyan("http://localhost:8025")}`),e.dockerServices.includes("inngest")&&i.push(`Inngest ${oe.cyan("http://localhost:8288")}`),ut.note(i.join(`
|
|
1317
|
+
`),oe.yellow("Dev Tools"))}let r=[],o=oc(e);o.length>0&&r.push(`Set in production: ${oe.dim(o.join(", "))}`),r.push("pnpm db:setup # Apply the database schema"),r.push(ic(e)),ut.note(r.join(`
|
|
1318
|
+
`),oe.yellow("Deployment"))}function oc(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 ic(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function mt(e){let n=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function He(e,t){let n=mt(e),r=mt(t);if(!n||!r)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function sn(e,t){return e.versions.find(n=>n.version===t)?.cli}function li(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:mt(e)===null}function cn(e,t,n="2.0.0"){if(li(n))return{ok:!0};let r=sn(e,e.latest);return!r||mt(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 di(e,t,n="2.0.0"){if(li(n))return{ok:!0};let r=sn(e,t);return!r||mt(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 dc from"picocolors";var uc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function mc(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 ui(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 ee("--frontend <type>","frontend framework").choices([...$e])).addOption(new ee("--architecture <type>","fullstack or separate").choices([...Ye])).addOption(new ee("--payment <provider>","payment provider").choices([...We])).addOption(new ee("--email <provider>","email provider").choices([...Xe])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new ee("--billing-scope <scope>","billing scope (requires --org)").choices([...et])).option("--blog","enable blog").option("--no-blog","disable blog").option("--email-tracking","enable email analytics (open/click tracking + admin analytics page)").option("--no-email-tracking","disable email analytics").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--desktop-auto","auto-trigger the desktop release workflow on CI success (default: manual-only)").option("--no-desktop-auto","manual-only desktop releases (workflow_dispatch)").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion + MCP server").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - a daemon your users install to run their own AI subscriptions for this app (shared repo or vendored)").option("--no-companion","exclude the backend companion feature").addOption(new ee("--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 ee("--currency <code>","default currency for billing").choices([...he])).addOption(new ee("--deploy <target>","deployment target").choices([...ye])).addOption(new ee("--database <provider>","database provider").choices([...we])).addOption(new ee("--cache <provider>","cache provider").choices([...ve])).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 ee("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ee("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await fc(t?{...n,apiKey:t}:n)})}async function fc(e){let t=performance.now();lr("2.0.0");let n;try{n=Ar(e)}catch(E){A.cancel(T(E)),process.exit(1)}let r=A.spinner(),o;try{o=await rt({apiKey:e.apiKey,prompt:!e.yes})}catch(E){A.cancel(T(E)),process.exit(1)}e.demo&&zn(o)!==uc&&(A.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=be(o),a,s=async()=>{a=await Re(i);let E=cn(a,"init");if(!E.ok)throw new Error(E.message);return{latestVersion:a.latest,selectedVersion:a.latest,desktopAllowed:a.entitlements?.desktopAllowed??!0}};r.start("Verifying access...");let u,g,l=!0;try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),Me(o)}catch(E){if(r.stop("Access verification failed."),E instanceof V&&E.status===401){e.yes&&(A.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),A.log.warning("Invalid API key."),o=await Et(),i=be(o),r.start("Verifying access...");try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),Me(o)}catch(M){r.stop("Access verification failed."),A.cancel(M instanceof V&&M.status===401?"Invalid API key.":T(M)),process.exit(1)}}else A.cancel(T(E)),process.exit(1)}A.log.success(`Latest version: ${u}`),n.desktop===!0&&!l&&(A.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let m;e.yes?m=Pr(l?n:{...n,desktop:!1}):m=await Rr(n,{desktopAllowed:l});let w;r.start("Activating license...");try{let E=e.demo&&m.baseUrl?await mc(m.baseUrl):crypto.randomUUID(),M=()=>({frontend:m.frontend,version:g,installId:E,projectName:m.projectName,options:Cr(m)}),W;try{W=await An(i,M())}catch(j){let K=Ht(j);if(!K?.lastAllowedVersion||!a)throw j;r.stop("License activation failed.");let L=di(a,K.lastAllowedVersion);if(L.ok||(A.cancel(`${K.message} ${L.message}`),process.exit(1)),e.yes){let B=sn(a,K.lastAllowedVersion);A.cancel(`${K.message} Re-run ${B?`npx generatesaas@${B} init`:"init"} without --yes to continue with v${K.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let k=await A.confirm({message:`Your update window has ended. Continue with v${K.lastAllowedVersion} (the last version your license covers)?`});(A.isCancel(k)||!k)&&(A.cancel("Setup cancelled."),process.exit(0)),g=K.lastAllowedVersion,r.start(`Activating license for v${g}...`),W=await An(i,M())}w={token:W.token,keyHash:zn(o),installId:W.installId??E},r.stop("License activated.")}catch(E){r.stop("License activation failed."),A.cancel(T(E)),process.exit(1)}let v=lc(m.projectDir);if(ac(v)&&sc(v).length>0)if(e.yes)A.log.info(`Directory ${v} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let M=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(M)||M==="cancel")&&(A.cancel("Setup cancelled."),process.exit(0)),M==="overwrite"&&cc(v,{recursive:!0,force:!0})}let x={...m,projectDir:v,version:g,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await zt(i,g,v),r.stop("Template downloaded.")}catch(E){r.stop("Download failed."),A.cancel(T(E)),process.exit(1)}let Y;r.start("Generating project files...");try{if({dockerComposeGenerated:Y}=await on(x),!e.demo){let E=await Be(v);await p(pc(v,Gt),JSON.stringify(E,null," ")+`
|
|
1319
|
+
`),await Qo(v,v)}await ni(v,x.aiTools),await Xo(x,w),r.stop("Project files generated.")}catch(E){r.stop("Generation failed."),A.cancel(T(E)),process.exit(1)}await oi(v);let ne=await ii(v);ne&&x.demo!==!0&&e.dbMigration!==!1&&await ai(v),await si(v),ne&&await ci(v);let fe=Ke("docker"),Oe=En(x).map(E=>E.key).filter(E=>!x.credentials?.[E]);pi(x,{pnpmInstalled:ne,dockerComposeGenerated:Y,dockerAvailable:fe,skippedCredentials:Oe}),dr(),A.log.info(dc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as er}from"fs";import{readFile as tr}from"fs/promises";import{join as ft,resolve as Sc}from"path";import*as P from"@clack/prompts";import q from"picocolors";import{mkdtemp as gc,rm as hc}from"fs/promises";import{tmpdir as yc}from"os";import{join as wc}from"path";async function Zn(e,t,n,r){let o=await gc(wc(yc(),"generatesaas-stage-"));try{await zt(e,t,o),await on({...n,projectDir:o}),await Jn(o,r)}finally{await hc(o,{recursive:!0,force:!0})}}import{readFile as vc,rm as kc}from"fs/promises";import{join as Qn}from"path";var mi=Qn(J,"companion-release.json"),bc=["apps/companion/","packages/companion-protocol/","packages/agent-core-types/","packages/agent-core/","scripts/companion-export/"];async function fi(e){let t;try{t=await vc(Qn(e,mi),"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 gi(e){try{return await kc(Qn(e,mi)),!0}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function hi(e){return e.some(t=>bc.some(n=>t.startsWith(n)))}function wi(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=Sc(n.cwd??process.cwd()),i=ft(o,Ie),a;try{a=JSON.parse(await tr(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 rt()}catch(l){P.cancel(T(l)),process.exit(1)}let u=be(s),g=P.spinner();try{g.start("Verifying access...");let l;try{l=await Re(u)}catch(k){throw k instanceof V&&k.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):k}let m=cn(l,"update");if(!m.ok)throw new Error(m.message);g.stop("Access verified."),Me(s),g.start("Fetching latest skill files...");let w=await Or(u,l.latest);await Wn(o,w.skillMd,w.scripts,a.aiTools);let v=Yn(a.aiTools);if(g.stop("Skills updated."),P.log.success(`Skill files installed to ${q.cyan(v.length.toString())} locations.`),a.version===l.latest){P.log.info(`Already on the latest version (${a.version}).`);return}let x=JSON.stringify(a);Sr(a),Er(a),await Ec(a,Ir(a),r);let Y=gr(a),ne=hr(a),fe=JSON.stringify(ne)!==x;if(a=ne,a.licenseToken)try{let k=await Dr(u,{currentToken:a.licenseToken,newVersion:l.latest});a.licenseToken=k.token,k.licenseKeyHash&&(a.licenseKeyHash=k.licenseKeyHash),await p(i,JSON.stringify(a,null," ")+`
|
|
1320
|
+
`),fe=!1,P.log.success("License refreshed.")}catch(k){let B=Ht(k);B&&(P.cancel(B.message),process.exit(1)),P.log.warn("License refresh skipped.")}fe&&await p(i,JSON.stringify(a,null," ")+`
|
|
1321
|
+
`);let _e=Wo(a,o),Oe=ft(o,Tr);g.start(`Staging v${l.latest} (shaped for your config)...`),await Zn(u,l.latest,_e,Oe),g.stop("Template staged.");let{text:E,title:M}=await Ac(u,l,a.version);E&&P.note(E,M);let W=ft(o,Gt),j=ft(o,Kt),K=!er(j),L=!er(W);if(K){if(g.start("Building baseline template (one-time migration)..."),await Zn(u,a.version,_e,j),L){let k=await Be(j);await p(W,JSON.stringify(k,null," ")+`
|
|
1322
|
+
`)}if(g.stop("Baseline template stored."),!L){let k=await Rc(W,j);k>0&&P.log.warn(`Rebuilt baseline differs from the original for ${k} 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(L){g.start("Computing baseline template hashes...");let k=await Be(j);await p(W,JSON.stringify(k,null," ")+`
|
|
1323
|
+
`),g.stop("Baseline hashes computed.")}if(await p(ft(o,_r),JSON.stringify({currentVersion:a.version,targetVersion:l.latest,changelog:E,stagedAt:new Date().toISOString(),...Y.length>0?{newOptions:Y}:{},...r?{mode:r}:{}},null," ")+`
|
|
1324
|
+
`),P.log.info(`Update staged: ${q.cyan(a.version)} \u2192 ${q.cyan(l.latest)}`),a.aiTools&&a.aiTools.length>0){let k=a.aiTools[0],B=wt[k].label;P.log.info(`Open your project in ${q.cyan(B)} and ask: ${q.cyan("'update my GenerateSaaS project'")}`)}else P.log.info(`Ask your AI coding assistant to ${q.cyan("'update my GenerateSaaS project'")}.`);if(a.companion===!0)try{if(pe(a)==="vendored"){let k=await fi(o);if(k){let B=await Pc(W,Oe);hi(B)&&P.log.warn(`Companion: vendored daemon changed since your published v${k.version} - run pnpm companion:publish (your users auto-update once tagged)`)}}else await gi(o)&&P.log.info("Companion: removed the stale vendored publish state (.generatesaas/companion-release.json) - this project points at a shared companion.")}catch(k){P.log.warn(`Companion re-release check skipped: ${T(k)}`)}a.desktop===!0&&er(ft(o,"apps/tauri"))&&P.log.warn(`Desktop: the app moved to an Electron shell (${q.cyan("apps/electron")}). Your project still has the old Tauri shell (${q.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${q.cyan("/desktop/updates")}.`)}catch(l){g.stop("Failed."),P.cancel(`Update failed: ${T(l)}`),process.exit(1)}})}async function Ec(e,t,n){if(t.kind==="none")return;if(t.kind==="daemon-materialized"){P.log.info(`Desktop: your app now bundles its own companion daemon. This update adds its source to your repo (${q.cyan("apps/companion")}, branded ${q.cyan(e.companionName??"")}) and about 106MB to each packaged build. Nothing to publish - it ships inside the app.`);return}let r=Ic[t.kind];n==="auto"&&(P.cancel(`${r.message}
|
|
1325
|
+
|
|
1326
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${q.cyan("generatesaas update")} without ${q.cyan("auto")} and answer it.`),process.exit(1));let o=await P.select({message:r.message,options:r.options});P.isCancel(o)&&(P.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e),Sn(e)}function yi(e){e.desktop=!1,e.desktopAutoRelease=!1}var Ic={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also adds the companion daemon's source to your repo (apps/companion, ~106MB per packaged build) and makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal, no bundled daemon"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack and bundles a companion daemon. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack, the Terminal, and the bundled companion daemon (apps/companion, ~106MB per packaged build)"},{value:{apply:e=>{e.ai=!1,e.companion=!1,e.mcpServer=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion and the MCP server - they both require AI"},{value:{apply:yi},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]},"shared-source-contradiction":{message:"Your desktop app bundles a companion daemon, but your project points its web install flow at a shared companion. A bundled app needs its own daemon. How should this resolve?",options:[{value:{apply:e=>{e.companionSource="vendored"}},label:"Vendor your own companion",hint:"its source moves into your repo (apps/companion) and your web install UI switches to it - your users install yours, not the shared one"},{value:{apply:yi},label:"Drop the desktop app",hint:"your website keeps its AI surface and its shared companion exactly as they are today"}]}};async function Ac(e,t,n){let r=t.latest,o=t.versions.filter(a=>He(a.version,n)>0&&He(a.version,r)<=0).sort((a,s)=>He(a.version,s.version));if(o.length<=1)return{text:await In(e,r),title:`Changelog v${r}`};let i=[];for(let a of o){let s=null;try{s=await In(e,a.version)}catch{s=null}let u=a.date?` (${a.date.slice(0,10)})`:"",g=a.breaking?" [BREAKING]":"";i.push(`# v${a.version}${u}${g}
|
|
1327
|
+
|
|
1328
|
+
${s??"_No changelog available for this release._"}`)}return{text:i.join(`
|
|
1329
|
+
|
|
1330
|
+
`),title:`Changelog v${n} \u2192 v${r}`}}async function Pc(e,t){let n=JSON.parse(await tr(e,"utf-8")),r=await Be(t),o=[];for(let[i,a]of Object.entries(r))n[i]!==a&&o.push(i);for(let i of Object.keys(n))i in r||o.push(i);return o}async function Rc(e,t){let n=JSON.parse(await tr(e,"utf-8")),r=await Be(t),o=0;for(let[i,a]of Object.entries(n))ot(i)||r[i]!==a&&o++;for(let i of Object.keys(r))i in n||o++;return o}import*as te from"@clack/prompts";import ie from"picocolors";import{readFile as xc}from"fs/promises";import{join as Tc,resolve as _c}from"path";function vi(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=_c(t.cwd??process.cwd()),r=Tc(n,Ie),o;try{o=JSON.parse(await xc(r,"utf-8"))}catch{te.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let i=[`Version: ${ie.cyan(o.version)}`,`Frontend: ${ie.cyan(o.frontend)}`,o.deploymentTarget?`Deploy target: ${ie.cyan(o.deploymentTarget)}`:null,o.databaseProvider?`Database: ${ie.cyan(o.databaseProvider)}`:null,o.cacheProvider?`Cache: ${ie.cyan(o.cacheProvider)}`:null,o.aiTools&&o.aiTools.length>0?`AI tools: ${ie.cyan(o.aiTools.join(", "))}`:null].filter(Boolean).join(`
|
|
1331
|
+
`);te.note(i,ie.bold("Project Status"));let a=te.spinner();a.start("Checking for updates...");try{let s=await rt(),u=be(s),l=(await Re(u)).latest;o.version===l?(a.stop("Up to date."),te.log.success(`Already on the latest version (${ie.green(l)})`)):(a.stop("Update available."),te.log.warning(`Update available: ${ie.yellow(o.version)} \u2192 ${ie.green(l)}`),te.log.info(`Open this project in your AI coding agent and ask it to ${ie.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(s){a.stop("Check failed."),s instanceof V&&s.status===401?te.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):te.log.warning(`Could not check for updates: ${T(s)}`)}})}import{readFile as Oc}from"fs/promises";import*as D from"@clack/prompts";import C from"picocolors";function Cc(){return process.env.GENERATESAAS_API_KEY??St()}function Dc(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 Nc(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function $c(e){switch(e.verdict){case"licensed":return D.log.success(`${C.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return D.log.success(`${C.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 D.log.error(`${C.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 D.log.error(`${C.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${C.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return D.log.error(`${C.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return D.log.warn(`${C.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function ki(e,t){let n=process.env.GENERATESAAS_API_URL??bt,r=Cc();e.start("Cross-referencing license records...");try{let o=r?Dc(await Nr(n,r,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Nc(await Pn(n,{token:t.token,domain:t.domain}));return e.stop(`${C.green("Checked")} - records cross-referenced`),$c(o)}catch(o){return e.stop(`${C.yellow("Skipped")} - ${T(o)}`),null}}function Lc(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 nr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function bi(e){D.note([`License ID: ${C.cyan(String(e.lid??"unknown"))}`,`Version: ${C.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${nr(e.pat)}`,`Last updated: ${nr(e.uat)}`,`Expires: ${nr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1332
|
+
`),C.yellow("License Details"))}function Uc(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 Si(e){let t=D.spinner(),n=null,r="no candidates";for(let a of Uc(e)){t.start(`Checking ${a}...`);try{let s=await fetch(a);if(!s.ok){r=`${a} returned ${s.status}`,t.stop(`${C.yellow("Not here")} - ${r}`);continue}let u=(await s.text()).trim();if(!u||u.split(".").length!==3){r=`${a} did not return a JWT`,t.stop(`${C.yellow("Not here")} - ${r}`);continue}n=u,t.stop(`${C.green("Found")} - license endpoint responded`);break}catch(s){r=`${a}: ${T(s)}`,t.stop(`${C.yellow("Unreachable")} - ${r}`)}}if(n===null){D.log.warn(`No license endpoint found (last: ${r}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let a=Ei(e);return a?await ki(t,{domain:a})??!1:!1}let o;try{o=Lc(n)}catch{return D.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let a=process.env.GENERATESAAS_API_URL??bt,s=await Pn(a,{token:n});if(s.valid)t.stop(`${C.green("Valid")} - signature verified`);else return t.stop(`${C.red("Invalid")} - ${s.reason}`),!1}catch{return t.stop(`${C.yellow("Skipped")} - could not reach verification service`),D.log.warn("Signature not verified. Displaying unverified claims:"),bi(o),!1}return bi(o),await ki(t,{token:n,lkh:typeof o.lkh=="string"?o.lkh:void 0,nid:typeof o.nid=="string"?o.nid:void 0,domain:Ei(e)})??!0}function Ei(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function Ii(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&&(D.cancel("Provide a URL or --file <path>."),process.exit(1)),n.file){let o=(await Oc(n.file,"utf-8")).split(`
|
|
1333
|
+
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));o.length===0&&(D.cancel("No URLs found in file."),process.exit(1));let i=0;for(let a of o)await Si(a)&&i++,D.log.info("");D.log.success(`${i}/${o.length} sites verified.`)}else await Si(t)||process.exit(1)})}import{existsSync as jc,rmSync as Mc}from"fs";import*as ae from"@clack/prompts";function Ai(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){jc(ke)?(Mc(ke),ae.log.success("API key removed.")):ae.log.info("No API key configured.");return}let n=St();n?ae.log.info(`Current API key: ****${n.slice(-4)}`):ae.log.info("No API key configured.");let r=await Et(),o=be(r),i=ae.spinner();i.start("Verifying API key...");try{await Re(o),i.stop("API key verified."),Me(r),ae.log.success("API key saved.")}catch(a){i.stop("Verification failed."),a instanceof V&&a.status===401?ae.cancel("Invalid API key."):ae.cancel(T(a)),process.exit(1)}})}import{existsSync as pn,rmSync as Vc,readFileSync as or,writeFileSync as Pi}from"fs";import{join as ze}from"path";import*as G from"@clack/prompts";var Fc=["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"],Bc=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1430
1334
|
`,` licenseHeartbeatFunction,
|
|
1431
1335
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1432
1336
|
`,` .route("/license", licenseRoutes)
|
|
1433
|
-
`]}];function
|
|
1434
|
-
`).filter(
|
|
1435
|
-
`);return r===n?!1:(
|
|
1337
|
+
`]}];function Gc(e){return(e&&e.length>0?e.map(n=>_t[n]):Object.values(_t)).map(n=>ze(n,qn))}function rr(e){return pn(e)?(Vc(e,{recursive:!0}),!0):!1}function Kc(e,t){if(!pn(e))return!1;let n=or(e,"utf-8"),r=n;for(let o of t)r=r.replace(o,"");return r===n?!1:(Pi(e,r,"utf-8"),!0)}function Hc(e){let t=ze(e,".gitignore");if(!pn(t))return!1;let n=or(t,"utf-8"),r=n.split(`
|
|
1338
|
+
`).filter(o=>!o.includes(".generatesaas")).join(`
|
|
1339
|
+
`);return r===n?!1:(Pi(t,r,"utf-8"),!0)}function Ri(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),n=ze(t,Ie),r;try{r=JSON.parse(or(n,"utf-8"))}catch{G.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let o=await G.text({message:'Type "eject" to confirm (this cannot be undone):',validate:s=>{if(s!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(G.isCancel(o)&&(G.cancel("Eject cancelled."),process.exit(0)),r.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.licenseToken}`},body:JSON.stringify({event:"eject",version:r.version,frontend:r.frontend}),signal:AbortSignal.timeout(5e3)}),G.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{G.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let i=[],a=[];for(let s of Gc(r.aiTools))rr(ze(t,s))&&i.push(s);for(let s of Fc)rr(ze(t,s))&&i.push(s);rr(ze(t,J))&&i.push(J+"/");for(let s of Bc){let u=ze(t,s.file);Kc(u,s.removals)?a.push(s.file):pn(u)&&G.log.warn(`Could not auto-modify ${s.file} - manually remove license/heartbeat references.`)}Hc(t)&&a.push(".gitignore");for(let s of i)G.log.info(`Deleted ${s}`);for(let s of a)G.log.info(`Modified ${s}`);G.log.success("Ejected successfully. This project is now fully standalone.")})}var Je=new zc().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.0.0").addHelpText("after",`
|
|
1436
1340
|
Examples:
|
|
1437
1341
|
$ generatesaas init Interactive setup
|
|
1438
1342
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1439
1343
|
$ generatesaas status Check for updates
|
|
1440
1344
|
$ generatesaas auth Set or update API key
|
|
1441
|
-
`);
|
|
1345
|
+
`);ui(Je);wi(Je);vi(Je);Ii(Je);Ai(Je);Ri(Je);Je.parseAsync().catch(e=>{xi.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|