generatesaas 0.2.2 → 0.2.3
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 +20 -20
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as Kr}from"commander";import*as
|
|
3
|
-
`)}async function q(e){let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=
|
|
2
|
+
import{Command as Kr}from"commander";import*as _t from"@clack/prompts";import{existsSync as Tr,readdirSync as xr,rmSync as kr}from"fs";import{join as Cr,resolve as Or}from"path";import{Option as x}from"commander";import*as g from"@clack/prompts";import*as Q from"@clack/prompts";import he from"picocolors";function Re(){Q.intro(he.bgMagenta(he.white(" GenerateSaaS ")))}function De(){Q.outro(he.magenta("Happy building!"))}import*as m from"@clack/prompts";var Z={nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"},nextjs:{label:"Next.js",hint:"coming soon"}},ve={fullstack:{label:"Fullstack",hint:"Nuxt handles API via server routes"},separate:{label:"Separate",hint:"Standalone Hono backend"}},Se={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},we={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Ie={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},Ee={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}},Te={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var O={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 ee={node:{label:"Node.js / Docker",hint:"self-hosted with Dockerfile",edgeRuntime:!1},cloudflare:{label:"Cloudflare Workers",hint:"edge runtime, wrangler.toml",edgeRuntime:!0},vercel:{label:"Vercel",hint:"serverless, vercel.json",edgeRuntime:!0},netlify:{label:"Netlify",hint:"serverless, netlify.toml",edgeRuntime:!0}},L={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"}]}},j={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"}]}},xe=[{target:"cloudflare",provider:"postgres",reason:"Cloudflare Workers cannot connect to self-hosted PostgreSQL. Use Neon or Supabase instead."},{target:"cloudflare",provider:"redis",reason:"Cloudflare Workers cannot connect to self-hosted Redis. Use Upstash instead."},{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"netlify",provider:"redis",reason:"Netlify serverless cannot maintain persistent Redis connections. Consider Upstash."}],ke=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];var te=["fullstack","separate"],re=["stripe","polar","none"],ne=["smtp","ses","resend"],ie=["postgres","redis","inngest","mailpit"],oe=["claude-code","cursor","codex","gemini-cli","windsurf"],se=["user","organization"],$=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],N=["node","cloudflare","vercel","netlify"],V=["postgres","neon","supabase"],U=["redis","upstash"];function Ce(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ae(e){return/^[a-z][a-z0-9-]*$/.test(e)}function I(e){return e instanceof Error?e.message:String(e)}function y(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}async function Oe(e){let t=e?.projectName??await(async()=>{let s=await m.text({message:"Project name:",placeholder:"my-saas",validate:c=>{if(!c?.trim())return"Project name is required.";if(!ae(c))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return y(s),s})(),r=e?.projectDir??await(async()=>{let s=await m.text({message:"Project location:",initialValue:`./${t}`});return y(s),s==="."?process.cwd():s})(),n=e?.frontend??await(async()=>{let s=Object.keys(Z),c=await m.select({message:"Frontend framework:",options:s.map(_=>({value:_,label:Z[_].label,hint:Z[_].hint}))});return y(c),c==="nextjs"&&(m.cancel("Next.js support is coming soon. Please select Nuxt for now."),process.exit(0)),c})(),i=e?.architecture??await(async()=>{let s=await m.select({message:"Architecture:",options:te.map(c=>({value:c,label:ve[c].label,hint:ve[c].hint}))});return y(s),s})(),o=e?.deploymentTarget??"node";if(i==="separate"&&e?.deploymentTarget===void 0){let s=await m.select({message:"Deployment target:",options:N.map(c=>({value:c,label:ee[c].label,hint:ee[c].hint}))});y(s),o=s}let a=e?.databaseProvider??await(async()=>{let s=await m.select({message:"Database provider:",options:V.map(c=>({value:c,label:L[c].label,hint:L[c].hint}))});return y(s),s})(),l=e?.cacheProvider??await(async()=>{let s=await m.select({message:"Cache provider:",options:U.map(c=>({value:c,label:j[c].label,hint:j[c].hint}))});return y(s),s})();if(i==="separate"){for(let s of xe)s.target===o&&(s.provider===a||s.provider===l)&&m.log.warn(s.reason);ee[o].edgeRuntime&&m.log.warn(`Edge runtime selected. These features are not available: ${ke.join(", ")}`)}let d=e?.paymentProvider??await(async()=>{let s=await m.select({message:"Payment provider:",options:re.map(c=>({value:c,label:Se[c].label,hint:Se[c].hint}))});return y(s),s})(),u=e?.defaultCurrency??await(async()=>{let s=await m.select({message:"Default currency:",options:$.map(c=>({value:c,label:c,hint:O[c].name}))});return y(s),s})(),R=e?.emailProvider??await(async()=>{let s=await m.select({message:"Email provider:",options:ne.map(c=>({value:c,label:we[c].label,hint:we[c].hint}))});return y(s),s})(),k=e?.multiTenancy??await(async()=>{let s=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return y(s),s})(),B=e?.billingScope??"user";if(k&&e?.billingScope===void 0){let s=await m.select({message:"Billing scope:",options:se.map(c=>({value:c,label:Ie[c].label,hint:Ie[c].hint}))});y(s),B=s}let f=e?.blog??await(async()=>{let s=await m.confirm({message:"Enable blog?",initialValue:!1});return y(s),s})(),v=e?.revenueSharing??await(async()=>{let s=await m.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return y(s),s})(),ye=e?.dockerServices??await(async()=>{let s=[...ie].filter(C=>C!=="mailpit");R==="smtp"&&s.push("mailpit");let c=s.map(C=>({value:C,label:Ee[C].label,hint:Ee[C].hint})),_=await m.multiselect({message:"Which services should we set up in Docker for you?",options:c,initialValues:c.map(C=>C.value),required:!1});return y(_),_})(),Pt=e?.aiTools??await(async()=>{let s=oe.map(_=>({value:_,label:Te[_].label})),c=await m.multiselect({message:"Which AI coding tools do you use?",options:s,initialValues:[],required:!1});return y(c),c})();return{projectName:t,projectDir:r,frontend:n,architecture:i,deploymentTarget:o,databaseProvider:a,cacheProvider:l,paymentProvider:d,emailProvider:R,multiTenancy:k,billingScope:B,blog:f,revenueSharing:v,dockerServices:ye,aiTools:Pt,defaultCurrency:u}}import{mkdir as Nt}from"fs/promises";import{Readable as Vt}from"stream";import{pipeline as Ut}from"stream/promises";import{extract as Mt}from"tar";import{join as G}from"path";import{homedir as Rt}from"os";var ce=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",M=".generatesaas",H=G(M,"manifest.json"),Le=G(M,"hashes.json"),pe=G(M,"template-hashes.json"),je=G(M,"staging"),$e=G(M,"staging.json"),z=G(Rt(),".generatesaas");var P=class extends Error{constructor(r,n){super(n);this.status=r}name="ApiError"};function K(e){return{apiKey:e,baseUrl:ce}}async function D(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli"}});if(!i.ok){let o;try{o=(await i.json()).error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new P(i.status,o)}return i}import{existsSync as Dt,readFileSync as Tt,writeFileSync as xt,mkdirSync as kt}from"fs";import{dirname as Ct}from"path";import*as T from"@clack/prompts";function Ot(){if(!Dt(z))return null;try{let e=JSON.parse(Tt(z,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&T.log.warning(`Found old GitHub token in ${z}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ne(e){kt(Ct(z),{recursive:!0}),xt(z,JSON.stringify({apiKey:e},null," ")+`
|
|
3
|
+
`)}async function q(e){let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=Ot();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");let n=await T.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:i=>{if(!i?.trim())return"API key is required."}});return T.isCancel(n)&&(T.cancel("Setup cancelled."),process.exit(0)),n}async function Y(e){return await(await D(e,"/versions")).json()}async function Ve(e,t){try{return await(await D(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof P&&r.status===404)return null;throw r}}async function Ue(e,t){return await(await D(e,`/skill/${encodeURIComponent(t)}`)).json()}async function Me(e,t){return await(await D(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Fe(e,t){return await(await D(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Be(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}var Lt=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".netlify",".wrangler",".devcontainer","playwright-report","test-results"]),jt=new Set(["data","mksaas",".claude",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","AGENTS.md","TODO.md","OVERVIEW.md","pnpm-lock.yaml"]),$t=["apps/cms","packages/blog","packages/cli","packages/cli-api","scripts/.env","scripts/.meta","infra/docker-compose.yml"];function le(e){let t=e.split("/");for(let r of t)if(Lt.has(r))return!0;if(jt.has(t[0]))return!0;for(let r of $t)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function J(e,t,r){let n=await D(e,`/template/${encodeURIComponent(t)}`);if(!n.body)throw new Error("Empty response body");await Nt(r,{recursive:!0});let i=Vt.fromWeb(n.body);await Ut(i,Mt({cwd:r,strip:1,filter:o=>{let a=o.replace(/^[^/]+\//,"");return a?!le(a):!0}}))}import{mkdir as Ft,writeFile as Bt}from"fs/promises";import{dirname as Gt}from"path";async function de(e){await Ft(e,{recursive:!0})}async function p(e,t){await de(Gt(e)),await Bt(e,t,"utf-8")}async function Ge(e){switch(e.cacheProvider){case"redis":await Ht(e),await zt(e);break;case"upstash":await Kt(e),await qt(e);break}}async function Ht(e){await p(`${e.projectDir}/packages/api/src/services/redis.ts`,`import { Redis } from "ioredis";
|
|
4
4
|
import { RedisStore } from "rate-limit-redis";
|
|
5
5
|
import { env } from "../env.js";
|
|
6
6
|
|
|
@@ -57,7 +57,7 @@ export async function withMutex<T>(key: string, ttlMs: number, fn: () => Promise
|
|
|
57
57
|
if (current === lockValue) await redis.del(lockKey);
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
|
-
`)}async function
|
|
60
|
+
`)}async function He(e){let t=Ce(e.projectName),r=e.paymentProvider!=="none",n=`import type { AppConfig } from "../types/index.js";
|
|
61
61
|
|
|
62
62
|
export const config: AppConfig = {
|
|
63
63
|
siteName: "${t}",
|
|
@@ -209,7 +209,7 @@ export * from "./section-tabs.js";
|
|
|
209
209
|
export * from "./sidebar.js";
|
|
210
210
|
export * from "./tenancy.js";
|
|
211
211
|
export * from "./user-menu.js";
|
|
212
|
-
`,i=`${e.projectDir}/packages/core/src/config/index.ts`;await p(i,n)}async function
|
|
212
|
+
`,i=`${e.projectDir}/packages/core/src/config/index.ts`;await p(i,n)}async function ze(e){let t;switch(e.databaseProvider){case"postgres":t=Yt();break;case"neon":t=Jt();break;case"supabase":t=Wt();break}await p(`${e.projectDir}/packages/db/src/index.ts`,t)}function Yt(){return`import { drizzle } from "drizzle-orm/node-postgres";
|
|
213
213
|
import { z } from "zod";
|
|
214
214
|
import * as schema from "./db/schema.js";
|
|
215
215
|
|
|
@@ -247,7 +247,7 @@ export const db = drizzle(client, { schema });
|
|
|
247
247
|
|
|
248
248
|
export * from "./db/schema.js";
|
|
249
249
|
export type { User, Account, Organization, Member } from "./db/auth.js";
|
|
250
|
-
`}async function
|
|
250
|
+
`}async function Ke(e){let t=[...e.dockerServices];if(L[e.databaseProvider].managed&&(t=t.filter(o=>o!=="postgres")),j[e.cacheProvider].managed&&(t=t.filter(o=>o!=="redis")),t.length===0)return!1;let r=[],n=[];t.includes("postgres")&&(r.push(` postgres:
|
|
251
251
|
image: postgres:18-alpine
|
|
252
252
|
ports:
|
|
253
253
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -290,7 +290,7 @@ ${r.join(`
|
|
|
290
290
|
volumes:
|
|
291
291
|
${n.join(`
|
|
292
292
|
`)}
|
|
293
|
-
`),await p(`${e.projectDir}/infra/docker-compose.yml`,i),!0}async function
|
|
293
|
+
`),await p(`${e.projectDir}/infra/docker-compose.yml`,i),!0}async function qe(e){if(e.architecture!=="separate")return;let t;switch(e.deploymentTarget){case"node":t=Xt();break;case"cloudflare":t=Qt();break;case"vercel":t=Zt();break;case"netlify":t=er();break}await p(`${e.projectDir}/apps/backend/src/index.ts`,t)}function Xt(){return`import { serve } from "@hono/node-server";
|
|
294
294
|
import { app, closeRedis, env, logger } from "@repo/api";
|
|
295
295
|
|
|
296
296
|
const server = serve(
|
|
@@ -319,12 +319,12 @@ export default handle(app);
|
|
|
319
319
|
import { app } from "@repo/api";
|
|
320
320
|
|
|
321
321
|
export default handle(app);
|
|
322
|
-
`}function
|
|
322
|
+
`}function Ye(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function tr(e){let t=crypto.randomUUID(),n=["# API Configuration",`API_URL=${e.architecture==="fullstack"?"http://localhost:3000/api":"http://localhost:3010"}`];switch(n.push("","# Database"),Ye(L[e.databaseProvider].envVars,n),n.push("","# Cache"),Ye(j[e.cacheProvider].envVars,n),n.push("","# Authentication",`BETTER_AUTH_SECRET=${t}`,"","# Job Queue - Inngest","INNGEST_APP_ID=api","INNGEST_EVENT_KEY=local","INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&n.push("","# API Port (standalone backend)","API_PORT=3010"),n.push("","# Email"),e.emailProvider){case"smtp":n.push("SMTP_HOST=localhost","SMTP_PORT=1025");break;case"ses":n.push("# TODO: Configure Amazon SES credentials","#AMAZON_SES_REGION=us-east-1","#AMAZON_SES_KEY=","#AMAZON_SES_SECRET=");break;case"resend":n.push("# TODO: Add your Resend API key","#RESEND_API_KEY=");break}if(e.paymentProvider!=="none")switch(n.push("","# Payment"),e.paymentProvider){case"stripe":n.push("# TODO: Add your Stripe keys","#STRIPE_SECRET_KEY=sk_test_...","#STRIPE_WEBHOOK_SECRET=whsec_...");break;case"polar":n.push("# TODO: Add your Polar keys","#POLAR_ACCESS_TOKEN=","#POLAR_WEBHOOK_SECRET=");break}return n.push(""),n.join(`
|
|
323
323
|
`)}function rr(e){return["# API Configuration",`NUXT_PUBLIC_API_URL=${e.architecture==="fullstack"?"http://localhost:3000/api":"http://localhost:3010"}`,""].join(`
|
|
324
|
-
`)}async function
|
|
325
|
-
`+t;await p(`${e.projectDir}/apps/web-nuxt/.env`,n)}else await p(`${e.projectDir}/apps/web-nuxt/.env`,r),await p(`${e.projectDir}/apps/backend/.env`,t)}import{readdir as ir}from"fs/promises";import{join as be,relative as
|
|
324
|
+
`)}async function Je(e){let t=tr(e),r=rr(e);if(e.architecture==="fullstack"){let n=r+`
|
|
325
|
+
`+t;await p(`${e.projectDir}/apps/web-nuxt/.env`,n)}else await p(`${e.projectDir}/apps/web-nuxt/.env`,r),await p(`${e.projectDir}/apps/backend/.env`,t)}import{readdir as ir}from"fs/promises";import{join as be,relative as Qe}from"path";import{createHash as We}from"crypto";import{readFile as nr}from"fs/promises";async function me(e){let t=await nr(e);return We("sha256").update(t).digest("hex")}function Xe(e){return We("sha256").update(e).digest("hex")}var or=new Set([".git","node_modules",".pnpm-store",".env","data",M]);function sr(e){let t=e.split("/");for(let r of t)if(or.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}async function Ze(e,t){let r=[],n=await ir(e,{withFileTypes:!0});for(let i of n){let o=be(e,i.name),a=Qe(t,o);sr(a)||(i.isDirectory()?r.push(...await Ze(o,t)):i.isFile()&&r.push(o))}return r}async function et(e,t){let n=(await Ze(e.projectDir,e.projectDir)).sort(),i=await Promise.all(n.map(async l=>[Qe(e.projectDir,l),await me(l)])),o=Object.fromEntries(i),a={version:e.version,initialVersion:e.version,repo:"Duzbee/GenerateSaaS",frontend:e.frontend,aiTools:e.aiTools,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,revenueSharing:e.revenueSharing,...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}};await p(be(e.projectDir,H),JSON.stringify(a,null," ")+`
|
|
326
326
|
`),await p(be(e.projectDir,Le),JSON.stringify(o,null," ")+`
|
|
327
|
-
`)}async function
|
|
327
|
+
`)}async function tt(e){if(!(e.architecture!=="separate"||e.deploymentTarget==="node"))switch(e.deploymentTarget){case"cloudflare":await ar(e);break;case"vercel":await cr(e);break;case"netlify":await pr(e);break}}async function ar(e){let t=`name = "${e.projectName}-api"
|
|
328
328
|
main = "src/index.ts"
|
|
329
329
|
compatibility_date = "2024-12-01"
|
|
330
330
|
|
|
@@ -342,7 +342,7 @@ API_URL = "https://api.example.com"
|
|
|
342
342
|
from = "/*"
|
|
343
343
|
to = "/.netlify/functions/index"
|
|
344
344
|
status = 200
|
|
345
|
-
`)}function lr(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function dr(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function mr(e){return e==="stripe"?' stripeProductId: "",':' polarProductId: "",'}async function
|
|
345
|
+
`)}function lr(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function dr(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function mr(e){return e==="stripe"?' stripeProductId: "",':' polarProductId: "",'}async function rt(e){if(e.paymentProvider==="none")return;let t=e.paymentProvider,r=e.defaultCurrency,n=lr(t),i=dr(t),o=mr(t),a=`import type { PricingConfig } from "../types/index.js";
|
|
346
346
|
|
|
347
347
|
export const pricingConfig: PricingConfig = {
|
|
348
348
|
defaultPlan: "free",
|
|
@@ -540,12 +540,12 @@ ${i}
|
|
|
540
540
|
]
|
|
541
541
|
}
|
|
542
542
|
};
|
|
543
|
-
`,l=`${e.projectDir}/packages/core/src/config/pricing.ts`;await p(l,a)}function ur(e){let t=[];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 r=e.frontend==="nuxt"?"Nuxt":e.frontend;if(t.push({type:"node-terminal",request:"launch",name:r,command:"pnpm dev",cwd:`\${workspaceFolder}/apps/web-${e.frontend}`,skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),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:"Email",command:"pnpm dev:email",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let n=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 ${n}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function fr(e){let t=e.frontend==="nuxt"?"Nuxt":e.frontend,r=[];return e.architecture==="separate"?r.push({name:`Dev (${t} + Backend + Inngest)`,configurations:["Backend",t,"Inngest"]}):r.push({name:`Dev (${t} + Inngest)`,configurations:[t,"Inngest"]}),r}async function
|
|
544
|
-
`)}import{readdir as gr}from"fs/promises";import{join as yr,relative as
|
|
545
|
-
`),Dr.magenta("Next steps"))}function
|
|
546
|
-
`),r.start("Generating configuration..."),await
|
|
547
|
-
`),S.log.success("License refreshed.")}catch{S.log.warn("License refresh skipped.")}if(i.version===d.latest){S.log.info(`Already on the latest version (${i.version}).`);return}let k=W(r,je);o.start(`Downloading v${d.latest} template...`),await J(l,d.latest,k),o.stop("Template staged.");let
|
|
548
|
-
`)}finally{await Nr(v,{recursive:!0,force:!0})}o.stop("Baseline hashes computed.")}await p(W(r,$e),JSON.stringify({currentVersion:i.version,targetVersion:d.latest,changelog:
|
|
549
|
-
`),S.log.info(`Update staged: ${ge.cyan(i.version)} \u2192 ${ge.cyan(d.latest)}`),S.log.info("Ask your AI assistant to "+ge.cyan("'update my GenerateSaaS project'")+".")}catch(a){o.stop("Failed."),S.cancel(`Update failed: ${I(a)}`),process.exit(1)}})}import*as h from"@clack/prompts";import
|
|
550
|
-
`),A.magenta("License Details"))}async function
|
|
551
|
-
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));i.length===0&&(w.cancel("No URLs found in file."),process.exit(1));let o=0;for(let a of i)await
|
|
543
|
+
`,l=`${e.projectDir}/packages/core/src/config/pricing.ts`;await p(l,a)}function ur(e){let t=[];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 r=e.frontend==="nuxt"?"Nuxt":e.frontend;if(t.push({type:"node-terminal",request:"launch",name:r,command:"pnpm dev",cwd:`\${workspaceFolder}/apps/web-${e.frontend}`,skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),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:"Email",command:"pnpm dev:email",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let n=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 ${n}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function fr(e){let t=e.frontend==="nuxt"?"Nuxt":e.frontend,r=[];return e.architecture==="separate"?r.push({name:`Dev (${t} + Backend + Inngest)`,configurations:["Backend",t,"Inngest"]}):r.push({name:`Dev (${t} + Inngest)`,configurations:[t,"Inngest"]}),r}async function nt(e){let t={version:"0.2.0",configurations:ur(e),compounds:fr(e)};await p(`${e.projectDir}/.vscode/launch.json`,JSON.stringify(t,null," ")+`
|
|
544
|
+
`)}import{readdir as gr}from"fs/promises";import{join as yr,relative as it}from"path";async function ot(e,t){let r=[],n=await gr(e,{withFileTypes:!0});for(let i of n){let o=yr(e,i.name),a=it(t,o);le(a)||(i.isDirectory()?r.push(...await ot(o,t)):i.isFile()&&r.push(o))}return r}async function ue(e){let r=(await ot(e,e)).sort(),n=await Promise.all(r.map(async i=>[it(e,i),await me(i)]));return Object.fromEntries(n)}import{existsSync as hr}from"fs";import{readFile as st,readdir as vr}from"fs/promises";import{join as E,dirname as Sr}from"path";import{fileURLToPath as wr}from"url";var ct={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Ir=Object.values(ct),Er="generatesaas-update",at=Sr(wr(import.meta.url));function br(){let e=E(at,"skill","content");return hr(e)?e:E(at,"content")}function Ae(e){return!e||e.length===0?Ir:e.map(t=>ct[t])}async function _e(e,t,r,n){let i=Ae(n);for(let o of i){let a=E(e,o,Er),l=E(a,"scripts"),d=E(a,"references");await de(l),await de(d),await p(E(a,"SKILL.md"),t),await p(E(d,".gitkeep"),"");for(let[u,R]of Object.entries(r))await p(E(l,u),R)}}async function pt(e,t){let r=br(),n=await st(E(r,"SKILL.md"),"utf-8"),i=E(r,"scripts"),o=await vr(i),a={};for(let l of o)l!==".gitkeep"&&(a[l]=await st(E(i,l),"utf-8"));await _e(e,n,a,t)}import{execFile as Ar,execFileSync as _r}from"child_process";import{access as Pr}from"fs/promises";import{join as Rr}from"path";import*as b from"@clack/prompts";function lt(e){try{return _r("which",[e],{stdio:"ignore"}),!0}catch{return!1}}function fe(e,t,r,n=3e5){return new Promise((i,o)=>{Ar(e,t,{cwd:r,timeout:n},a=>{a?o(a):i()})})}async function dt(e){if(!lt("pnpm"))return b.log.warn("pnpm not found. Skipping dependency installation."),b.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=b.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await fe("pnpm",["install"],e),t.stop("Dependencies installed."),!0}catch{return t.stop("Dependency installation failed."),b.log.warn("pnpm install failed. You can run it manually later."),!1}}async function mt(e){try{return await Pr(Rr(e,".git")),b.log.info("Git repository already exists, skipping init."),!0}catch{}if(!lt("git"))return b.log.warn("git not found. Skipping repository initialization."),!1;let t=b.spinner();t.start("Initializing git repository...");try{return await fe("git",["init"],e),await fe("git",["add","-A"],e),await fe("git",["commit","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),b.log.warn("You can run git init manually later."),!1}}import*as ut from"@clack/prompts";import Dr from"picocolors";function ft(e,t,r){let n=[];n.push(`cd ${e.projectDir}`),t||n.push("pnpm install"),n.push("Fill in .env with your API keys"),r?n.push("pnpm infra # Start Docker services"):n.push("# Using your existing services \u2014 no Docker setup needed"),n.push("pnpm dev # Start development server"),ut.note(n.join(`
|
|
545
|
+
`),Dr.magenta("Next steps"))}function ht(e){let t={};if(e.name!==void 0){if(!ae(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.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.frontend!==void 0&&(t.frontend=e.frontend),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===!1)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(e.blog!==void 0&&(t.blog=e.blog),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.docker!==void 0&&(t.dockerServices=yt(e.docker,ie,"docker service")),e.aiTools!==void 0&&(t.aiTools=yt(e.aiTools,oe,"AI tool")),e.currency!==void 0){if(!$.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${$.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!N.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${N.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!V.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${V.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!U.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${U.join(", ")}`);t.cacheProvider=e.cache}return t}var gt={projectName:"my-saas",frontend:"nuxt",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!1,revenueSharing:!1,dockerServices:["postgres","redis","inngest"],aiTools:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function vt(e){let t=e.projectName??gt.projectName,r=e.projectDir??`./${t}`;return{...gt,...e,projectName:t,projectDir:r}}function yt(e,t,r){if(e.trim()==="")return[];let n=e.split(",").map(o=>o.trim()).filter(Boolean),i=n.filter(o=>!t.includes(o));if(i.length>0)throw new Error(`Invalid ${r}(s): ${i.join(", ")}. Valid values: ${t.join(", ")}`);return n}function St(e){e.command("init").description("Scaffold a new GenerateSaaS project").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("-l, --location <path>","project directory (default: ./{name})").addOption(new x("--architecture <type>","fullstack or separate").choices([...te])).addOption(new x("--payment <provider>","payment provider").choices([...re])).addOption(new x("--email <provider>","email provider").choices([...ne])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new x("--billing-scope <scope>","billing scope (requires --org)").choices([...se])).option("--blog","enable blog").option("--no-blog","disable blog").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--docker <services>","comma-separated: postgres,redis,inngest,mailpit").option("--ai-tools <tools>","comma-separated: claude-code,cursor,codex,gemini-cli,windsurf").addOption(new x("--currency <code>","default currency for billing").choices([...$])).addOption(new x("--deploy <target>","deployment target").choices([...N])).addOption(new x("--database <provider>","database provider").choices([...V])).addOption(new x("--cache <provider>","cache provider").choices([...U])).option("-y, --yes","accept defaults for unspecified options (non-interactive)").action(async t=>{await Lr(t)})}async function Lr(e){Re();let t;try{t=ht(e)}catch(f){g.cancel(I(f)),process.exit(1)}let r=g.spinner(),n;try{n=await q({prompt:!e.yes})}catch(f){g.cancel(I(f)),process.exit(1)}let i=K(n);r.start("Verifying access...");let o;try{o=(await Y(i)).latest,r.stop("Access verified."),Ne(n)}catch(f){r.stop("Access verification failed."),f instanceof P&&f.status===401?g.cancel("Invalid API key. Check your key and try again."):g.cancel(I(f)),process.exit(1)}g.log.success(`Latest version: ${o}`);let a;r.start("Activating license...");try{let f=crypto.randomUUID();a={token:(await Me(i,{frontend:"nuxt",version:o,installId:f})).token,keyHash:Xe(n),installId:f},r.stop("License activated.")}catch{r.stop("License activation skipped."),g.log.warn("Could not activate license. You can retry with 'generatesaas update'.")}let l;e.yes?l=vt(t):l=await Oe(t);let d=Or(l.projectDir);if(Tr(d)&&xr(d).length>0)if(e.yes)g.log.info(`Directory ${d} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let v=await g.select({message:`Directory ${d} 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"}]});(g.isCancel(v)||v==="cancel")&&(g.cancel("Setup cancelled."),process.exit(0)),v==="overwrite"&&kr(d,{recursive:!0,force:!0})}let u={...l,projectDir:d,version:o};r.start("Downloading template...");try{await J(i,o,d),r.stop("Template downloaded.")}catch(f){r.stop("Download failed."),g.cancel(I(f)),process.exit(1)}let R=await ue(d);await p(Cr(d,pe),JSON.stringify(R,null," ")+`
|
|
546
|
+
`),r.start("Generating configuration..."),await He(u),await rt(u),r.stop("Configuration generated."),r.start("Generating environment files..."),await Je(u),r.stop("Environment files generated.");let k=await Ke(u);k&&g.log.success("Docker Compose generated."),await nt(u),r.start("Generating infrastructure..."),await qe(u),await ze(u),await Ge(u),await tt(u),r.stop("Infrastructure generated."),r.start("Installing AI skills..."),await pt(d,u.aiTools),r.stop("AI skills installed."),r.start("Generating manifest..."),await et(u,a),r.stop("Manifest generated.");let B=await dt(d);await mt(d),ft(u,B,k),De()}import{existsSync as jr}from"fs";import{readFile as $r,rm as Nr}from"fs/promises";import{join as W,resolve as Vr}from"path";import{mkdtemp as Ur}from"fs/promises";import{tmpdir as Mr}from"os";import*as S from"@clack/prompts";import ge from"picocolors";function wt(e){e.command("update").description("Update AI skill files and stage template updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=Vr(t.cwd??process.cwd()),n=W(r,H),i;try{i=JSON.parse(await $r(n,"utf-8"))}catch{S.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=S.spinner();try{let a=await q(),l=K(a);o.start("Fetching latest skill files...");let d=await Y(l),u=await Ue(l,d.latest);await _e(r,u.skillMd,u.scripts,i.aiTools);let R=Ae(i.aiTools);if(o.stop("Skills updated."),S.log.success(`Skill files installed to ${ge.cyan(R.length.toString())} locations.`),i.licenseToken)try{let v=await Fe(l,{currentToken:i.licenseToken,newVersion:d.latest});i.licenseToken=v.token,await p(n,JSON.stringify(i,null," ")+`
|
|
547
|
+
`),S.log.success("License refreshed.")}catch{S.log.warn("License refresh skipped.")}if(i.version===d.latest){S.log.info(`Already on the latest version (${i.version}).`);return}let k=W(r,je);o.start(`Downloading v${d.latest} template...`),await J(l,d.latest,k),o.stop("Template staged.");let B=await Ve(l,d.latest),f=W(r,pe);if(!jr(f)){o.start("Computing baseline template hashes (one-time migration)...");let v=await Ur(W(Mr(),"gs-update-"));try{await J(l,i.version,v);let ye=await ue(v);await p(f,JSON.stringify(ye,null," ")+`
|
|
548
|
+
`)}finally{await Nr(v,{recursive:!0,force:!0})}o.stop("Baseline hashes computed.")}await p(W(r,$e),JSON.stringify({currentVersion:i.version,targetVersion:d.latest,changelog:B,stagedAt:new Date().toISOString()},null," ")+`
|
|
549
|
+
`),S.log.info(`Update staged: ${ge.cyan(i.version)} \u2192 ${ge.cyan(d.latest)}`),S.log.info("Ask your AI assistant to "+ge.cyan("'update my GenerateSaaS project'")+".")}catch(a){o.stop("Failed."),S.cancel(`Update failed: ${I(a)}`),process.exit(1)}})}import*as h from"@clack/prompts";import F from"picocolors";import{readFile as Fr}from"fs/promises";import{join as Br,resolve as Gr}from"path";function It(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=Gr(t.cwd??process.cwd()),n=Br(r,H),i;try{i=JSON.parse(await Fr(n,"utf-8"))}catch{h.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}h.log.info(`${F.bold("Project Status")}`),h.log.info(` Version: ${F.cyan(i.version)}`),h.log.info(` Frontend: ${F.cyan(i.frontend)}`);let o=h.spinner();o.start("Checking for updates...");try{let a=await q(),l=K(a),u=(await Y(l)).latest;i.version===u?(o.stop("Up to date."),h.log.success(`Already on the latest version (${F.green(u)})`)):(o.stop("Update available."),h.log.warning(`Update available: ${F.yellow(i.version)} \u2192 ${F.green(u)}`),h.log.info(`Run ${F.cyan("generatesaas update")} to update skill files, then ask your AI assistant to apply the update.`))}catch(a){o.stop("Check failed."),a instanceof P&&a.status===401?h.log.warning("Invalid API key. Check your key and try again."):h.log.warning(`Could not check for updates: ${I(a)}`)}})}import{readFile as Hr}from"fs/promises";import*as w from"@clack/prompts";import A from"picocolors";function zr(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Pe(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Et(e){w.note([`License ID: ${A.cyan(String(e.lid??"unknown"))}`,`Version: ${A.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Pe(e.pat)}`,`Last updated: ${Pe(e.uat)}`,`Expires: ${Pe(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
550
|
+
`),A.magenta("License Details"))}async function bt(e){let t=w.spinner(),r=e.replace(/\/+$/,"");t.start(`Checking ${r}/license...`);let n;try{let o=await fetch(`${r}/license`);if(!o.ok)return t.stop(`${A.red("Not found")} \u2014 ${r}/license returned ${o.status}`),!1;if(n=await o.text(),!n||n.split(".").length!==3)return t.stop(`${A.red("Invalid")} \u2014 response is not a JWT`),!1;t.stop(`${A.green("Found")} \u2014 license endpoint responded`)}catch(o){return t.stop(`${A.red("Failed")} \u2014 ${I(o)}`),!1}let i;try{i=zr(n)}catch{return w.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let o=process.env.GENERATESAAS_API_URL??ce,a=await Be(o,n);if(a.valid)t.stop(`${A.green("Valid")} \u2014 signature verified`);else return t.stop(`${A.red("Invalid")} \u2014 ${a.reason}`),!1}catch{return t.stop(`${A.yellow("Skipped")} \u2014 could not reach verification service`),w.log.warn("Signature not verified. Displaying unverified claims:"),Et(i),!1}return Et(i),!0}function At(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/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(w.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await Hr(r.file,"utf-8")).split(`
|
|
551
|
+
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));i.length===0&&(w.cancel("No URLs found in file."),process.exit(1));let o=0;for(let a of i)await bt(a)&&o++,w.log.info("");w.log.success(`${o}/${i.length} sites verified.`)}else await bt(t)||process.exit(1)})}var X=new Kr().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("0.2.3");St(X);wt(X);It(X);At(X);X.parseAsync().catch(e=>{_t.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|