generatesaas 1.20.1 → 1.21.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 +330 -188
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as Rs}from"commander";import*as _i from"@clack/prompts";import{existsSync as Ha,readdirSync as za,rmSync as Ya}from"fs";import{join as qa,resolve as Ja}from"path";import{Option as Q}from"commander";import*as A from"@clack/prompts";import*as ft from"@clack/prompts";import Gt from"picocolors";function xn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";ft.intro(Gt.bgYellow(Gt.black(t)))}function Cn(){ft.outro(Gt.yellow("Happy building!"))}import*as g from"@clack/prompts";import y from"picocolors";var et={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},tt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},gt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},ht={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},yt={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},De={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}},nt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Se={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var ne={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},G={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},re={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},rt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],it=[{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)."}],Dn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function vt(e){let t=G[e.databaseProvider].managed,n=re[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 Ee=["nextjs","nuxt"],Ne=["fullstack","separate"],Le=["stripe","polar","none"],$e=["smtp","ses","resend"],je=["postgres","redis","inngest","mailpit"],Ue=["claude-code","cursor","codex","gemini-cli","windsurf"],Me=["user","organization"],ce=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],le=["node","vercel"],pe=["postgres","neon","supabase"],de=["redis","upstash"],Ve=["google","github","facebook","discord","x"];function kt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function wt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function C(e){return e instanceof Error?e.message:String(e)}var Nn=["companion","mcpServer","rag"];function zt(e){if(!Nn.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 Ln(e){return Nn.some(n=>e[n]===!0)&&(e.ai=!0),e}function $n(e){let t={};if(e.name!==void 0){if(!wt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.frontend!==void 0){if(!Ee.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ee.join(", ")}`);t.frontend=e.frontend}if(e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.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),zt(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=Ht(e.docker,je,"docker service")),e.aiTools!==void 0&&(t.aiTools=Ht(e.aiTools,Ue,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=Ht(e.socialProviders,Ve,"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 jn(e){let t=e.projectName??ue.projectName,n=e.projectDir??`./${t}`,r=e.appName??kt(t),i=e.deploymentTarget??ue.deploymentTarget,o=ne[i]?.edgeRuntime??!1,a=e.databaseProvider??(o?"neon":ue.databaseProvider),s=e.cacheProvider??(o?"upstash":ue.cacheProvider),p=e.emailProvider??(o?"resend":ue.emailProvider),f=e.dockerServices??(o?ue.dockerServices.filter(d=>d!=="postgres"&&d!=="redis"):ue.dockerServices),m={...ue,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:i,databaseProvider:a,cacheProvider:s,emailProvider:p,dockerServices:f};m.paymentProvider==="none"&&(m.credits=!1),m.multiTenancy||(m.billingScope="user"),m.ai||(m.aiByok=ue.aiByok);for(let d of rt){if(m.deploymentTarget!==d.target)continue;let v=m.databaseProvider===d.provider?"database":"cache";if(m.databaseProvider===d.provider||m.cacheProvider===d.provider)throw new Error(`Incompatible: --deploy ${d.target} + --${v} ${d.provider}. ${d.reason}`)}for(let d of it)if(m.architecture===d.architecture&&m.deploymentTarget===d.target)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);return m}function Ht(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 Yt(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 Un(e,t){let n=!1;e&&zt(e),g.log.info(y.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(!wt(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:kt(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(et),u=await g.select({message:"Frontend framework:",options:c.map(S=>({value:S,label:et[S].label,hint:et[S].hint}))});return E(u),u})();g.log.info(y.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:ne[u].label,hint:ne[u].hint}))});E(c),s=c}let p=e?.architecture?it.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let f=new Set(it.filter(c=>c.target===s).map(c=>c.architecture)),m=Ne.filter(c=>!f.has(c)),d=e?.architecture??await(async()=>{if(m.length===1){let u=m[0];return g.log.info(`Auto-selected ${tt[u].label} architecture (only compatible option for ${ne[s].label}).`),u}n=!0;let c=await g.select({message:"Architecture:",options:m.map(u=>({value:u,label:tt[u].label,hint:tt[u].hint}))});return E(c),c})(),v=e?.databaseProvider??await(async()=>{n=!0;let c=pe.filter(S=>!rt.some(F=>F.target===s&&F.provider===S));if(c.length===1){let S=c[0];return g.log.info(`Auto-selected ${G[S].label} (only compatible option for ${ne[s].label}).`),S}let u=await g.select({message:"Database provider:",options:c.map(S=>({value:S,label:G[S].label,hint:G[S].hint}))});return E(u),u})(),b=e?.cacheProvider??await(async()=>{n=!0;let c=de.filter(S=>!rt.some(F=>F.target===s&&F.provider===S));if(c.length===1){let S=c[0];return g.log.info(`Auto-selected ${re[S].label} (only compatible option for ${ne[s].label}).`),S}let u=await g.select({message:"Cache provider:",options:c.map(S=>({value:S,label:re[S].label,hint:re[S].hint}))});return E(u),u})();if(ne[s]?.edgeRuntime){let c=Dn.map(u=>` - ${u}`).join(`
|
|
3
|
-
`);g.note(c,"Unavailable on edge runtime")}g.log.info(
|
|
4
|
-
`),u=[` Deploy target: ${
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`))}}async function
|
|
11
|
-
`)}function
|
|
12
|
-
- **Payments:** ${
|
|
2
|
+
import{Command as Va}from"commander";import*as Ci from"@clack/prompts";import{existsSync as ia,readdirSync as oa,rmSync as sa}from"fs";import{join as aa,resolve as ca}from"path";import{Option as ee}from"commander";import*as E from"@clack/prompts";import*as ft from"@clack/prompts";import zt from"picocolors";function Dn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";ft.intro(zt.bgYellow(zt.black(t)))}function Nn(){ft.outro(zt.yellow("Happy building!"))}import*as g from"@clack/prompts";import h from"picocolors";var tt={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},nt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},gt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},ht={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},yt={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},Le={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}},rt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Ae={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}},Y={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},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"}]}},it=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],ot=[{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)."}],Ln=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function vt(e){let t=Y[e.databaseProvider].managed,n=ie[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var ce={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 Ie=["nextjs","nuxt"],$e=["fullstack","separate"],je=["stripe","polar","none"],Ue=["smtp","ses","resend"],Me=["postgres","redis","inngest","mailpit"],Ve=["claude-code","cursor","codex","gemini-cli","windsurf"],Be=["user","organization"],le=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],pe=["node","vercel"],de=["postgres","neon","supabase"],ue=["redis","upstash"],Fe=["google","github","facebook","discord","x"];function bt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function kt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function L(e){return e instanceof Error?e.message:String(e)}var $n=["companion","mcpServer","rag"];function qt(e){if(!$n.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 jn(e){return $n.some(n=>e[n]===!0)&&(e.ai=!0),e}function Un(e){let t={};if(e.name!==void 0){if(!kt(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(!Ie.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ie.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),qt(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=Yt(e.docker,Me,"docker service")),e.aiTools!==void 0&&(t.aiTools=Yt(e.aiTools,Ve,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=Yt(e.socialProviders,Fe,"social provider")),e.currency!==void 0){if(!le.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${le.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!pe.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${pe.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!de.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${de.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ue.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ue.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 me={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 Mn(e){let t=e.projectName??me.projectName,n=e.projectDir??`./${t}`,r=e.appName??bt(t),i=e.deploymentTarget??me.deploymentTarget,o=re[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":me.databaseProvider),a=e.cacheProvider??(o?"upstash":me.cacheProvider),d=e.emailProvider??(o?"resend":me.emailProvider),m=e.dockerServices??(o?me.dockerServices.filter(f=>f!=="postgres"&&f!=="redis"):me.dockerServices),p={...me,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:d,dockerServices:m};p.paymentProvider==="none"&&(p.credits=!1),p.multiTenancy||(p.billingScope="user"),p.ai||(p.aiByok=me.aiByok);for(let f of it){if(p.deploymentTarget!==f.target)continue;let w=p.databaseProvider===f.provider?"database":"cache";if(p.databaseProvider===f.provider||p.cacheProvider===f.provider)throw new Error(`Incompatible: --deploy ${f.target} + --${w} ${f.provider}. ${f.reason}`)}for(let f of ot)if(p.architecture===f.architecture&&p.deploymentTarget===f.target)throw new Error(`Incompatible: --architecture ${f.architecture} + --deploy ${f.target}. ${f.reason}`);return p}function Yt(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 S(e){g.isCancel(e)&&(g.cancel("Setup cancelled."),process.exit(0))}function Jt(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=ce[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 Vn(e,t){let n=!1;e&&qt(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(!kt(u))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),i=e?.appName??await(async()=>{n=!0;let c=await g.text({message:"App name:",initialValue:bt(r),validate:u=>{if(!u?.trim())return"App name is required."}});return S(c),c})(),o=e?.projectDir??await(async()=>{n=!0;let c=await g.text({message:"Project location:",initialValue:`./${r}`});return S(c),c==="."?process.cwd():c})(),s=e?.frontend??await(async()=>{n=!0;let c=Object.keys(tt),u=await g.select({message:"Frontend framework:",options:c.map(k=>({value:k,label:tt[k].label,hint:tt[k].hint}))});return S(u),u})();g.log.info(h.bold("Infrastructure"));let a=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await g.select({message:"Deployment target:",options:pe.map(u=>({value:u,label:re[u].label,hint:re[u].hint}))});S(c),a=c}let d=e?.architecture?ot.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let m=new Set(ot.filter(c=>c.target===a).map(c=>c.architecture)),p=$e.filter(c=>!m.has(c)),f=e?.architecture??await(async()=>{if(p.length===1){let u=p[0];return g.log.info(`Auto-selected ${nt[u].label} architecture (only compatible option for ${re[a].label}).`),u}n=!0;let c=await g.select({message:"Architecture:",options:p.map(u=>({value:u,label:nt[u].label,hint:nt[u].hint}))});return S(c),c})(),w=e?.databaseProvider??await(async()=>{n=!0;let c=de.filter(k=>!it.some(G=>G.target===a&&G.provider===k));if(c.length===1){let k=c[0];return g.log.info(`Auto-selected ${Y[k].label} (only compatible option for ${re[a].label}).`),k}let u=await g.select({message:"Database provider:",options:c.map(k=>({value:k,label:Y[k].label,hint:Y[k].hint}))});return S(u),u})(),b=e?.cacheProvider??await(async()=>{n=!0;let c=ue.filter(k=>!it.some(G=>G.target===a&&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[a].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 S(u),u})();if(re[a]?.edgeRuntime){let c=Ln.map(u=>` - ${u}`).join(`
|
|
3
|
+
`);g.note(c,"Unavailable on edge runtime")}g.log.info(h.bold("Features"));let A=e?.paymentProvider??await(async()=>{n=!0;let c=await g.select({message:"Payment provider:",options:je.map(u=>({value:u,label:gt[u].label,hint:gt[u].hint}))});return S(c),c})(),J=e?.defaultCurrency??await(async()=>{if(A==="none")return"USD";n=!0;let c=await g.select({message:"Default currency:",options:le.map(u=>({value:u,label:u,hint:Ae[u].name}))});return S(c),c})(),V=e?.emailProvider??await(async()=>{n=!0;let c=await g.select({message:"Email provider:",options:Ue.map(u=>({value:u,label:ht[u].label,hint:ht[u].hint}))});return S(c),c})(),R=e?.multiTenancy??await(async()=>{n=!0;let c=await g.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return S(c),c})(),ae=R?e?.billingScope??"user":"user";if(R&&e?.billingScope===void 0){n=!0;let c=await g.select({message:"Billing scope:",options:Be.map(u=>({value:u,label:yt[u].label,hint:yt[u].hint}))});S(c),ae=c}let B=e?.blog??await(async()=>{n=!0;let c=await g.confirm({message:"Enable blog?",initialValue:!0});return S(c),c})(),v=e?.docs??await(async()=>{n=!0;let c=await g.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return S(c),c})(),P=t?.desktopAllowed!==!1,_=e?.desktop??(P?await(async()=>{n=!0;let c=await g.confirm({message:"Include the desktop app? (apps/tauri - cross-platform, built with Tauri, device-auth)",initialValue:!1});return S(c),c})():(g.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),z=_?e?.desktopAutoRelease??await(async()=>{n=!0;let c=await g.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,I=e?.ai??await(async()=>{n=!0;let c=await g.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion + MCP server)",initialValue:!1});return S(c),c})(),T=I?e?.rag??await(async()=>{n=!0;let c=await g.confirm({message:"Add a server-side knowledge base (keyword search over your knowledge/ docs)?",initialValue:!1});return S(c),c})():!1,Se=I?e?.companion??await(async()=>{n=!0;let c=await g.confirm({message:"Add the companion daemon? A small program your users 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.",initialValue:!1});return S(c),c})():!1,Rn=I?e?.mcpServer??await(async()=>{n=!0;let c=await g.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,_n=I?e?.aiByok??await(async()=>{n=!0;let c=await g.confirm({message:"AI BYOK mode? (end-users bring their own provider key; no = operator-keyed, credit-metered)",initialValue:!0});return S(c),c})():!0,On=e?.revenueSharing??await(async()=>{n=!0;let c=await g.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return S(c),c})(),xn=A==="none"?!1:e?.credits??await(async()=>{n=!0;let c=await g.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return S(c),c})(),ut=e?.socialProviders??await(async()=>{n=!0;let c=Fe.map(k=>({value:k,label:ce[k].label,hint:`requires ${ce[k].envVars.map(G=>G.name).join(" / ")}`})),u=await g.multiselect({message:"Which social login providers should the sign-in screen show?",options:c,initialValues:[],required:!1});return S(u),u})();g.log.info(h.bold("Tooling"));let Kt=e?.dockerServices??await(async()=>{n=!0;let c=[...Me].filter(H=>H!=="mailpit");V==="smtp"&&c.push("mailpit");let u=c.map(H=>({value:H,label:Le[H].label,hint:Le[H].hint})),k=u.map(H=>H.value).filter(H=>!(H==="postgres"&&(w==="neon"||w==="supabase")||H==="redis"&&b==="upstash")),G=await g.multiselect({message:"Which services should we set up in Docker for you?",options:u,initialValues:k,required:!1});return S(G),G})(),Gt=e?.aiTools??await(async()=>{n=!0;let c=Ve.map(k=>({value:k,label:rt[k].label})),u=await g.multiselect({message:"Which AI coding tools do you use?",options:c,initialValues:[],required:!1});return S(u),u})(),Ht=e?.demo,mt=Jt({databaseProvider:w,cacheProvider:b,paymentProvider:A,emailProvider:V,socialProviders:ut,demo:Ht}),et={};if(mt.length>0&&n){g.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of mt)if(n=!0,c.secret){let u=await g.password({message:c.message,mask:"*"});S(u),typeof u=="string"&&u.trim()&&(et[c.key]=u.trim())}else{let u=await g.text({message:c.message,placeholder:c.placeholder});S(u),typeof u=="string"&&u.trim()&&(et[c.key]=u.trim())}}if(n){let c=[` Name: ${h.cyan(r)}`,` App name: ${h.cyan(i)}`,` Location: ${h.cyan(o)}`,` Frontend: ${h.cyan(tt[s].label)}`,` Architecture: ${h.cyan(nt[f].label)}`].join(`
|
|
4
|
+
`),u=[` Deploy target: ${h.cyan(re[a]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Y[w].label)}`,` Cache: ${h.cyan(ie[b].label)}`,Kt.length>0?` Docker: ${h.cyan(Kt.map(Ee=>Le[Ee].label).join(", "))}`:` Docker: ${h.dim("none")}`].filter(Boolean).join(`
|
|
5
|
+
`),k=[A!=="none"?` Payment: ${h.cyan(gt[A].label)} (${J})`:` Payment: ${h.dim("none")}`,` Credits: ${xn?h.cyan("Yes"):h.dim("No")}`,` AI features: ${I?h.cyan("Yes"):h.dim("No")}`,...I?[` AI mode: ${h.cyan(_n?"BYOK":"Operator-keyed (credits)")}`,` RAG knowledge: ${T?h.cyan("Yes"):h.dim("No")}`,` Companion: ${Se?h.cyan("Yes"):h.dim("No")}`,` MCP server: ${Rn?h.cyan("Yes"):h.dim("No")}`]:[],` Email: ${h.cyan(ht[V].label)}`,` Multi-tenancy: ${R?h.cyan("Yes")+` (billing: ${yt[ae].label})`:h.dim("No")}`,` Blog: ${B?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${v?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${_?h.cyan("Yes"):h.dim("No")}`,..._?[` Releases: ${h.cyan(z?"Automatic on CI":"Manual only")}`]:[],` Rev. sharing: ${On?h.cyan("Yes"):h.dim("No")}`,ut.length>0?` Social login: ${h.cyan(ut.map(Ee=>ce[Ee].label).join(", "))}`:` Social login: ${h.dim("none")}`,Gt.length>0?` AI tools: ${h.cyan(Gt.map(Ee=>rt[Ee].label).join(", "))}`:` AI tools: ${h.dim("none")}`].join(`
|
|
6
|
+
`),G=[h.bold("Project"),c,"",h.bold("Infrastructure"),u,"",h.bold("Features"),k];if(mt.length>0){let Ee=mt.map(Cn=>{let Di=et[Cn.key]?h.green("provided"):h.dim("skipped");return` ${Cn.key}: ${Di}`}).join(`
|
|
7
|
+
`);G.push("",h.bold("Credentials"),Ee)}g.note(G.join(`
|
|
8
|
+
`),"Summary");let H=await g.confirm({message:"Proceed with these settings?"});(g.isCancel(H)||!H)&&(g.cancel("Setup cancelled."),process.exit(0))}return{projectName:r,appName:i,projectDir:o,frontend:s,architecture:f,deploymentTarget:a,databaseProvider:w,cacheProvider:b,paymentProvider:A,emailProvider:V,multiTenancy:R,billingScope:ae,blog:B,docs:v,desktop:_,desktopAutoRelease:z,desktopAi:_?e?.desktopAi??!1:!1,ai:I,rag:T,companion:Se,mcpServer:Rn,aiByok:_n,revenueSharing:On,credits:xn,dockerServices:Kt,aiTools:Gt,socialProviders:ut,defaultCurrency:J,...Object.keys(et).length>0?{credentials:et}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...Ht!==void 0?{demo:Ht}:{}}}import{createReadStream as Ki}from"fs";import{mkdir as Gi}from"fs/promises";import{Readable as Hi}from"stream";import{pipeline as qn}from"stream/promises";import{extract as zi}from"tar";import{join as Pe}from"path";import{homedir as Ni}from"os";var st=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",W=".generatesaas",he=Pe(W,"manifest.json"),Bn=Pe(W,"hashes.json"),wt=Pe(W,"template-hashes.json"),St=Pe(W,"template"),Fn=Pe(W,"staging"),Kn=Pe(W,"staging.json"),fe=Pe(Ni(),".generatesaas");var M=class extends Error{constructor(n,r,i){super(r);this.status=n;this.body=i}status;body;name="ApiError"};function ge(e){return{apiKey:e,baseUrl:st}}async function ye(e,t,n){let r=`${e.baseUrl}${t}`,i=await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new M(i.status,o,s)}return i}import{existsSync as Li,readFileSync as $i,writeFileSync as ji,mkdirSync as Ui}from"fs";import{dirname as Mi}from"path";import*as ve from"@clack/prompts";function at(){if(!Li(fe))return null;try{let e=JSON.parse($i(fe,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&ve.log.warning(`Found old GitHub token in ${fe}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Te(e){Ui(Mi(fe),{recursive:!0}),ji(fe,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function Ke(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=at();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 ct()}async function ct(){let e=await ve.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return ve.isCancel(e)&&(ve.cancel("Setup cancelled."),process.exit(0)),e.trim()}async function be(e){return 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 ye(e,"/versions")).json()}async function Wt(e,t){try{return await(await ye(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(n){if(n instanceof M&&n.status===404)return null;throw n}}async function Gn(e,t){return await(await ye(e,`/skill/${encodeURIComponent(t)}`)).json()}function Et(e){if(!(e instanceof M)||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 Hn(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,docs:e.docs,desktop:e.desktop,credits:e.credits,revenueSharing:e.revenueSharing,socialProviders:e.socialProviders,aiTools:e.aiTools,currency:e.defaultCurrency}}async function Xt(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await ye(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function zn(e,t){return await(await ye(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Zt(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 Yn(e,t,n){let r=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${r.status}`)}return await r.json()}var Qt=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),en=new Set(["pnpm-lock.yaml"]);function Ge(e){if(tn(e))return!0;for(let t of e.split("/"))if(en.has(t))return!0;return!1}var Vi=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","README.md","TODO.md","OVERVIEW.md"]),Bi=["scripts/knowledge-corpus.ts","scripts/knowledge-corpus.test.ts","scripts/knowledge-lint.ts","scripts/knowledge-build.ts","scripts/dev-ai-setup.ts","scripts/docs-lint.ts"],Fi=["docs/superpowers","packages/cli","packages/cli-api","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(Qt.has(n))return!0;if(Bi.includes(e))return!1;if(Vi.has(t[0]))return!0;for(let n of Fi)if(e===n||e.startsWith(n+"/"))return!0;return!1}async function At(e,t,n){await Gi(n,{recursive:!0});let r=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(r){await qn(Ki(r),Jn(n));return}let i=await ye(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let o=Hi.fromWeb(i.body);await qn(o,Jn(n))}function Jn(e){return zi({cwd:e,strip:1,filter:t=>{let n=t.replace(/^[^/]+\//,"");return n?!tn(n):!0},sync:!1})}import{access as Yi,readdir as qi,readFile as It,rm as nn,writeFile as Pt}from"fs/promises";import{join as ke}from"path";var Ji=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function Zn(e){await Promise.all(Ji.map(t=>nn(ke(e,t),{recursive:!0,force:!0})))}var Wi="packages/config/src/blog.ts";async function Qn(e){let t=ke(e,Wi),n=await It(t,"utf-8"),r=Wn(Wn(n,"blogCategories",t),"blogAuthors",t);await Pt(t,r)}function Wn(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 er(e){let t=ke(e,"packages/i18n/translations"),n;try{n=await qi(t)}catch{return}for(let r of n){let i=ke(t,r,"web.json"),o;try{o=await It(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await Pt(i,JSON.stringify(s,null," ")+`
|
|
10
|
+
`))}}var Xi="packages/config/src/ai/tasks.ts";async function tr(e){let t=ke(e,Xi),n=await It(t,"utf-8"),r=n.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(r===n)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);await Pt(t,r)}var Xn="apps/tauri/resources/ai-skills/example-skill";async function nr(e){let t=ke(e,Xn);try{await Yi(t)}catch{throw new Error(`removeExampleSkill: expected the demo skill at ${Xn}, but it was missing (boilerplate drift). The desktop AI layer is kept for this build, so the skill must exist.`)}await nn(t,{recursive:!0})}async function rr(e,t){t.includes("claude-code")||await nn(ke(e,".claude"),{recursive:!0,force:!0})}async function ir(e,t){let n=ke(e,".claude","settings.json"),r;try{r=await It(n,"utf8")}catch{return}let i=JSON.parse(r);delete i.alwaysThinkingEnabled,delete i.enableAllProjectMcpServers,i.env&&(delete i.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(i.env).length===0&&delete i.env),i.permissions?.allow&&(i.permissions.allow=i.permissions.allow.filter(o=>Zi(o,t))),await Pt(n,JSON.stringify(i,null," ")+`
|
|
11
|
+
`)}function Zi(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as or}from"path";import{mkdir as Qi,readdir as eo,rm as to,rmdir as no,writeFile as ro}from"fs/promises";import{dirname as Tt,join as io,relative as oo,sep as so}from"path";function Re(e){return e.split(so).join("/")}async function Rt(e){await Qi(e,{recursive:!0})}async function l(e,t){await Rt(Tt(e)),await ro(e,t,"utf-8")}async function rn(e,t){await to(e,{force:!0});let n=Tt(e);for(;n!==t&&n!==Tt(n);){try{await no(n)}catch{return}n=Tt(n)}}async function _e(e,t,n){let r=[],i=await eo(e,{withFileTypes:!0});for(let o of i){let s=io(e,o.name),a=Re(oo(t,s));n(a)||(o.isDirectory()?r.push(...await _e(s,t,n)):o.isFile()&&r.push(s))}return r}var ao={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},co={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},lo={redis:"Redis",upstash:"Upstash Redis"},po={node:"Node.js / Docker",vercel:"Vercel"},uo={stripe:"Stripe",polar:"Polar"};function mo(e){let t=e.frontend==="nuxt",n=t?"Nuxt 4":"Next.js 16",r=t?"apps/web-nuxt":"apps/web-next",i=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",o=e.architecture==="fullstack",s=o?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",a=o?`Mounted inside \`${r}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",d=lo[e.cacheProvider],m=po[e.deploymentTarget],p=e.paymentProvider==="none"?"":`
|
|
12
|
+
- **Payments:** ${uo[e.paymentProvider]}`,f=e.desktop?", and the desktop app (built with Tauri) under `docs/desktop/`":"",w=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",b=t?"**Navigation:** always use `localePath()` for paths (hardcoded paths break non-default locales); `await navigateTo()` in SSR.":"**Navigation:** `next/link` for links; `redirect()` from `next/navigation` for programmatic redirects in Server Components.";return`# AGENTS.md
|
|
13
13
|
|
|
14
14
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
15
15
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -35,13 +35,13 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
35
35
|
|
|
36
36
|
## Stack
|
|
37
37
|
|
|
38
|
-
- **Frontend:** ${n} ${
|
|
39
|
-
- **API:** Hono, RPC-typed. ${
|
|
40
|
-
- **Database:** Drizzle ORM + ${
|
|
41
|
-
- **Cache + jobs:** ${
|
|
42
|
-
- **Auth:** Better Auth${
|
|
43
|
-
- **Email:** ${
|
|
44
|
-
- **Deploy:** ${
|
|
38
|
+
- **Frontend:** ${n} ${s}
|
|
39
|
+
- **API:** Hono, RPC-typed. ${a}
|
|
40
|
+
- **Database:** Drizzle ORM + ${ao[e.databaseProvider]}
|
|
41
|
+
- **Cache + jobs:** ${d} + Inngest
|
|
42
|
+
- **Auth:** Better Auth${p}
|
|
43
|
+
- **Email:** ${co[e.emailProvider]}
|
|
44
|
+
- **Deploy:** ${m}
|
|
45
45
|
|
|
46
46
|
## Where things live (extend these - don't reinvent)
|
|
47
47
|
|
|
@@ -52,11 +52,11 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
52
52
|
- \`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
53
|
- \`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
54
|
- \`${r}\` - the ${n} app (${i}).
|
|
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/\`${
|
|
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/\`${f}.
|
|
56
56
|
|
|
57
57
|
## Knowledge
|
|
58
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
|
|
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\`.
|
|
60
60
|
|
|
61
61
|
## Code style
|
|
62
62
|
|
|
@@ -73,7 +73,7 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
73
73
|
|
|
74
74
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
75
75
|
- **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. ${
|
|
76
|
+
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${w} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
77
77
|
- ${b}
|
|
78
78
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
79
79
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
@@ -85,16 +85,16 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
85
85
|
## This project
|
|
86
86
|
|
|
87
87
|
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
|
|
88
|
+
`}async function sr(e){await l(or(e.projectDir,"AGENTS.md"),mo(e)),await l(or(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
89
|
+
`)}import{join as fo}from"path";var go={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ho(e){let t=e.appName.trim()||e.projectName,n=e.frontend==="nuxt",r=n?"Nuxt 4":"Next.js 16",i=n?"apps/web-nuxt":"apps/web-next",o=go[e.databaseProvider],s=vt(e),a=e.architecture==="fullstack"?`${r} app at \`${i}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${r} app at \`${i}/\` and a separate Hono backend at \`apps/backend/\`.`,d=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
90
90
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
91
91
|
- API: http://localhost:3010
|
|
92
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
93
|
-
`:"",
|
|
92
|
+
- Inngest dev server: http://127.0.0.1:8288`,m=s?`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
93
|
+
`:"",p=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
94
|
|
|
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).${
|
|
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).${s?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,f=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
96
|
|
|
97
|
-
${
|
|
97
|
+
${a}
|
|
98
98
|
|
|
99
99
|
## Stack
|
|
100
100
|
|
|
@@ -112,11 +112,11 @@ pnpm install
|
|
|
112
112
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
113
113
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
114
114
|
# reference. All apps load the single root \`.env\`.
|
|
115
|
-
${
|
|
115
|
+
${m}pnpm db:setup # first run: create the database schema (idempotent)
|
|
116
116
|
pnpm dev
|
|
117
117
|
\`\`\`
|
|
118
118
|
|
|
119
|
-
${
|
|
119
|
+
${d}
|
|
120
120
|
|
|
121
121
|
## Build your SaaS
|
|
122
122
|
|
|
@@ -129,14 +129,14 @@ App-level configuration lives in \`packages/config/src/index.ts\`. Translation s
|
|
|
129
129
|
## Database
|
|
130
130
|
|
|
131
131
|
\`\`\`bash
|
|
132
|
-
pnpm db:setup #
|
|
133
|
-
pnpm -F @repo/database push # push schema changes only
|
|
132
|
+
pnpm db:setup # apply the database schema (idempotent)
|
|
133
|
+
pnpm -F @repo/database push # push schema changes only
|
|
134
134
|
pnpm -F @repo/database migrate # run migrations
|
|
135
135
|
pnpm -F @repo/database studio # open Drizzle Studio
|
|
136
136
|
pnpm auth:generate # regenerate Better Auth schema after config changes
|
|
137
137
|
\`\`\`
|
|
138
138
|
|
|
139
|
-
${
|
|
139
|
+
${p}
|
|
140
140
|
|
|
141
141
|
## Removing the GenerateSaaS license
|
|
142
142
|
|
|
@@ -148,12 +148,13 @@ pnpm dlx generatesaas eject
|
|
|
148
148
|
|
|
149
149
|
## Updates
|
|
150
150
|
|
|
151
|
-
${
|
|
152
|
-
`}async function
|
|
151
|
+
${f}
|
|
152
|
+
`}async function ar(e){await l(fo(e.projectDir,"README.md"),ho(e))}import{readFile as yo}from"fs/promises";import{join as _t}from"path";var on="https://generatesaas.com";async function vo(e,t){let n=_t(e,"apps/tauri/src-tauri/tauri.conf.json"),r=JSON.parse(await yo(n,"utf8")),i=r.app?.security?.csp;if(typeof i!="string"||!i.includes(on))throw new Error(`Cannot neutralize ${n}: the upstream origin "${on}" was not found in app.security.csp. The boilerplate config may have drifted.`);if(r.app.security.csp=i.split(on).join(t),!r.bundle?.macOS||!("signingIdentity"in r.bundle.macOS))throw new Error(`Cannot neutralize ${n}: expected bundle.macOS.signingIdentity to remove. The boilerplate config may have drifted.`);delete r.bundle.macOS.signingIdentity,await l(n,JSON.stringify(r,null,2)+`
|
|
153
|
+
`)}function bo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function ko(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"app"}function wo(e,t){let n=ko(e);return{appId:`${t.split(".").reverse().join(".")}.${n.replace(/-/g,"")}`,productName:e,protocol:n}}async function cr(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=e.paymentProvider!=="none",r=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",o=bo(i),s=e.demo?"false":"true",a=e.demo?`
|
|
153
154
|
support: {
|
|
154
155
|
enableInDev: true,
|
|
155
156
|
crisp: { websiteId: "7e221cec-ed61-46b7-b1b4-8cbc16557cca" }
|
|
156
|
-
},`:"",
|
|
157
|
+
},`:"",d=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",m=wo(t,o),p=`{ enabled: ${e.rag} }`,f=e.companion?'{ enabled: true, clientId: "companion" }':'{ enabled: false, clientId: "companion" }',w=`{ enabled: ${e.mcpServer} }`,b=`import type { AppConfig } from "@repo/config/types";
|
|
157
158
|
import { desktopConfig } from "./desktop.mjs";
|
|
158
159
|
import { tenancyConfig } from "./tenancy-flags.mjs";
|
|
159
160
|
|
|
@@ -164,7 +165,7 @@ export const config: AppConfig = {
|
|
|
164
165
|
fullSiteName: "${t}",
|
|
165
166
|
domain: "${i}",
|
|
166
167
|
baseUrl: process.env.BASE_URL ?? "${r}",
|
|
167
|
-
indexable: ${
|
|
168
|
+
indexable: ${s},
|
|
168
169
|
logo: {
|
|
169
170
|
main: "/images/logo.svg",
|
|
170
171
|
square: "/images/logo-square.svg"
|
|
@@ -222,7 +223,7 @@ export const config: AppConfig = {
|
|
|
222
223
|
prefix: "key_"
|
|
223
224
|
},
|
|
224
225
|
apiDocs: true,
|
|
225
|
-
performanceMonitor: { enabled: ${
|
|
226
|
+
performanceMonitor: { enabled: ${d} },
|
|
226
227
|
notifications: {
|
|
227
228
|
enabled: true,
|
|
228
229
|
maxPerUser: 100,
|
|
@@ -240,7 +241,7 @@ export const config: AppConfig = {
|
|
|
240
241
|
enabled: true,
|
|
241
242
|
provider: "turnstile",
|
|
242
243
|
siteKey: "0x4AAAAAACJo9y9FxH8lqkGu"
|
|
243
|
-
}`:"{ enabled: false }"},${
|
|
244
|
+
}`:"{ enabled: false }"},${a}
|
|
244
245
|
currency: ${e.demo?`{
|
|
245
246
|
// Demo mirrors the boilerplate's showcase config so geo\u2192currency
|
|
246
247
|
// switching can be demonstrated. Real users get a single-currency
|
|
@@ -260,7 +261,7 @@ export const config: AppConfig = {
|
|
|
260
261
|
}`:`{
|
|
261
262
|
base: "${e.defaultCurrency}",
|
|
262
263
|
list: [
|
|
263
|
-
{ symbol: "${
|
|
264
|
+
{ symbol: "${Ae[e.defaultCurrency].symbol}", name: "${Ae[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Ae[e.defaultCurrency].place}", space: ${Ae[e.defaultCurrency].space} }
|
|
264
265
|
],
|
|
265
266
|
countryMap: {
|
|
266
267
|
default: "${e.defaultCurrency}"
|
|
@@ -305,12 +306,12 @@ export const config: AppConfig = {
|
|
|
305
306
|
userSchedules: true
|
|
306
307
|
},
|
|
307
308
|
desktop: desktopConfig,
|
|
308
|
-
// Server-side
|
|
309
|
-
rag: ${
|
|
309
|
+
// Server-side keyword knowledge base over your knowledge/ docs. Off by default.
|
|
310
|
+
rag: ${p},
|
|
310
311
|
// Companion daemon (apps/companion): drives the user's subscription CLIs for this app. Off by default.
|
|
311
|
-
companion: ${
|
|
312
|
+
companion: ${f},
|
|
312
313
|
// Outward MCP server exposing the capability layer to external agents. Off by default.
|
|
313
|
-
mcpServer: ${
|
|
314
|
+
mcpServer: ${w},
|
|
314
315
|
seo: {
|
|
315
316
|
description: "Production-ready SaaS application",
|
|
316
317
|
foundingDate: "${new Date().getFullYear()}-01-01"
|
|
@@ -343,27 +344,29 @@ export * from "./pricing";
|
|
|
343
344
|
export * from "./roles";
|
|
344
345
|
export * from "./section-tabs";
|
|
345
346
|
export * from "./tenancy";
|
|
346
|
-
`,
|
|
347
|
-
// TypeScript config index reads it directly: the
|
|
348
|
-
//
|
|
349
|
-
// Edit these values once to rebrand - they are the same
|
|
350
|
-
// they live in committed config, not env. The config
|
|
351
|
-
// config.desktop.
|
|
347
|
+
`,A=_t(e.projectDir,"packages/config/src/index.ts");await l(A,b),await l(_t(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
348
|
+
// TypeScript config index reads it directly: the Tauri renderer, the apps/tauri
|
|
349
|
+
// sidecar engine, the Tauri identity sync (apps/tauri/scripts/sync-identity.mjs)
|
|
350
|
+
// and the release scripts. Edit these values once to rebrand - they are the same
|
|
351
|
+
// in dev and production, so they live in committed config, not env. The config
|
|
352
|
+
// index re-exports this as config.desktop.
|
|
352
353
|
|
|
353
354
|
export const desktopConfig = {
|
|
354
355
|
enabled: ${e.desktop},
|
|
355
|
-
appId: "${
|
|
356
|
-
productName: "${
|
|
357
|
-
protocol: "${
|
|
356
|
+
appId: "${m.appId}",
|
|
357
|
+
productName: "${m.productName}",
|
|
358
|
+
protocol: "${m.protocol}",
|
|
358
359
|
baseUrl: "${r}",
|
|
359
360
|
// Name of the app's data folder (created under the OS app-data dir). Where the app
|
|
360
361
|
// and its AI agents persist files - logs, gathered data, generated artifacts. Rename
|
|
361
362
|
// it freely; it is a plain folder name, not a path.
|
|
362
363
|
dataFolder: "data",
|
|
363
|
-
|
|
364
|
+
// Public base URL the release workflow uploads to; the Tauri updater polls
|
|
365
|
+
// \`<url>/latest.json\` and the stable installer download links live under it.
|
|
366
|
+
autoUpdate: { url: "https://cdn.${o}/tauri" },
|
|
364
367
|
agents: {
|
|
365
|
-
// Feature toggles only. Agents
|
|
366
|
-
//
|
|
368
|
+
// Feature toggles only. Agents live in the apps/tauri sidecar engine, registered
|
|
369
|
+
// through the @repo/agent-runtime registry - typed TypeScript wiring next to the
|
|
367
370
|
// markdown prompt files you tune.
|
|
368
371
|
enabled: ${e.desktopAi},
|
|
369
372
|
modelRegistry: { enabled: true },
|
|
@@ -383,8 +386,8 @@ export const desktopConfig = {
|
|
|
383
386
|
maxChatsPerAgent: 20
|
|
384
387
|
}
|
|
385
388
|
};
|
|
386
|
-
`),await l(
|
|
387
|
-
// TypeScript config index reads it directly (the
|
|
389
|
+
`),await l(_t(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
|
|
390
|
+
// TypeScript config index reads it directly (the Tauri renderer). Mirrors the
|
|
388
391
|
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
389
392
|
|
|
390
393
|
export const tenancyConfig = ${e.multiTenancy?`{
|
|
@@ -392,11 +395,8 @@ export const tenancyConfig = ${e.multiTenancy?`{
|
|
|
392
395
|
organizationLimit: 5,
|
|
393
396
|
billingScope: "${e.billingScope}"
|
|
394
397
|
}`:"{ multiTenant: false }"};
|
|
395
|
-
`),e.desktop&&await
|
|
396
|
-
|
|
397
|
-
updaterCacheDirName: ${f.protocol}-updater
|
|
398
|
-
`)}import{join as go}from"path";function ho(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function rn(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
|
|
399
|
-
`)}async function or(e){let t=go(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let d=`import type { PricingConfig } from "@repo/config/types";
|
|
398
|
+
`),e.desktop&&await vo(e.projectDir,new URL(r).origin)}import{join as So}from"path";function Eo(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function sn(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
|
|
399
|
+
`)}async function lr(e){let t=So(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let f=`import type { PricingConfig } from "@repo/config/types";
|
|
400
400
|
|
|
401
401
|
export const pricingConfig: PricingConfig = {
|
|
402
402
|
defaultPlan: "free",
|
|
@@ -425,7 +425,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
425
425
|
credits: { enabled: false },
|
|
426
426
|
products: { enabled: false, items: [] }
|
|
427
427
|
};
|
|
428
|
-
`;await l(t,
|
|
428
|
+
`;await l(t,f);return}let r=e.paymentProvider,i=Eo(r),o=e.credits,s=sn({credits:5,rateLimit:100,withCredits:o}),a=sn({credits:10,rateLimit:1e3,withCredits:o}),d=sn({credits:50,rateLimit:5e3,withCredits:o}),p=`import type { PricingConfig } from "@repo/config/types";
|
|
429
429
|
|
|
430
430
|
export const pricingConfig: PricingConfig = {
|
|
431
431
|
defaultPlan: "free",
|
|
@@ -449,7 +449,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
449
449
|
amounts: { ${n}: 0 }
|
|
450
450
|
}
|
|
451
451
|
],
|
|
452
|
-
${
|
|
452
|
+
${s}
|
|
453
453
|
},
|
|
454
454
|
{
|
|
455
455
|
id: "starter",
|
|
@@ -475,7 +475,7 @@ ${i}
|
|
|
475
475
|
anchorAmounts: { ${n}: 109 }
|
|
476
476
|
}
|
|
477
477
|
],
|
|
478
|
-
${
|
|
478
|
+
${a}
|
|
479
479
|
},
|
|
480
480
|
{
|
|
481
481
|
id: "pro",
|
|
@@ -506,7 +506,7 @@ ${i}
|
|
|
506
506
|
anchorAmounts: { ${n}: 349 }
|
|
507
507
|
}
|
|
508
508
|
],
|
|
509
|
-
${
|
|
509
|
+
${d}
|
|
510
510
|
}
|
|
511
511
|
],
|
|
512
512
|
${o?" credits: { enabled: true }":" credits: { enabled: false }"},
|
|
@@ -515,12 +515,12 @@ ${o?" credits: { enabled: true }":" credits: { enabled: false }"},
|
|
|
515
515
|
items: []
|
|
516
516
|
}
|
|
517
517
|
};
|
|
518
|
-
`;await l(t,
|
|
519
|
-
`)}function
|
|
520
|
-
`)}async function
|
|
521
|
-
`+
|
|
522
|
-
`+
|
|
523
|
-
image:
|
|
518
|
+
`;await l(t,p)}var Ao={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]};function Io(e){let t=ce[e];return t.envVars.map((n,r)=>({key:n.name,...r===0?{comment:`# TODO: Add your ${t.label} OAuth credentials`}:{}}))}var Po={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 He(e,t){return t?e.map(n=>{let r=t[n.key];return r?{...n,defaultValue:r,comment:void 0}:n}):e}function ze(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 an(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function dr(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function To(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 Ot(e,t,n,r){e.push(r==="example"?`${t}=`:`${t}=${n}`)}function pr(e,t){let n=t==="example"?void 0:e.credentials,{apiUrl:r,baseUrl:i}=dr(e),o=[];e.architecture==="separate"?o.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${r}`,`BASE_URL=${i}`):o.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),o.push("","# Database"),ze(He(Y[e.databaseProvider].envVars,n),o),o.push("","# Cache"),ze(He(ie[e.cacheProvider].envVars,n),o),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Ot(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Ot(o,"CONTENT_API_KEY",an(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Ot(o,"INNGEST_EVENT_KEY",an(32),t),Ot(o,"INNGEST_SIGNING_KEY",an(32),t),o.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(o.push("","# API Port (standalone backend)","API_PORT=3010"),o.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let s=Ao[e.emailProvider];if(s&&(o.push("","# Email"),ze(He(s,n),o)),e.paymentProvider!=="none"){let a=Po[e.paymentProvider];a&&(o.push("","# Payment"),ze(He(a,n),o))}if(e.socialProviders.length>0){o.push("","# Social auth");for(let a of e.socialProviders)ze(He(Io(a),n),o)}return e.demo&&(o.push("","# Captcha (Cloudflare Turnstile)"),ze(He([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],n),o)),o.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY="),o.push("","# AI base - 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="),o.push(""),o.join(`
|
|
519
|
+
`)}function Ro(e){let{apiUrl:t}=dr(e),n=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",r=["# API Configuration",`${n}=${t}`],i=To(e);return i&&e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${n}=${i.backend}`),r.push(""),r.join(`
|
|
520
|
+
`)}async function ur(e){let t=Ro(e);await l(`${e.projectDir}/.env`,t+`
|
|
521
|
+
`+pr(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
|
|
522
|
+
`+pr(e,"example"))}import{join as _o}from"path";async function mr(e){let t=[...e.dockerServices];if(Y[e.databaseProvider].managed&&(t=t.filter(o=>o!=="postgres")),ie[e.cacheProvider].managed&&(t=t.filter(o=>o!=="redis")),t.length===0)return!1;let n=[],r=[];t.includes("postgres")&&(n.push(` postgres:
|
|
523
|
+
image: postgres:18-alpine
|
|
524
524
|
ports:
|
|
525
525
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
526
526
|
environment:
|
|
@@ -563,8 +563,8 @@ ${n.join(`
|
|
|
563
563
|
volumes:
|
|
564
564
|
${r.join(`
|
|
565
565
|
`)}
|
|
566
|
-
`),await l(
|
|
567
|
-
`)}import{join as
|
|
566
|
+
`),await l(_o(e.projectDir,"infra/docker-compose.yml"),i),!0}import{join as Oo}from"path";function xo(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/tauri",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.companion){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Companion",command:`pnpm cli serve --url ${r}`,cwd:"${workspaceFolder}/apps/companion",skipFiles:["<node_internals>/**"]})}if(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 Co(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 fr(e){let t={version:"0.2.0",configurations:xo(e),compounds:Co(e)};await l(Oo(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
567
|
+
`)}import{join as Do}from"path";async function gr(e){if(e.architecture!=="separate")return;await l(Do(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
|
|
568
568
|
import app from "@repo/api";
|
|
569
569
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
570
570
|
|
|
@@ -595,12 +595,12 @@ bootstrap().catch((error) => {
|
|
|
595
595
|
logger.error("[Backend] Fatal error", error);
|
|
596
596
|
process.exit(1);
|
|
597
597
|
});
|
|
598
|
-
`)}import{readFile as
|
|
599
|
-
export const pool = db.$client
|
|
598
|
+
`)}import{readFile as No}from"fs/promises";import{join as Lo}from"path";var cn='import { drizzle } from "drizzle-orm/node-postgres";',ln=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
599
|
+
export const pool = db.$client;`,$o={postgres:{importLine:cn,instantiation:ln},neon:{importLine:`import { neon } from "@neondatabase/serverless";
|
|
600
600
|
import { drizzle } from "drizzle-orm/neon-http";`,instantiation:`const sql = neon(parsed.data.DATABASE_URL);
|
|
601
601
|
export const db = drizzle(sql, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
602
602
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
603
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
603
|
+
export const db = drizzle(client, { schema });`}};async function hr(e){let t=Lo(e.projectDir,"packages/database/src/index.ts"),n=await No(t,"utf-8");if(!n.includes(cn)||!n.includes(ln))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let r=$o[e.databaseProvider],i=n.replace(cn,r.importLine).replace(ln,r.instantiation);await l(t,i)}import{join as xt}from"path";async function yr(e){switch(e.cacheProvider){case"redis":await jo(e),await Uo(e);break;case"upstash":await Mo(e),await Vo(e);break}}async function jo(e){await l(xt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
604
604
|
import { Redis } from "ioredis";
|
|
605
605
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
606
606
|
import { env } from "./env";
|
|
@@ -729,7 +729,7 @@ export async function closeRedis() {
|
|
|
729
729
|
closed = true;
|
|
730
730
|
}
|
|
731
731
|
}
|
|
732
|
-
`)}async function
|
|
732
|
+
`)}async function Uo(e){await l(xt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
733
733
|
import { redis } from "./redis";
|
|
734
734
|
|
|
735
735
|
export class MutexTimeoutError extends Error {
|
|
@@ -766,7 +766,7 @@ export async function withMutex<T>(
|
|
|
766
766
|
await mutex.release();
|
|
767
767
|
}
|
|
768
768
|
}
|
|
769
|
-
`)}async function
|
|
769
|
+
`)}async function Mo(e){await l(xt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
770
770
|
import type { Store } from "hono-rate-limiter";
|
|
771
771
|
import { env } from "./env";
|
|
772
772
|
|
|
@@ -884,7 +884,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
884
884
|
|
|
885
885
|
/** No persistent connection to close with Upstash REST. */
|
|
886
886
|
export async function closeRedis(): Promise<void> {}
|
|
887
|
-
`)}async function
|
|
887
|
+
`)}async function Vo(e){await l(xt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
888
888
|
import { redis } from "./redis";
|
|
889
889
|
|
|
890
890
|
export class MutexTimeoutError extends Error {
|
|
@@ -929,7 +929,7 @@ export async function withMutex<T>(
|
|
|
929
929
|
await lock.release();
|
|
930
930
|
}
|
|
931
931
|
}
|
|
932
|
-
`)}async function
|
|
932
|
+
`)}async function vr(e){await l(`${e.projectDir}/packages/runtime/src/env.ts`,Bo(e))}function Bo(e){return`import { z } from "zod";
|
|
933
933
|
|
|
934
934
|
const EnvSchema = z.object({
|
|
935
935
|
NODE_ENV: z.enum(["development", "production"]).default("development"),
|
|
@@ -1050,13 +1050,13 @@ export const env = (() => {
|
|
|
1050
1050
|
const parsedApiUrl = new URL(env.API_URL);
|
|
1051
1051
|
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1052
1052
|
export const apiOrigin = parsedApiUrl.origin;
|
|
1053
|
-
`}import{readFile as
|
|
1054
|
-
`)}function
|
|
1055
|
-
`)}var
|
|
1056
|
-
`))}}import{readFile as
|
|
1057
|
-
`);let o=
|
|
1053
|
+
`}import{readFile as Fo}from"fs/promises";import{join as oe}from"path";var Ct={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function qe(e){let t=await Fo(e,"utf-8");return JSON.parse(t)}async function Je(e,t){await l(e,JSON.stringify(t,null," ")+`
|
|
1054
|
+
`)}function lt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function Ye(e,t,n,r=!1){let i=r?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=n}async function br(e){await Ko(e),await Go(e),await Ho(e),await zo(e),e.frontend==="nextjs"?await qo(e):await Yo(e)}async function Ko(e){let t=oe(e.projectDir,"packages/api/package.json"),n=await qe(t);lt(n,["sharp","@types/sharp"]),await Je(t,n)}async function Go(e){let t=oe(e.projectDir,"packages/runtime/package.json"),n=await qe(t);e.cacheProvider==="upstash"&&(lt(n,["ioredis","rate-limit-redis","redis-semaphore"]),Ye(n,"@upstash/redis",Ct["@upstash/redis"]),Ye(n,"@upstash/lock",Ct["@upstash/lock"])),await Je(t,n)}async function Ho(e){let t=oe(e.projectDir,"packages/database/package.json"),n=await qe(t);e.databaseProvider==="neon"?(lt(n,["pg","@types/pg"]),Ye(n,"@neondatabase/serverless",Ct["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(lt(n,["pg","@types/pg"]),Ye(n,"postgres",Ct.postgres)),await Je(t,n)}async function zo(e){if(e.architecture!=="separate")return;let t=oe(e.projectDir,"apps/backend/package.json"),n=await qe(t);e.deploymentTarget!=="node"&<(n,["@hono/node-server"]),await Je(t,n)}async function Yo(e){if(e.architecture!=="separate")return;let t=oe(e.projectDir,"apps/web-nuxt");await rn(oe(t,"server/api/[...paths].ts"),t);let n=oe(t,"package.json"),r=await qe(n),i=r.dependencies?.["@repo/api"];i&&(delete r.dependencies?.["@repo/api"],Ye(r,"@repo/api",i,!0)),await Je(n,r)}async function qo(e){if(e.architecture!=="separate")return;let t=oe(e.projectDir,"apps/web-next");await rn(oe(t,"app/api/[[...rest]]/route.ts"),t);let n=oe(t,"package.json"),r=await qe(n),i=r.dependencies?.["@repo/api"];i&&(delete r.dependencies?.["@repo/api"],Ye(r,"@repo/api",i,!0)),await Je(n,r)}import{readFile as wr}from"fs/promises";import{join as Sr}from"path";async function Er(e){let t=Sr(e.projectDir,"turbo.json"),n;try{n=await wr(t,"utf-8")}catch{return}let r=JSON.parse(n),i=r.tasks?.build;if(!i)return;let o=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",s=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),a=!1;if(Array.isArray(i.env)){let d=i.env.filter(m=>m!==o);d.length!==i.env.length&&(i.env=d,a=!0)}if(Array.isArray(i.outputs)){let d=i.outputs.filter(m=>!s.has(m));d.length!==i.outputs.length&&(i.outputs=d,a=!0)}a&&await l(t,JSON.stringify(r,null," ")+`
|
|
1055
|
+
`)}var Jo=["base.json","node.json","next.json"],kr="GenerateSaaS ";async function Ar(e){if(!e.demo)for(let t of Jo){let n=Sr(e.projectDir,"tooling/typescript",t),r;try{r=await wr(n,"utf-8")}catch{continue}let i=JSON.parse(r);typeof i.display!="string"||!i.display.startsWith(kr)||(i.display=i.display.slice(kr.length),await l(n,JSON.stringify(i,null," ")+`
|
|
1056
|
+
`))}}import{readFile as Wo,rm as Xo}from"fs/promises";import{existsSync as Ir}from"fs";import{join as Pr}from"path";async function Tr(e){if(e.frontend==="nuxt")return;let t=Pr(e.projectDir,"packages/i18n/package.json");if(!Ir(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await Wo(t,"utf-8")),r=!!(n.exports?.["./module"]??n.exports?.["./nuxt"]),i=!1;if(n.exports)for(let s of["./module","./nuxt"])s in n.exports&&(delete n.exports[s],i=!0);n.devDependencies&&"@nuxt/kit"in n.devDependencies&&(delete n.devDependencies["@nuxt/kit"],i=!0),i&&await l(t,JSON.stringify(n,null," ")+`
|
|
1057
|
+
`);let o=Pr(e.projectDir,"packages/i18n/nuxt");if(r&&!Ir(o))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${o} is missing - did the i18n Nuxt module move?`);await Xo(o,{recursive:!0,force:!0})}import{readFile as Rr,rm as Zo}from"fs/promises";import{join as pn}from"path";async function _r(e){e.cacheProvider==="upstash"&&await Promise.all([Qo(e.projectDir),es(e.projectDir),Zo(pn(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function Qo(e){let t=pn(e,"packages/runtime/tests/setup.ts"),n;try{n=await Rr(t,"utf-8")}catch{return}let r=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1058
1058
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1059
|
-
`);r!==n&&await l(t,r)}async function
|
|
1059
|
+
`);r!==n&&await l(t,r)}async function es(e){let t=pn(e,"packages/api/tests/setup.ts"),n;try{n=await Rr(t,"utf-8")}catch{return}let r=n;r=r.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1060
1060
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1061
1061
|
`),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",
|
|
1062
1062
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1077,114 +1077,256 @@ vi.mock("@upstash/lock", () => {
|
|
|
1077
1077
|
return { Lock };
|
|
1078
1078
|
});
|
|
1079
1079
|
|
|
1080
|
-
$1`),r!==n&&await l(t,r)}import{readdir as
|
|
1080
|
+
$1`),r!==n&&await l(t,r)}import{readdir as hn,readFile as $,rm as x}from"fs/promises";import{join as y}from"path";import{readFile as Nt,rm as ts}from"fs/promises";import{join as Dt}from"path";function ns(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function F(e,t,n="ai",r="stripDesktopAi"){let i=ns(n);if(e.match(i)===null)throw new Error(`${r}: expected gsaas ${n} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${n}-start`)||o.includes(`gsaas:${n}-end`))throw new Error(`${r}: an unbalanced gsaas ${n} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
|
|
1081
1081
|
|
|
1082
|
-
`)}async function
|
|
1083
|
-
`,"",`${t} meta.json ${n} nav entry`,i);let
|
|
1084
|
-
`).find(
|
|
1085
|
-
`,"",`${t} ai.mdx ${n} card`,i),o!==void 0){let
|
|
1086
|
-
`).find(b=>b.startsWith(
|
|
1087
|
-
`,"",`${t} ai.mdx ${o} hub-table row`,i)}}async function
|
|
1088
|
-
`,n=await
|
|
1089
|
-
`,"","internal router mcp import",n),await
|
|
1082
|
+
`)}async function O(e,t,n,r,i){let o=await Nt(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(o.indexOf(t,s+t.length)!==-1)throw new Error(`${i}: the ${r} seam appears more than once (boilerplate drift).`);await l(e,o.slice(0,s)+n+o.slice(s+t.length))}function we(e,t,n,r){if(!(t in e))throw new Error(`${r}: expected ${n} (boilerplate drift).`);delete e[t]}function Lt(e){return e.frontend==="nextjs"?"next":"nuxt"}async function $t(e,t,n,r,i,o){let s=Dt(e,"docs",t);await ts(Dt(s,`${n}.mdx`)),await O(Dt(s,"meta.json"),` "${n}",
|
|
1083
|
+
`,"",`${t} meta.json ${n} nav entry`,i);let a=Dt(s,"ai.mdx"),m=(await Nt(a,"utf-8")).split(`
|
|
1084
|
+
`).find(p=>p.includes(`href="${r}"`));if(m===void 0)throw new Error(`${i}: expected the ai.mdx card linking to ${r} (boilerplate drift).`);if(await O(a,`${m}
|
|
1085
|
+
`,"",`${t} ai.mdx ${n} card`,i),o!==void 0){let p=`| **${o}** |`,w=(await Nt(a,"utf-8")).split(`
|
|
1086
|
+
`).find(b=>b.startsWith(p));if(w===void 0)throw new Error(`${i}: expected the ai.mdx "${o}" hub-table row (boilerplate drift).`);await O(a,`${w}
|
|
1087
|
+
`,"",`${t} ai.mdx ${o} hub-table row`,i)}}async function jt(e){let t=`import { config } from "@repo/config";
|
|
1088
|
+
`,n=await Nt(e,"utf-8");if(!n.includes(t))return;let r=n.replace(t,""),i=r.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(i)||await l(e,r)}import{readFile as rs}from"fs/promises";import{join as is}from"path";async function dn(e){if(e.rag)return;let t=is(e.projectDir,"packages/config/src/index.ts"),n=await rs(t,"utf-8");if(!/rag:\s*\{\s*enabled:\s*false\s*\}/.test(n))throw new Error("stripRag: expected `config.rag` emitted with `enabled: false` for a rag-off build, but it was missing (generator drift).")}import{readFile as Or,rm as un}from"fs/promises";import{join as Oe}from"path";async function mn(e){if(e.mcpServer)return;let t=e.projectDir,n="stripMcpServer";await un(Oe(t,"packages/api/src/routes/internal/ai/mcp.ts")),await un(Oe(t,"packages/api/tests/routes/mcp.test.ts")),await un(Oe(t,"packages/auth/src/mcp.ts"));let r=Oe(t,"packages/api/src/routes/internal/index.ts");await O(r,`import mcpRoutes from "./ai/mcp";
|
|
1089
|
+
`,"","internal router mcp import",n),await O(r,'\n// Outward MCP server (`/mcp` + its OAuth `.well-known` discovery), gated on `config.mcpServer`.\n// Mounted at the API root so the discovery metadata sits at `{apiBasePath}/.well-known/...` where\n// an external agent probes it. Off by default, so the routes are absent entirely when disabled. It\n// is not chained into the typed router above: external agents (not the typed RPC client) call it,\n// so it needs no `AppType` inference, and gating it keeps the feature truly inert when off.\nif (config.mcpServer?.enabled) {\n app.route("/", mcpRoutes);\n}\n',"","internal router mcp mount",n),await jt(r);let i=Oe(t,"packages/auth/src/config.ts");await O(i,` magicLink,
|
|
1090
1090
|
mcp,
|
|
1091
1091
|
organization,`,` magicLink,
|
|
1092
|
-
organization,`,"auth config mcp plugin import",n),await
|
|
1092
|
+
organization,`,"auth config mcp plugin import",n),await O(i,` // Outward MCP server: turns Better Auth into an OAuth 2.1 provider so an
|
|
1093
1093
|
// external agent (Hermes/OpenClaw) can authenticate and drive the app's
|
|
1094
1094
|
// capability layer over MCP. Brings the oauthApplication/oauthAccessToken/
|
|
1095
1095
|
// oauthConsent tables (run \`pnpm auth:generate\` after toggling).
|
|
1096
1096
|
...(config.mcpServer?.enabled
|
|
1097
1097
|
? [mcp({ loginPage: \`\${config.baseUrl}\${config.routes.auth}/login\` })]
|
|
1098
1098
|
: []),
|
|
1099
|
-
`,"","auth config mcp plugin block",n);let o=
|
|
1100
|
-
`);let
|
|
1101
|
-
`);let
|
|
1102
|
-
`);let o=
|
|
1099
|
+
`,"","auth config mcp plugin block",n);let o=Oe(t,"packages/auth/package.json"),s=JSON.parse(await Or(o,"utf-8"));if(!s.exports)throw new Error(`${n}: expected an exports map in packages/auth/package.json (boilerplate drift).`);we(s.exports,"./mcp",'the "./mcp" export in packages/auth/package.json',n),await l(o,JSON.stringify(s,null," ")+`
|
|
1100
|
+
`);let a=Oe(t,"packages/api/package.json"),d=JSON.parse(await Or(a,"utf-8"));if(!d.dependencies)throw new Error(`${n}: expected dependencies in packages/api/package.json (boilerplate drift).`);we(d.dependencies,"@modelcontextprotocol/sdk","@modelcontextprotocol/sdk in packages/api dependencies",n),await l(a,JSON.stringify(d,null," ")+`
|
|
1101
|
+
`);let m=Lt(e);await $t(t,m,"companion-agent-mcp",`/${m}/companion-agent-mcp`,n,"MCP")}import{rm as X}from"fs/promises";import{join as Z}from"path";import{readFile as fn}from"fs/promises";import{join as We}from"path";async function xr(e,t){let n=We(e,"packages/api/src/routes/internal/index.ts");await l(n,F(await fn(n,"utf-8"),"internal router","companion",t)),await jt(n);let r=We(e,"packages/api/package.json"),i=JSON.parse(await fn(r,"utf-8"));if(!i.dependencies)throw new Error(`${t}: expected dependencies in packages/api/package.json (boilerplate drift).`);we(i.dependencies,"@repo/companion-protocol","@repo/companion-protocol in packages/api dependencies",t),await l(r,JSON.stringify(i,null," ")+`
|
|
1102
|
+
`);let o=We(e,"packages/api/src/ai/schedule-runner.ts");await l(o,F(await fn(o,"utf-8"),"schedule-runner.ts","companion",t));let s=We(e,"packages/api/src/ai/settings-store.ts");await O(s,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1103
1103
|
|
|
1104
|
-
`,"","settings-store.ts relay import",t),await
|
|
1104
|
+
`,"","settings-store.ts relay import",t),await O(s," * - 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 O(s," *\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 O(s," * @param opts - `allowCompanion` (default `true`) controls companion-key acceptance.\n","","settings-store.ts @param opts",t),await O(s,`export function validModelKey(
|
|
1105
1105
|
key: string | null | undefined,
|
|
1106
1106
|
opts: { allowCompanion?: boolean } = {}
|
|
1107
1107
|
): string | null {
|
|
1108
1108
|
`,`export function validModelKey(key: string | null | undefined): string | null {
|
|
1109
|
-
`,"settings-store.ts validModelKey signature",t),await
|
|
1109
|
+
`,"settings-store.ts validModelKey signature",t),await O(s,` if (
|
|
1110
1110
|
opts.allowCompanion !== false &&
|
|
1111
1111
|
config.companion?.enabled === true &&
|
|
1112
1112
|
parseCompanionKey(key) !== null
|
|
1113
1113
|
) {
|
|
1114
1114
|
return key;
|
|
1115
1115
|
}
|
|
1116
|
-
`,"","settings-store.ts companion-key branch",t);let
|
|
1117
|
-
`,"","task-run.ts relay import",t),await
|
|
1116
|
+
`,"","settings-store.ts companion-key branch",t);let a=We(e,"packages/api/src/ai/task-run.ts");await O(a,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1117
|
+
`,"","task-run.ts relay import",t),await O(a,`/** Whether a chain link is usable for a task run: present and not a companion (device) key. */
|
|
1118
1118
|
`,`/** Whether a chain link is usable for a task run: a present, non-empty key. */
|
|
1119
|
-
`,"task-run.ts usableTaskModelKey docstring",t),await
|
|
1119
|
+
`,"task-run.ts usableTaskModelKey docstring",t),await O(a,` return typeof key === "string" && key.length > 0 && parseCompanionKey(key) === null;
|
|
1120
1120
|
`,` return typeof key === "string" && key.length > 0;
|
|
1121
|
-
`,"task-run.ts usableTaskModelKey body",t),await
|
|
1121
|
+
`,"task-run.ts usableTaskModelKey body",t),await O(a,` * override, then the builder's \`defaults.web.model\`, then the acting user's account default -
|
|
1122
1122
|
* skipping companion (device-bound) links, which are valid for chat but never for a background
|
|
1123
1123
|
* task - and delegating the final resolution to {@link resolveChatRun}, which owns BYOK/platform
|
|
1124
|
-
`," * 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
|
|
1124
|
+
`," * 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 d=We(e,"packages/api/src/routes/internal/ai/tasks-router.ts");await O(d,` modelKey: validModelKey(override?.modelKey ?? null, { allowCompanion: false }),
|
|
1125
1125
|
`,` modelKey: validModelKey(override?.modelKey ?? null),
|
|
1126
|
-
`,"tasks-router.ts listTaskOverrides validModelKey",t),await
|
|
1126
|
+
`,"tasks-router.ts listTaskOverrides validModelKey",t),await O(d,` if (typeof body.modelKey === "string" && validModelKey(body.modelKey, { allowCompanion: false }) === null) {
|
|
1127
1127
|
`,` if (typeof body.modelKey === "string" && validModelKey(body.modelKey) === null) {
|
|
1128
|
-
`,"tasks-router.ts putTask validModelKey",t)}async function
|
|
1129
|
-
`)}async function
|
|
1130
|
-
`))}async function
|
|
1131
|
-
`)}}async function
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1128
|
+
`,"tasks-router.ts putTask validModelKey",t)}async function gn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await X(Z(t,"apps/companion"),{recursive:!0}),await X(Z(t,"packages/companion-protocol"),{recursive:!0}),e.desktop&&e.desktopAi||await X(Z(t,"packages/agent-runtime"),{recursive:!0}),await X(Z(t,"packages/api/src/relay"),{recursive:!0}),await X(Z(t,"packages/api/tests/relay"),{recursive:!0}),await X(Z(t,"packages/api/src/routes/internal/companion.ts")),await X(Z(t,"packages/api/src/routes/internal/companion-transport.ts")),await X(Z(t,"packages/api/src/routes/internal/companion-install.ts")),await X(Z(t,"packages/api/tests/routes/companion.test.ts")),await X(Z(t,"packages/api/tests/routes/companion-transport.test.ts")),await X(Z(t,"packages/api/tests/routes/companion-install.test.ts")),await xr(t,n);let r=Lt(e);await $t(t,r,"companion",`/${r}/companion`,n,"Companions")}var os=new Set(["ci.yml","tauri-release.yml"]),ss=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:units","playground:test:build"];async function Cr(e){let t=y(e.projectDir,".github/workflows"),n=await hn(t).catch(()=>[]);for(let r of n)os.has(r)||await x(y(t,r),{recursive:!0,force:!0})}async function Dr(e){let t=y(e.projectDir,"package.json"),n=await $(t,"utf-8"),r=JSON.parse(n),i=!1;if(r.scripts){for(let o of ss)o in r.scripts&&(delete r.scripts[o],i=!0);if(!vt(e))for(let o of["infra","infra:stop"])o in r.scripts&&(delete r.scripts[o],i=!0)}i&&await l(t,JSON.stringify(r,null," ")+`
|
|
1129
|
+
`)}async function Nr(e){let t=y(e.projectDir,"package.json"),n=await $(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," ")+`
|
|
1130
|
+
`))}async function Lr(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await x(y(e.projectDir,t),{recursive:!0,force:!0})}async function $r(e){e.docs||await x(y(e.projectDir,"apps/docs"),{recursive:!0})}async function jr(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await x(y(e.projectDir,t),{recursive:!0,force:!0}),await x(y(e.projectDir,"docs/index.mdx")),!e.desktop)await x(y(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!e.desktopAi){await x(y(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=y(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await $(n,"utf-8"));r.pages=r.pages.filter(i=>i!=="ai"),await l(n,`${JSON.stringify(r,null,2)}
|
|
1131
|
+
`)}}async function Ur(e){if(e.desktop)return;await x(y(e.projectDir,"apps/tauri"),{recursive:!0});let t=y(e.projectDir,"packages/i18n/translations");for(let n of await hn(t,{withFileTypes:!0}))n.isDirectory()&&await x(y(t,n.name,"desktop.json"),{force:!0});await x(y(e.projectDir,".github/workflows/tauri-release.yml"))}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 Mr(e){if(!e.desktop||e.desktopAi)return;let t=e.projectDir;await x(y(t,"apps/tauri/sidecar"),{recursive:!0}),await x(y(t,"apps/tauri/tsconfig.sidecar.json")),await x(y(t,"apps/tauri/tsup.sidecar.config.ts")),await x(y(t,"apps/tauri/tests/sidecar"),{recursive:!0}),await x(y(t,"apps/tauri/src-tauri/src/daemon.rs")),await x(y(t,"apps/tauri/scripts/stage-sidecar.mjs")),await x(y(t,"apps/tauri/scripts/sign-nested.mjs")),await x(y(t,"apps/tauri/resources/ai-skills"),{recursive:!0}),await x(y(t,"apps/tauri/src-tauri/resources"),{recursive:!0,force:!0});for(let s 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 x(y(t,s),{recursive:!0});for(let s 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 x(y(t,s));let n=y(t,"apps/tauri/package.json"),r=JSON.parse(await $(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 s of i){if(!r.dependencies||!(s in r.dependencies))throw new Error(`stripDesktopAi: expected ${s} in apps/tauri dependencies (boilerplate drift).`);delete r.dependencies[s]}for(let s of["@types/ws","tsup"]){if(!r.devDependencies||!(s in r.devDependencies))throw new Error(`stripDesktopAi: expected ${s} in apps/tauri devDependencies (boilerplate drift).`);delete r.devDependencies[s]}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)+`
|
|
1132
|
+
`),await fs(t);let o=y(t,"packages/i18n/translations");for(let s of await hn(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let a=y(o,s.name,"desktop.json"),d=await $(a,"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(a,JSON.stringify(m,null," ")+`
|
|
1133
|
+
`)}}var as=`/**
|
|
1134
|
+
* Assembles a full bridge over the injected {@link BridgeDeps} seams. Wires the control-info source,
|
|
1135
|
+
* the engine HTTP transport, the shared status store, the event hub, the host auth-token sync, the
|
|
1136
|
+
* native surface (registering the reconnect auth resync via the hub), and the ai surface (folding in
|
|
1137
|
+
* the native workspace picker). The four \`@tauri-apps\` primitives are injected so a bridge can be built
|
|
1138
|
+
* against fake transports in tests; this factory imports the real plugin functions directly, which the
|
|
1139
|
+
* shell webview satisfies.
|
|
1140
|
+
*
|
|
1141
|
+
* @param deps - The \`fetch\`, \`WebSocket\`, \`invoke\`, and \`listen\` seams.
|
|
1142
|
+
* @returns The assembled bridge and its status store.
|
|
1143
|
+
*/
|
|
1144
|
+
export function createBridge(deps: BridgeDeps): { bridge: Bridge; status: StatusStore } {
|
|
1145
|
+
const clientId = crypto.randomUUID()
|
|
1146
|
+
const source = createControlSource(deps)
|
|
1147
|
+
const http = createEngineHttp({ source, fetchFn: deps.fetchFn, clientId })
|
|
1148
|
+
const status = createStatusStore()
|
|
1149
|
+
const events = createEngineEvents({
|
|
1150
|
+
source,
|
|
1151
|
+
http,
|
|
1152
|
+
WebSocketCtor: deps.WebSocketCtor,
|
|
1153
|
+
clientId,
|
|
1154
|
+
status
|
|
1155
|
+
})
|
|
1156
|
+
const hostAuthSync = createHostAuthSync({ source, fetchFn: deps.fetchFn, clientId })
|
|
1157
|
+
const { native, pickWorkspace } = createNativeBridge({
|
|
1158
|
+
invoke: deps.invoke,
|
|
1159
|
+
listen: deps.listen,
|
|
1160
|
+
openUrl,
|
|
1161
|
+
isPermissionGranted,
|
|
1162
|
+
requestPermission,
|
|
1163
|
+
sendNotification: (options) => sendNotification(options),
|
|
1164
|
+
checkUpdate: () => check(),
|
|
1165
|
+
relaunch,
|
|
1166
|
+
openDialog: (options) => open(options),
|
|
1167
|
+
hostAuthSync,
|
|
1168
|
+
registerAuthResync: events.syncAuthToken,
|
|
1169
|
+
isDev: import.meta.env.DEV
|
|
1170
|
+
})
|
|
1171
|
+
const ai = createAiBridge({ http, events, pickWorkspace })
|
|
1172
|
+
return { bridge: { ...native, ai }, status }
|
|
1173
|
+
}`,cs=`/**
|
|
1174
|
+
* Assembles the native bridge over the injected Tauri command/event seams. The \`invoke\` and \`listen\`
|
|
1175
|
+
* primitives are injected so a bridge can be built against fakes in tests; this factory imports the
|
|
1176
|
+
* real plugin functions (opener / notification / updater / process / dialog) directly, which the
|
|
1177
|
+
* shell webview satisfies.
|
|
1178
|
+
*
|
|
1179
|
+
* @param deps - The \`invoke\` and \`listen\` seams.
|
|
1180
|
+
* @returns The assembled native bridge.
|
|
1181
|
+
*/
|
|
1182
|
+
export function createBridge(deps: {
|
|
1183
|
+
invoke: <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>
|
|
1184
|
+
listen: (event: string, handler: (event: { payload: unknown }) => void) => Promise<() => void>
|
|
1185
|
+
}): { bridge: Bridge } {
|
|
1186
|
+
const { native } = createNativeBridge({
|
|
1187
|
+
invoke: deps.invoke,
|
|
1188
|
+
listen: deps.listen,
|
|
1189
|
+
openUrl,
|
|
1190
|
+
isPermissionGranted,
|
|
1191
|
+
requestPermission,
|
|
1192
|
+
sendNotification: (options) => sendNotification(options),
|
|
1193
|
+
checkUpdate: () => check(),
|
|
1194
|
+
relaunch,
|
|
1195
|
+
openDialog: (options) => open(options),
|
|
1196
|
+
isDev: import.meta.env.DEV
|
|
1197
|
+
})
|
|
1198
|
+
return { bridge: native }
|
|
1199
|
+
}`,ls=`/** The four production seams: \`globalThis\` fetch/WebSocket + the real Tauri command/event primitives. */
|
|
1200
|
+
function productionDeps(): BridgeDeps {
|
|
1201
|
+
return {
|
|
1202
|
+
fetchFn: (input, init) => fetch(input, init),
|
|
1203
|
+
WebSocketCtor: WebSocket,
|
|
1204
|
+
invoke,
|
|
1205
|
+
listen: (event, handler) => tauriListen(event, handler)
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
let instance: { bridge: Bridge; status: StatusStore } | null = null
|
|
1210
|
+
|
|
1211
|
+
/** Builds the production bridge exactly once, on first use (never at module load). */
|
|
1212
|
+
function productionInstance(): { bridge: Bridge; status: StatusStore } {
|
|
1213
|
+
if (!instance) instance = createBridge(productionDeps())
|
|
1214
|
+
return instance
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/**
|
|
1218
|
+
* Forwards every property access to a lazily-built target, so importing this module triggers no
|
|
1219
|
+
* \`invoke\` / \`listen\` / socket work (the control source subscribes to Tauri events at construction).
|
|
1220
|
+
* The first property access builds and memoizes the instance; every later access returns the same
|
|
1221
|
+
* member (stable identities, so \`useSyncExternalStore(bridgeStatus.subscribe, ...)\` does not tear).
|
|
1222
|
+
*/
|
|
1223
|
+
function lazyForward<T extends object>(build: () => T): T {
|
|
1224
|
+
return new Proxy(Object.create(null) as T, {
|
|
1225
|
+
get: (_target, prop) => (build() as Record<PropertyKey, unknown>)[prop]
|
|
1226
|
+
})
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/** The production bridge singleton, lazily built on first property access. */
|
|
1230
|
+
export const bridge: Bridge = lazyForward(() => productionInstance().bridge)
|
|
1231
|
+
|
|
1232
|
+
/** The production status store feeding the reconnect indicator. */
|
|
1233
|
+
export const bridgeStatus: StatusStore = lazyForward(() => productionInstance().status)`,ps=`/** The two production seams: the real Tauri command/event primitives. */
|
|
1234
|
+
function productionDeps(): {
|
|
1235
|
+
invoke: <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>
|
|
1236
|
+
listen: (event: string, handler: (event: { payload: unknown }) => void) => Promise<() => void>
|
|
1237
|
+
} {
|
|
1238
|
+
return {
|
|
1239
|
+
invoke,
|
|
1240
|
+
listen: (event, handler) => tauriListen(event, handler)
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
let instance: { bridge: Bridge } | null = null
|
|
1245
|
+
|
|
1246
|
+
/** Builds the production bridge exactly once, on first use (never at module load). */
|
|
1247
|
+
function productionInstance(): { bridge: Bridge } {
|
|
1248
|
+
if (!instance) instance = createBridge(productionDeps())
|
|
1249
|
+
return instance
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/**
|
|
1253
|
+
* Forwards every property access to a lazily-built target, so importing this module triggers no
|
|
1254
|
+
* \`invoke\` / \`listen\` work. The first property access builds and memoizes the instance; every later
|
|
1255
|
+
* access returns the same member (stable identities).
|
|
1256
|
+
*/
|
|
1257
|
+
function lazyForward<T extends object>(build: () => T): T {
|
|
1258
|
+
return new Proxy(Object.create(null) as T, {
|
|
1259
|
+
get: (_target, prop) => (build() as Record<PropertyKey, unknown>)[prop]
|
|
1260
|
+
})
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** The production bridge singleton, lazily built on first property access. */
|
|
1264
|
+
export const bridge: Bridge = lazyForward(() => productionInstance().bridge)`,ds=`/// The control-server coordinates the renderer needs: the loopback URL (absent until the
|
|
1265
|
+
/// sidecar reports ready) and the bearer token (always present, minted at shell startup).
|
|
1266
|
+
#[derive(serde::Serialize)]
|
|
1267
|
+
struct ControlInfo {
|
|
1268
|
+
url: Option<String>,
|
|
1269
|
+
token: String,
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
/// Returns the current control-server URL and bearer. Callable before the sidecar is ready
|
|
1273
|
+
/// (\`url\` is \`None\` until then; \`token\` is always the minted control token).
|
|
1274
|
+
#[tauri::command]
|
|
1275
|
+
fn get_control_info(state: tauri::State<'_, daemon::DaemonHandle>) -> ControlInfo {
|
|
1276
|
+
let guard = state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
1277
|
+
ControlInfo {
|
|
1278
|
+
url: guard.url.clone(),
|
|
1279
|
+
token: guard.control_token.clone(),
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
`,us="//! 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`.",ms="//! 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 fs(e){let t=y(e,"apps/tauri/src/components/shell.tsx");await l(t,F(await $(t,"utf-8"),"components/shell.tsx"));let n=y(e,"apps/tauri/src/components/sidebar/app-sidebar.tsx"),r=F(await $(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 $(i,"utf-8"),"config/sidebar.ts");o=C(o,`import {
|
|
1164
1284
|
BuildingsIcon,
|
|
1165
1285
|
GearIcon,
|
|
1166
1286
|
HouseIcon,
|
|
1167
1287
|
RobotIcon,
|
|
1168
1288
|
UserCircleIcon
|
|
1169
|
-
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1289
|
+
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await l(i,o);let s=y(e,"apps/tauri/src/lib/config.ts"),a=F(await $(s,"utf-8"),"lib/config.ts");a=a.replace(/,(\n\} as const)/,"$1"),await l(s,a);let d=y(e,"apps/tauri/src/lib/sidebar-flags.ts");await l(d,F(await $(d,"utf-8"),"lib/sidebar-flags.ts"));let m=y(e,"apps/tauri/src/router.tsx"),p=F(await $(m,"utf-8"),"router.tsx");p=C(p,`import { clientConfig } from '@/lib/config'
|
|
1290
|
+
`,"","router clientConfig import"),p=C(p,` createRouter,
|
|
1291
|
+
redirect
|
|
1292
|
+
} from '@tanstack/react-router'`,` createRouter
|
|
1293
|
+
} from '@tanstack/react-router'`,"router redirect import specifier"),p=C(p,`import { AiHubScreen } from '@/screens/ai'
|
|
1294
|
+
`,"","router AiHubScreen import"),p=C(p,` ...(clientConfig.agentsEnabled ? [aiRoute, agentsRoute, schedulesRoute, integrationsRoute] : []),
|
|
1295
|
+
`,"","router ai route spread"),await l(m,p);let f=y(e,"apps/tauri/src/lib/bridge/index.ts"),w=F(await $(f,"utf-8"),"lib/bridge/index.ts");w=C(w,`/**
|
|
1296
|
+
* The complete public bridge: the app's full native + AI call surface, assembled from three transports
|
|
1297
|
+
* (engine HTTP, the event socket, native Tauri commands/plugins). The renderer imports \`bridge\` as a
|
|
1298
|
+
* module and derives its types from \`typeof bridge\`.
|
|
1299
|
+
*/
|
|
1300
|
+
export interface Bridge extends NativeBridgeParts {
|
|
1301
|
+
/** The AI tool-orchestration surface (present regardless of the feature flag). */
|
|
1302
|
+
ai: AiBridge
|
|
1303
|
+
}`,"/**\n * The complete public bridge: the app's full native call surface (native Tauri commands + plugins). The\n * renderer imports `bridge` as a module and derives its types from `typeof bridge`.\n */\nexport type Bridge = NativeBridgeParts","bridge Bridge interface"),w=C(w,as,cs,"bridge createBridge factory"),w=C(w,ls,ps,"bridge singleton tail"),await l(f,w);let b=y(e,"apps/tauri/src/lib/bridge/native.ts"),A=F(await $(b,"utf-8"),"lib/bridge/native.ts");A=C(A," /** Securely persists the Bearer token via the OS keychain, then syncs the running sidecar. */"," /** Securely persists the Bearer token via the OS keychain. */","native setToken jsdoc"),A=C(A," /** Removes the stored token (sign-out) and clears it on the running sidecar. */"," /** Removes the stored token (sign-out). */","native clearToken jsdoc"),A=C(A," Assembles the auth keyring\n * triplet (dual-writing the running sidecar on set/clear and registering the reconnect resync), the\n * guarded `openExternal`,"," Assembles the auth keyring\n * triplet, the guarded `openExternal`,","native createNativeBridge jsdoc"),await l(b,A);let J=y(e,"apps/tauri/tests/bridge/native.test.ts");await l(J,F(await $(J,"utf-8"),"tests/bridge/native.test.ts"));let V=y(e,"apps/tauri/src-tauri/src/lib.rs"),R=await $(V,"utf-8");R=C(R,`mod daemon;
|
|
1304
|
+
`,"","lib.rs mod daemon"),R=C(R,ds,"","lib.rs get_control_info command"),R=C(R,` get_control_info,
|
|
1305
|
+
`,"","lib.rs get_control_info handler registration"),R=C(R,` let handle = app.handle().clone();
|
|
1306
|
+
`,"","lib.rs handle binding"),R=C(R,` if let Err(err) = daemon::init(&handle) {
|
|
1307
|
+
eprintln!("[shell] sidecar init failed: {err}");
|
|
1308
|
+
}
|
|
1309
|
+
`,"","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| {
|
|
1310
|
+
if let tauri::RunEvent::Exit = event {
|
|
1311
|
+
daemon::shutdown(app_handle);
|
|
1312
|
+
}
|
|
1313
|
+
});`," .run(|_app_handle, _event| {});","lib.rs daemon::shutdown exit hook"),await l(V,R);let ae=y(e,"apps/tauri/src-tauri/src/keyring_store.rs"),B=await $(ae,"utf-8");B=C(B,us,ms,"keyring_store module doc"),B=F(B,"src-tauri/src/keyring_store.rs"),await l(ae,B);let v=y(e,"apps/tauri/src-tauri/capabilities/default.json"),P=JSON.parse(await $(v,"utf-8")),_=P.permissions.length;if(P.permissions=P.permissions.filter(T=>T!=="dialog:default"),P.permissions.length===_)throw new Error("stripDesktopAi: expected the dialog:default capability in capabilities/default.json (boilerplate drift).");await l(v,JSON.stringify(P,null,2)+`
|
|
1314
|
+
`);let z=y(e,"apps/tauri/src-tauri/tauri.conf.json"),I=JSON.parse(await $(z,"utf-8"));if(!I.bundle)throw new Error("stripDesktopAi: expected a bundle block in tauri.conf.json (boilerplate drift).");if(we(I.bundle,"externalBin","the tauri.conf bundle.externalBin key","stripDesktopAi"),we(I.bundle,"resources","the tauri.conf bundle.resources key","stripDesktopAi"),!I.build||I.build.beforeDevCommand!=="pnpm sidecar:stage && pnpm dev:vite")throw new Error("stripDesktopAi: expected the sidecar-staged beforeDevCommand in tauri.conf.json (boilerplate drift).");if(I.build.beforeBuildCommand!=="pnpm sidecar:stage && pnpm build:vite")throw new Error("stripDesktopAi: expected the sidecar-staged beforeBuildCommand in tauri.conf.json (boilerplate drift).");I.build.beforeDevCommand="node scripts/sync-identity.mjs && pnpm dev:vite",I.build.beforeBuildCommand="node scripts/sync-identity.mjs && pnpm build:vite",await l(z,JSON.stringify(I,null,2)+`
|
|
1315
|
+
`)}import{readFile as gs}from"fs/promises";import{join as hs}from"path";var Vr=`on:
|
|
1174
1316
|
workflow_run:
|
|
1175
1317
|
workflows: ["CI"]
|
|
1176
1318
|
branches: [main]
|
|
1177
1319
|
types: [completed]
|
|
1178
|
-
workflow_dispatch:`,
|
|
1320
|
+
workflow_dispatch:`,ys=`on:
|
|
1179
1321
|
# Automatic release on CI success is disabled for this project to conserve
|
|
1180
1322
|
# GitHub Actions minutes. Re-enable by uncommenting the workflow_run trigger.
|
|
1181
1323
|
# workflow_run:
|
|
1182
1324
|
# workflows: ["CI"]
|
|
1183
1325
|
# branches: [main]
|
|
1184
1326
|
# types: [completed]
|
|
1185
|
-
workflow_dispatch:`;async function
|
|
1327
|
+
workflow_dispatch:`;async function Br(e){if(!e.desktop||e.desktopAutoRelease)return;let t=hs(e.projectDir,".github/workflows/tauri-release.yml"),n=await gs(t,"utf8");if(!n.includes(Vr))throw new Error(`Cannot make desktop releases manual: the expected workflow_run trigger block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,n.replace(Vr,ys))}import{join as vs}from"path";async function Fr(e){let t=bs(e);await l(vs(e.projectDir,".github/workflows/ci.yml"),t)}function bs(e){let t=Y[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",i=t?"":` services:
|
|
1186
1328
|
postgres:
|
|
1187
|
-
image:
|
|
1329
|
+
image: postgres:18-alpine
|
|
1188
1330
|
env:
|
|
1189
1331
|
POSTGRES_USER: postgres
|
|
1190
1332
|
POSTGRES_PASSWORD: postgres
|
|
@@ -1196,14 +1338,14 @@ resources/models/
|
|
|
1196
1338
|
--health-interval 10s
|
|
1197
1339
|
--health-timeout 5s
|
|
1198
1340
|
--health-retries 5
|
|
1199
|
-
`,o=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",
|
|
1341
|
+
`,o=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",s=n?`
|
|
1200
1342
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1201
|
-
UPSTASH_REDIS_REST_TOKEN: test-token`:"",
|
|
1343
|
+
UPSTASH_REDIS_REST_TOKEN: test-token`:"",a=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1202
1344
|
STRIPE_SECRET_KEY: test
|
|
1203
1345
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1204
1346
|
POLAR_ACCESS_TOKEN: test
|
|
1205
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1206
|
-
${
|
|
1347
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let f=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(f)}"`)}}})(),d=e.socialProviders.map(f=>ce[f].envVars.map(w=>`
|
|
1348
|
+
${w.name}: test`).join("")).join("");return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1207
1349
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1208
1350
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1209
1351
|
|
|
@@ -1228,7 +1370,7 @@ jobs:
|
|
|
1228
1370
|
runs-on: ubuntu-latest
|
|
1229
1371
|
timeout-minutes: 20
|
|
1230
1372
|
${i} env:
|
|
1231
|
-
CONTENT_API_KEY: test-contentapi-key-16chars${
|
|
1373
|
+
CONTENT_API_KEY: test-contentapi-key-16chars${s}${a}${d}
|
|
1232
1374
|
STORAGE_REGION: test
|
|
1233
1375
|
STORAGE_ENDPOINT: http://test
|
|
1234
1376
|
STORAGE_ACCESS_KEY_ID: test
|
|
@@ -1252,46 +1394,46 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1252
1394
|
run: echo "DATABASE_URL=${o}" > .env
|
|
1253
1395
|
|
|
1254
1396
|
- run: pnpm test
|
|
1255
|
-
`}import{readFile as
|
|
1256
|
-
`))}async function
|
|
1257
|
-
`))}async function
|
|
1397
|
+
`}import{readFile as Kr}from"fs/promises";import{existsSync as ks}from"fs";import{join as yn}from"path";var Gr="@repo/database";function ws(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function Ss(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 Es(e,t,n){let r=await Kr(e,"utf-8"),i=JSON.parse(r),o=i.scripts?.[t];if(!o)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);o.includes(Gr)||(i.scripts={...i.scripts,[t]:`${n} && ${o}`},await l(e,JSON.stringify(i,null," ")+`
|
|
1398
|
+
`))}async function As(e,t){let n=ks(e)?JSON.parse(await Kr(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},r=n.buildCommand?.trim()||"pnpm build";r.includes(Gr)||(n.buildCommand=`${t} && ${r}`,await l(e,JSON.stringify(n,null," ")+`
|
|
1399
|
+
`))}async function Hr(e){let t=ws(e.demo===!0),n=Ss(e.architecture,e.frontend),r=yn(e.projectDir,"apps",n);switch(e.deploymentTarget){case"node":await Es(yn(r,"package.json"),"start",t);return;case"vercel":await As(yn(r,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as Is}from"fs/promises";import{existsSync as Ps}from"fs";import{join as Ut}from"path";var Ts=["stripe","polar"];async function zr(e){let t=Ut(e.projectDir,"packages/payments/src"),n=e.paymentProvider,r=`// Active payment provider. To switch, change the path below to
|
|
1258
1400
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1259
1401
|
export { ops } from "./${n}/index";
|
|
1260
|
-
`;await l(
|
|
1261
|
-
`).filter(
|
|
1262
|
-
`)}import{readdir as
|
|
1402
|
+
`;await l(Ut(t,"providers/index.ts"),r),await l(Ut(t,"index.ts"),await Rs(t,n))}async function Rs(e,t){let n=Ut(e,"index.ts");if(!Ps(n))throw new Error(`generatePaymentBarrel: expected ${n} to exist - did packages/payments move?`);let r=await Is(n,"utf-8"),i=Ts.filter(s=>s!==t);return r.split(`
|
|
1403
|
+
`).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
|
|
1404
|
+
`)}import{readdir as _s,readFile as Os}from"fs/promises";import{join as Yr}from"path";async function qr(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,n=JSON.stringify(t).slice(1,-1),r=Yr(e.projectDir,"packages/i18n/translations"),i;try{i=await _s(r)}catch{return}for(let o of i){let s=Yr(r,o,"web.json"),a;try{a=await Os(s,"utf-8")}catch{continue}let d=a.replaceAll("GenerateSaaS",n);d!==a&&await l(s,d)}}import{readFile as xs}from"fs/promises";import{join as Jr}from"path";var Cs=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],Ds=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function Xr(e){let n=e.frontend==="nuxt"?Ds:Cs;await Wr(Jr(e.projectDir,".gitignore"),n),await Wr(Jr(e.projectDir,".dockerignore"),n)}async function Wr(e,t){let n;try{n=await xs(e,"utf-8")}catch{return}let r=new Set(t),i=n.split(`
|
|
1263
1405
|
`).filter(o=>!r.has(o.trim()));i.length!==n.split(`
|
|
1264
1406
|
`).length&&await l(e,i.join(`
|
|
1265
|
-
`))}async function
|
|
1266
|
-
`),await l(
|
|
1267
|
-
`)}import{relative as
|
|
1268
|
-
`);o(new Error(
|
|
1269
|
-
${
|
|
1270
|
-
`),
|
|
1271
|
-
`),
|
|
1272
|
-
`),
|
|
1273
|
-
`),await
|
|
1274
|
-
`),
|
|
1275
|
-
`);let
|
|
1276
|
-
`)}if(
|
|
1277
|
-
`),
|
|
1278
|
-
`),
|
|
1279
|
-
|
|
1280
|
-
${
|
|
1281
|
-
|
|
1282
|
-
`),title:`Changelog v${n} \u2192 v${r}`}}async function
|
|
1283
|
-
`);
|
|
1284
|
-
`),
|
|
1285
|
-
`).map(
|
|
1407
|
+
`))}async function Mt(e){let t=e.projectDir;e.demo||(await Zn(t),await Qn(t),await er(t),await tr(t),e.desktop&&e.desktopAi&&await nr(t)),await rr(t,e.aiTools),await ir(t,e.frontend),await sr(e),await ar(e),await cr(e),e.demo||await lr(e),await ur(e);let n=await mr(e);return await fr(e),await gr(e),await hr(e),await yr(e),await vr(e),await br(e),await Er(e),await Ar(e),await Tr(e),await _r(e),await Cr(e),await Fr(e),await Dr(e),await Nr(e),await Lr(e),await $r(e),await jr(e),await Ur(e),await Mr(e),await Br(e),await dn(e),await mn(e),await gn(e),await Hr(e),await zr(e),await qr(e),await Xr(e),{dockerComposeGenerated:n}}import{basename as Qr,join as ei,relative as Ls}from"path";import{createHash as Zr}from"crypto";import{readFile as Ns}from"fs/promises";async function Vt(e){let t=await Ns(e);return Zr("sha256").update(t).digest("hex")}function vn(e){return Zr("sha256").update(e).digest("hex")}var $s=new Set(["data",W]);function js(e){let t=e.split("/");for(let n of t)if(Qt.has(n)||en.has(n)||$s.has(n)||n.startsWith(".env")&&!n.includes("example"))return!0;return!1}function ti(e,t){return{projectName:e.projectName??Qr(t),appName:e.appName??e.projectName??Qr(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,docs:e.docs??!1,desktop:e.desktop??!1,desktopAutoRelease:e.desktopAutoRelease??!0,desktopAi:e.desktopAi??!1,ai:e.ai??!1,rag:e.rag??!1,companion:e.companion??!1,mcpServer:e.mcpServer??!1,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 Us(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,docs:e.docs,desktop:e.desktop,desktopAutoRelease:e.desktopAutoRelease,desktopAi:e.desktopAi,ai:e.ai,rag:e.rag,companion:e.companion,mcpServer:e.mcpServer,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 ni(e,t){let r=(await _e(e.projectDir,e.projectDir,js)).sort(),i=await Promise.all(r.map(async a=>[Re(Ls(e.projectDir,a)),await Vt(a)])),o=Object.fromEntries(i),s=Us(e,t);await l(ei(e.projectDir,he),JSON.stringify(s,null," ")+`
|
|
1408
|
+
`),await l(ei(e.projectDir,Bn),JSON.stringify(o,null," ")+`
|
|
1409
|
+
`)}import{relative as Ms}from"path";async function Xe(e){let n=(await _e(e,e,Ge)).sort(),r=await Promise.all(n.map(async i=>[Re(Ms(e,i)),await Vt(i)]));return Object.fromEntries(r)}import{copyFile as Vs,mkdir as Bs,rm as Fs}from"fs/promises";import{dirname as Ks,join as ri,relative as Gs}from"path";import{existsSync as Hs}from"fs";async function bn(e,t){Hs(t)&&await Fs(t,{recursive:!0,force:!0});let n=await _e(e,e,Ge);for(let r of n){let i=Re(Gs(e,r)),o=ri(t,i);await Bs(Ks(o),{recursive:!0}),await Vs(r,o)}}async function ii(e,t){await bn(e,ri(t,St))}import{existsSync as zs}from"fs";import{readFile as oi,readdir as Ys}from"fs/promises";import{join as se,dirname as qs,resolve as Js,sep as Ws}from"path";import{fileURLToPath as Xs}from"url";var pt={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Md=Object.values(pt),kn="generatesaas-update",si=qs(Xs(import.meta.url));function Zs(){let e=se(si,"skill","content");return zs(e)?e:se(si,"content")}function wn(e){return!e||e.length===0?[]:e.map(t=>pt[t])}async function Sn(e,t,n,r){let i=wn(r);for(let o of i){let s=se(e,o,kn),a=se(s,"scripts"),d=se(s,"references");await Rt(a),await Rt(d),await l(se(s,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",o)),await l(se(d,".gitkeep"),"");for(let[m,p]of Object.entries(n)){let f=Js(a,m);f.startsWith(a+Ws)&&await l(f,p)}}}async function ai(e,t){let n=Zs(),r=await oi(se(n,"SKILL.md"),"utf-8"),i=se(n,"scripts"),o=await Ys(i),s={};for(let a of o)a!==".gitkeep"&&(s[a]=await oi(se(i,a),"utf-8"));await Sn(e,r,s,t)}import{execFile as Qs,execFileSync as ea}from"child_process";import{access as ci,readFile as ta}from"fs/promises";import{join as En}from"path";import*as j from"@clack/prompts";function Ce(e){try{let t=process.platform==="win32"?"where":"which";return ea(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function xe(e,t,n,r=3e5){return new Promise((i,o)=>{Qs(e,t,{cwd:n,timeout:r,maxBuffer:50*1024*1024},(s,a,d)=>{if(s){let m=String(a||"").trim(),f=[String(d||"").trim(),m].filter(Boolean).join(`
|
|
1410
|
+
`);o(new Error(f?`${s.message}
|
|
1411
|
+
${f}`:s.message))}else i()})})}async function li(e){if(!Ce("pnpm"))return j.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await xe("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let n=t instanceof Error?t.message:String(t);return j.log.warn(`Lockfile regeneration failed: ${n}`),j.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function pi(e){if(!Ce("pnpm"))return j.log.warn("pnpm not found. Skipping dependency installation."),j.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=j.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await xe("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(n){t.stop("Dependency installation failed.");let r=n instanceof Error?n.message:String(n);return j.log.warn(`pnpm install failed: ${r}`),j.log.warn("You can run it manually later."),!1}}async function di(e){if(!Ce("pnpm"))return!1;let t=j.spinner();t.start("Generating baseline database migration...");try{return await xe("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(n){t.stop("Baseline migration generation failed.");let r=n instanceof Error?n.message:String(n);return j.log.warn(`Could not generate baseline migration: ${r}`),j.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function ui(e){try{return await ci(En(e,".git")),j.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ce("git"))return j.log.warn("git not found. Skipping repository initialization."),!1;let t=j.spinner();t.start("Initializing git repository...");try{return await xe("git",["init"],e),await xe("git",["add","-A"],e),await xe("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),j.log.warn("You can run git init manually later."),!1}}async function mi(e){if(!Ce("pnpm"))return!1;try{await ci(En(e,".git"))}catch{return!1}try{let t=JSON.parse(await ta(En(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 xe("pnpm",["exec","simple-git-hooks"],e),!0}catch{return j.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Ze from"@clack/prompts";import Q from"picocolors";function fi(e,t){t.dockerComposeGenerated&&!t.dockerAvailable&&Ze.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 o=e.dockerServices.map(s=>Le[s].label).join(", ");n.push(`pnpm infra ${Q.dim(`# ${o}`)}`)}if(n.push(`pnpm dev ${Q.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(Q.dim("Fill in remaining TODO values in .env"))),Ze.note(n.join(`
|
|
1412
|
+
`),Q.yellow("Start Development")),t.dockerComposeGenerated){let o=[];o.push(`App ${Q.cyan("http://localhost:3000")}`),e.architecture==="separate"&&o.push(`API ${Q.cyan("http://localhost:3010")}`),e.dockerServices.includes("mailpit")&&o.push(`Mailpit ${Q.cyan("http://localhost:8025")}`),e.dockerServices.includes("inngest")&&o.push(`Inngest ${Q.cyan("http://localhost:8288")}`),Ze.note(o.join(`
|
|
1413
|
+
`),Q.yellow("Dev Tools"))}let r=[],i=na(e);i.length>0&&r.push(`Set in production: ${Q.dim(i.join(", "))}`),r.push("pnpm db:setup # Apply the database schema"),r.push(ra(e)),Ze.note(r.join(`
|
|
1414
|
+
`),Q.yellow("Deployment"))}function na(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 ra(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}import la from"picocolors";var pa="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function da(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 ua(e){if(e===void 0)return;let t=e.trim().replace(/^v/,"");if(!/^\d+\.\d+\.\d+$/.test(t))throw new Error(`Invalid template version "${e}". Use semver like 1.2.3.`);return t}function gi(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([...Ie])).addOption(new ee("--architecture <type>","fullstack or separate").choices([...$e])).addOption(new ee("--payment <provider>","payment provider").choices([...je])).addOption(new ee("--email <provider>","email provider").choices([...Ue])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new ee("--billing-scope <scope>","billing scope (requires --org)").choices([...Be])).option("--blog","enable blog").option("--no-blog","disable blog").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/tauri, built with Tauri)").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("--desktop-ai","include the desktop AI orchestration layer (requires --desktop)").option("--no-desktop-ai","exclude the desktop AI orchestration layer").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion + MCP server").option("--no-ai","exclude the AI features").option("--rag","include the server-side knowledge base (keyword search over your knowledge/ docs)").option("--no-rag","exclude the server-side knowledge base").option("--companion","include the companion daemon (apps/companion) + its HTTP transport").option("--no-companion","exclude the companion daemon").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-byok","AI BYOK mode: end-users bring their own provider key (default)").option("--no-ai-byok","operator-keyed, credit-metered AI platform mode").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([...le])).addOption(new ee("--deploy <target>","deployment target").choices([...pe])).addOption(new ee("--database <provider>","database provider").choices([...de])).addOption(new ee("--cache <provider>","cache provider").choices([...ue])).option("--template-version <version>","specific template version to scaffold").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 ma(t?{...n,apiKey:t}:n)})}async function ma(e){let t=performance.now();Dn("1.21.0");let n,r;try{n=Un(e),r=ua(e.templateVersion)}catch(v){E.cancel(L(v)),process.exit(1)}let i=E.spinner(),o;try{o=await Ke({apiKey:e.apiKey,prompt:!e.yes})}catch(v){E.cancel(L(v)),process.exit(1)}e.demo&&vn(o)!==pa&&(E.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=ge(o),a=async()=>{let v=await be(s),P=v.latest,_=r??P;if(r&&!v.versions.some(z=>z.version===_))throw new Error(`Template version "${r}" is not available.`);return{latestVersion:P,selectedVersion:_,desktopAllowed:v.entitlements?.desktopAllowed??!0}};i.start("Verifying access...");let d,m,p=!0;try{({latestVersion:d,selectedVersion:m,desktopAllowed:p}=await a()),i.stop("Access verified."),Te(o)}catch(v){if(i.stop("Access verification failed."),v instanceof M&&v.status===401){e.yes&&(E.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),E.log.warning("Invalid API key."),o=await ct(),s=ge(o),i.start("Verifying access...");try{({latestVersion:d,selectedVersion:m,desktopAllowed:p}=await a()),i.stop("Access verified."),Te(o)}catch(P){i.stop("Access verification failed."),E.cancel(P instanceof M&&P.status===401?"Invalid API key.":L(P)),process.exit(1)}}else E.cancel(L(v)),process.exit(1)}E.log.success(`Latest version: ${d}`),m!==d&&E.log.success(`Using template version: ${m}`),n.desktop===!0&&!p&&(E.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let f;e.yes?f=Mn(p?n:{...n,desktop:!1}):f=await Vn(n,{desktopAllowed:p});let w;i.start("Activating license...");try{let v=e.demo&&f.baseUrl?await da(f.baseUrl):crypto.randomUUID(),P=()=>({frontend:f.frontend,version:m,installId:v,projectName:f.projectName,options:Hn(f)}),_;try{_=await Xt(s,P())}catch(z){let I=Et(z);if(!I?.lastAllowedVersion)throw z;i.stop("License activation failed."),e.yes&&(E.cancel(`${I.message} Re-run with --template-version ${I.lastAllowedVersion}.`),process.exit(1));let T=await E.confirm({message:`Your update window has ended. Continue with v${I.lastAllowedVersion} (the last version your license covers)?`});(E.isCancel(T)||!T)&&(E.cancel("Setup cancelled."),process.exit(0)),m=I.lastAllowedVersion,i.start(`Activating license for v${m}...`),_=await Xt(s,P())}w={token:_.token,keyHash:vn(o),installId:_.installId??v},i.stop("License activated.")}catch(v){i.stop("License activation failed."),E.cancel(L(v)),process.exit(1)}let b=ca(f.projectDir);if(ia(b)&&oa(b).length>0)if(e.yes)E.log.info(`Directory ${b} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let P=await E.select({message:`Directory ${b} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(E.isCancel(P)||P==="cancel")&&(E.cancel("Setup cancelled."),process.exit(0)),P==="overwrite"&&sa(b,{recursive:!0,force:!0})}let A={...f,projectDir:b,version:m,...e.demo?{docs:!1}:{}};i.start("Downloading template...");try{await At(s,m,b),i.stop("Template downloaded.")}catch(v){i.stop("Download failed."),E.cancel(L(v)),process.exit(1)}let J;i.start("Generating project files...");try{if({dockerComposeGenerated:J}=await Mt(A),!e.demo){let v=await Xe(b);await l(aa(b,wt),JSON.stringify(v,null," ")+`
|
|
1415
|
+
`),await ii(b,b)}await ai(b,A.aiTools),await ni(A,w),i.stop("Project files generated.")}catch(v){i.stop("Generation failed."),E.cancel(L(v)),process.exit(1)}await li(b);let V=await pi(b);V&&A.demo!==!0&&e.dbMigration!==!1&&await di(b),await ui(b),V&&await mi(b);let R=Ce("docker"),B=Jt(A).map(v=>v.key).filter(v=>!A.credentials?.[v]);fi(A,{pnpmInstalled:V,dockerComposeGenerated:J,dockerAvailable:R,skippedCredentials:B}),Nn(),E.log.info(la.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as ki}from"fs";import{readFile as wi}from"fs/promises";import{join as dt,resolve as ba}from"path";import*as U from"@clack/prompts";import Qe from"picocolors";import{mkdtemp as fa,rm as ga}from"fs/promises";import{tmpdir as ha}from"os";import{join as ya}from"path";async function An(e,t,n,r){let i=await fa(ya(ha(),"generatesaas-stage-"));try{await At(e,t,i),await Mt({...n,projectDir:i}),await bn(i,r)}finally{await ga(i,{recursive:!0,force:!0})}}var hi=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ie,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:$e,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:pe,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:de,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ue,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:je,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:le,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ue,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:Be,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:"Adds the terminal companion (apps/companion) that drives the user's subscription CLIs over stateless HTTP. Works on any deployment.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{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:Fe,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Me,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:Ve,adoptable:!1,impact:"config"}];function va(e,t){return e[t]!==void 0}function yi(e){return hi.filter(t=>t.adoptable&&!va(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function vi(e){let t={};for(let n of hi)t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}function bi(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 Bt(e,t){let n=bi(e),r=bi(t);if(!n||!r)return 0;for(let i=0;i<3;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function Si(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,n)=>{let r=t==="auto"?"auto":void 0,i=ba(n.cwd??process.cwd()),o=dt(i,he),s;try{s=JSON.parse(await wi(o,"utf-8"))}catch{U.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let a;try{a=await Ke()}catch(p){U.cancel(L(p)),process.exit(1)}let d=ge(a),m=U.spinner();try{m.start("Verifying access...");let p;try{p=await be(d)}catch(T){throw T instanceof M&&T.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):T}m.stop("Access verified."),Te(a),m.start("Fetching latest skill files...");let f=await Gn(d,p.latest);await Sn(i,f.skillMd,f.scripts,s.aiTools);let w=wn(s.aiTools);if(m.stop("Skills updated."),U.log.success(`Skill files installed to ${Qe.cyan(w.length.toString())} locations.`),s.version===p.latest){U.log.info(`Already on the latest version (${s.version}).`);return}let b=JSON.stringify(s);jn(s);let A=yi(s),J=vi(s),V=JSON.stringify(J)!==b;if(s=J,s.licenseToken)try{let T=await zn(d,{currentToken:s.licenseToken,newVersion:p.latest});s.licenseToken=T.token,T.licenseKeyHash&&(s.licenseKeyHash=T.licenseKeyHash),await l(o,JSON.stringify(s,null," ")+`
|
|
1416
|
+
`),V=!1,U.log.success("License refreshed.")}catch(T){let Se=Et(T);Se&&(U.cancel(Se.message),process.exit(1)),U.log.warn("License refresh skipped.")}V&&await l(o,JSON.stringify(s,null," ")+`
|
|
1417
|
+
`);let R=ti(s,i),ae=dt(i,Fn);m.start(`Staging v${p.latest} (shaped for your config)...`),await An(d,p.latest,R,ae),m.stop("Template staged.");let{text:B,title:v}=await ka(d,p,s.version);B&&U.note(B,v);let P=dt(i,wt),_=dt(i,St),z=!ki(_),I=!ki(P);if(z){if(m.start("Building baseline template (one-time migration)..."),await An(d,s.version,R,_),I){let T=await Xe(_);await l(P,JSON.stringify(T,null," ")+`
|
|
1418
|
+
`)}if(m.stop("Baseline template stored."),!I){let T=await wa(P,_);T>0&&U.log.warn(`Rebuilt baseline differs from the original for ${T} 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(I){m.start("Computing baseline template hashes...");let T=await Xe(_);await l(P,JSON.stringify(T,null," ")+`
|
|
1419
|
+
`),m.stop("Baseline hashes computed.")}if(await l(dt(i,Kn),JSON.stringify({currentVersion:s.version,targetVersion:p.latest,changelog:B,stagedAt:new Date().toISOString(),...A.length>0?{newOptions:A}:{},...r?{mode:r}:{}},null," ")+`
|
|
1420
|
+
`),U.log.info(`Update staged: ${Qe.cyan(s.version)} \u2192 ${Qe.cyan(p.latest)}`),s.aiTools&&s.aiTools.length>0){let T=s.aiTools[0],Se=rt[T].label;U.log.info(`Open your project in ${Qe.cyan(Se)} and ask: ${Qe.cyan("'update my GenerateSaaS project'")}`)}else U.log.info(`Ask your AI coding assistant to ${Qe.cyan("'update my GenerateSaaS project'")}.`)}catch(p){m.stop("Failed."),U.cancel(`Update failed: ${L(p)}`),process.exit(1)}})}async function ka(e,t,n){let r=t.latest,i=t.versions.filter(s=>Bt(s.version,n)>0&&Bt(s.version,r)<=0).sort((s,a)=>Bt(s.version,a.version));if(i.length<=1)return{text:await Wt(e,r),title:`Changelog v${r}`};let o=[];for(let s of i){let a=null;try{a=await Wt(e,s.version)}catch{a=null}let d=s.date?` (${s.date.slice(0,10)})`:"",m=s.breaking?" [BREAKING]":"";o.push(`# v${s.version}${d}${m}
|
|
1421
|
+
|
|
1422
|
+
${a??"_No changelog available for this release._"}`)}return{text:o.join(`
|
|
1423
|
+
|
|
1424
|
+
`),title:`Changelog v${n} \u2192 v${r}`}}async function wa(e,t){let n=JSON.parse(await wi(e,"utf-8")),r=await Xe(t),i=0;for(let[o,s]of Object.entries(n))Ge(o)||r[o]!==s&&i++;for(let o of Object.keys(r))o in n||i++;return i}import*as q from"@clack/prompts";import te from"picocolors";import{readFile as Sa}from"fs/promises";import{join as Ea,resolve as Aa}from"path";function Ei(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=Aa(t.cwd??process.cwd()),r=Ea(n,he),i;try{i=JSON.parse(await Sa(r,"utf-8"))}catch{q.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${te.cyan(i.version)}`,`Frontend: ${te.cyan(i.frontend)}`,i.deploymentTarget?`Deploy target: ${te.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${te.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${te.cyan(i.cacheProvider)}`:null,i.aiTools&&i.aiTools.length>0?`AI tools: ${te.cyan(i.aiTools.join(", "))}`:null].filter(Boolean).join(`
|
|
1425
|
+
`);q.note(o,te.bold("Project Status"));let s=q.spinner();s.start("Checking for updates...");try{let a=await Ke(),d=ge(a),p=(await be(d)).latest;i.version===p?(s.stop("Up to date."),q.log.success(`Already on the latest version (${te.green(p)})`)):(s.stop("Update available."),q.log.warning(`Update available: ${te.yellow(i.version)} \u2192 ${te.green(p)}`),q.log.info(`Open this project in your AI coding agent and ask it to ${te.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof M&&a.status===401?q.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):q.log.warning(`Could not check for updates: ${L(a)}`)}})}import{readFile as Ia}from"fs/promises";import*as N from"@clack/prompts";import D from"picocolors";function Pa(){return process.env.GENERATESAAS_API_KEY??at()}function Ta(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 Ra(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function _a(e){switch(e.verdict){case"licensed":return N.log.success(`${D.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return N.log.success(`${D.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return N.log.error(`${D.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return N.log.error(`${D.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${D.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return N.log.error(`${D.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return N.log.warn(`${D.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Ai(e,t){let n=process.env.GENERATESAAS_API_URL??st,r=Pa();e.start("Cross-referencing license records...");try{let i=r?Ta(await Yn(n,r,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Ra(await Zt(n,{token:t.token,domain:t.domain}));return e.stop(`${D.green("Checked")} - records cross-referenced`),_a(i)}catch(i){return e.stop(`${D.yellow("Skipped")} - ${L(i)}`),null}}function Oa(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 In(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Ii(e){N.note([`License ID: ${D.cyan(String(e.lid??"unknown"))}`,`Version: ${D.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${In(e.pat)}`,`Last updated: ${In(e.uat)}`,`Expires: ${In(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1426
|
+
`),D.yellow("License Details"))}function xa(e){let n=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(n.endsWith("/api"))return[`${n}/license`];try{if(new URL(n).pathname!=="/")return[`${n}/license`]}catch{return[`${n}/license`]}return[`${n}/api/license`,`${n}/license`]}async function Pi(e){let t=N.spinner(),n=null,r="no candidates";for(let s of xa(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){r=`${s} returned ${a.status}`,t.stop(`${D.yellow("Not here")} - ${r}`);continue}let d=(await a.text()).trim();if(!d||d.split(".").length!==3){r=`${s} did not return a JWT`,t.stop(`${D.yellow("Not here")} - ${r}`);continue}n=d,t.stop(`${D.green("Found")} - license endpoint responded`);break}catch(a){r=`${s}: ${L(a)}`,t.stop(`${D.yellow("Unreachable")} - ${r}`)}}if(n===null){N.log.warn(`No license endpoint found (last: ${r}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=Ti(e);return s?await Ai(t,{domain:s})??!1:!1}let i;try{i=Oa(n)}catch{return N.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??st,a=await Zt(s,{token:n});if(a.valid)t.stop(`${D.green("Valid")} - signature verified`);else return t.stop(`${D.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${D.yellow("Skipped")} - could not reach verification service`),N.log.warn("Signature not verified. Displaying unverified claims:"),Ii(i),!1}return Ii(i),await Ai(t,{token:n,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:Ti(e)})??!0}function Ti(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function Ri(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,n)=>{if(!t&&!n.file&&(N.cancel("Provide a URL or --file <path>."),process.exit(1)),n.file){let i=(await Ia(n.file,"utf-8")).split(`
|
|
1427
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(N.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await Pi(s)&&o++,N.log.info("");N.log.success(`${o}/${i.length} sites verified.`)}else await Pi(t)||process.exit(1)})}import{existsSync as Ca,rmSync as Da}from"fs";import*as ne from"@clack/prompts";function _i(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Ca(fe)?(Da(fe),ne.log.success("API key removed.")):ne.log.info("No API key configured.");return}let n=at();n?ne.log.info(`Current API key: ****${n.slice(-4)}`):ne.log.info("No API key configured.");let r=await ct(),i=ge(r),o=ne.spinner();o.start("Verifying API key...");try{await be(i),o.stop("API key verified."),Te(r),ne.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof M&&s.status===401?ne.cancel("Invalid API key."):ne.cancel(L(s)),process.exit(1)}})}import{existsSync as Ft,rmSync as Na,readFileSync as Tn,writeFileSync as Oi}from"fs";import{join as De}from"path";import*as K from"@clack/prompts";var La=["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"],$a=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1286
1428
|
`,` licenseHeartbeatFunction,
|
|
1287
1429
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1288
1430
|
`,` .route("/license", licenseRoutes)
|
|
1289
|
-
`]}];function
|
|
1431
|
+
`]}];function ja(e){return(e&&e.length>0?e.map(n=>pt[n]):Object.values(pt)).map(n=>De(n,kn))}function Pn(e){return Ft(e)?(Na(e,{recursive:!0}),!0):!1}function Ua(e,t){if(!Ft(e))return!1;let n=Tn(e,"utf-8"),r=n;for(let i of t)r=r.replace(i,"");return r===n?!1:(Oi(e,r,"utf-8"),!0)}function Ma(e){let t=De(e,".gitignore");if(!Ft(t))return!1;let n=Tn(t,"utf-8"),r=n.split(`
|
|
1290
1432
|
`).filter(i=>!i.includes(".generatesaas")).join(`
|
|
1291
|
-
`);return r===n?!1:(
|
|
1433
|
+
`);return r===n?!1:(Oi(t,r,"utf-8"),!0)}function xi(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),n=De(t,he),r;try{r=JSON.parse(Tn(n,"utf-8"))}catch{K.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await K.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(K.isCancel(i)&&(K.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)}),K.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{K.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of ja(r.aiTools))Pn(De(t,a))&&o.push(a);for(let a of La)Pn(De(t,a))&&o.push(a);Pn(De(t,W))&&o.push(W+"/");for(let a of $a){let d=De(t,a.file);Ua(d,a.removals)?s.push(a.file):Ft(d)&&K.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Ma(t)&&s.push(".gitignore");for(let a of o)K.log.info(`Deleted ${a}`);for(let a of s)K.log.info(`Modified ${a}`);K.log.success("Ejected successfully. This project is now fully standalone.")})}var Ne=new Va().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("1.21.0").addHelpText("after",`
|
|
1292
1434
|
Examples:
|
|
1293
1435
|
$ generatesaas init Interactive setup
|
|
1294
1436
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1295
1437
|
$ generatesaas status Check for updates
|
|
1296
1438
|
$ generatesaas auth Set or update API key
|
|
1297
|
-
`);
|
|
1439
|
+
`);gi(Ne);Si(Ne);Ei(Ne);Ri(Ne);_i(Ne);xi(Ne);Ne.parseAsync().catch(e=>{Ci.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|