Skip to content

borghei/Claude-Skills / engineering/saas-scaffolder

saas-scaffolder

Verified

Lays down a Next.js SaaS skeleton (provider-specific deps, env, Drizzle tenancy schema, middleware) and guides auth, billing and tenant isolation. Use when starting a SaaS, subscription app or multi-tenant platform.

scripts/saas_scaffolder.py

View on GitHub
#!/usr/bin/env python3
"""SaaS Project Scaffolder: lay down a Next.js SaaS skeleton for the chosen providers.

Writes the tree, a package.json whose dependencies follow --auth/--db/--payments,
a provider-filtered .env.example, a Drizzle schema shaped by --tenancy, configs and
middleware. Other files are stubs naming the reference section to implement them
from. Dependencies are npm dist-tags, not pins. Stdlib only.
Exit codes: 0 = done, 2 = bad input (invalid --name, or --output not empty).
"""

import argparse
import json
import os
import re
import sys
from datetime import datetime, timezone

REF_AUTH = "references/auth-billing-and-tenancy.md"
REF_SCHEMA = "references/project-structure-and-schema.md"

BASE_DEPS = {"next": "^16.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "latest",
             "drizzle-orm": "latest", "@paralleldrive/cuid2": "latest"}
DEV_DEPS = {"typescript": "latest", "drizzle-kit": "latest", "tailwindcss": "^4.0.0",  # tags = unpinned: commit the lockfile
            "@tailwindcss/postcss": "^4.0.0", "@types/node": "latest", "@types/react": "^19.0.0",
            "tsx": "latest", "eslint": "latest", "prettier": "latest"}
AUTH_DEPS = {"nextauth": {"next-auth": "beta", "@auth/drizzle-adapter": "latest"},  # v5 API ships on the beta tag
             "clerk": {"@clerk/nextjs": "latest"},
             "supabase": {"@supabase/supabase-js": "latest", "@supabase/ssr": "latest"}}
DB_DEPS = {"neondb": {"@neondatabase/serverless": "latest"}, "supabase": {"postgres": "latest"}, "postgres": {"postgres": "latest"}}
PAY_DEPS = {"stripe": {"stripe": "latest"}, "lemonsqueezy": {"@lemonsqueezy/lemonsqueezy.js": "latest"}, "none": {}}

ENV_BLOCKS = {  # each value is a list of .env.example lines
    'app': ['# App', 'NEXT_PUBLIC_APP_URL=http://localhost:3000'],
    'db': ['# Database', 'DATABASE_URL=              # postgresql://user:pass@host/db?sslmode=require'],
    'nextauth': ['# Auth.js', 'AUTH_SECRET=               # openssl rand -base64 32', '# AUTH_URL is optional (inferred from the request); set AUTH_TRUST_HOST=true behind a reverse proxy', 'AUTH_GOOGLE_ID=', 'AUTH_GOOGLE_SECRET=', 'AUTH_GITHUB_ID=', 'AUTH_GITHUB_SECRET=', 'RESEND_API_KEY='],
    'clerk': ['# Clerk', 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=', 'CLERK_SECRET_KEY='],
    'supabase': ['# Supabase', 'NEXT_PUBLIC_SUPABASE_URL=', 'NEXT_PUBLIC_SUPABASE_ANON_KEY='],
    'stripe': ['# Stripe', 'STRIPE_SECRET_KEY=', 'STRIPE_WEBHOOK_SECRET=', 'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=', 'STRIPE_PRO_MONTHLY_PRICE_ID=', 'STRIPE_PRO_YEARLY_PRICE_ID='],
    'lemonsqueezy': ['# Lemon Squeezy', 'LEMONSQUEEZY_API_KEY=', 'LEMONSQUEEZY_STORE_ID=', 'LEMONSQUEEZY_WEBHOOK_SECRET='],
}

MIDDLEWARE = {
    "nextauth": """export { auth as {fn} } from '@/lib/auth'

export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'] }
""",
    "clerk": """import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const isProtected = createRouteMatcher(['/dashboard(.*)', '/settings(.*)'])

export default clerkMiddleware(async (auth, req) => {
  if (isProtected(req)) await auth.protect()
})

export const config = { matcher: ['/((?!_next|.*\\\\..*).*)', '/(api|trpc)(.*)'] }
""",
    "supabase": f"""// STUB generated by saas_scaffolder.py.
// Refresh the Supabase session cookie and redirect signed-out users away from /dashboard.
// Implement with @supabase/ssr createServerClient; see the middleware section of {REF_AUTH}.
export {{}}
""",
}

DRIZZLE_CONFIG = """import { defineConfig } from 'drizzle-kit'

export default defineConfig({
  schema: './db/schema.ts',
  out: './db/migrations',
  dialect: 'postgresql',
  dbCredentials: { url: process.env.DATABASE_URL! },
})
"""

SCHEMA_HEAD = """import { pgTable, text, timestamp, uniqueIndex, index } from 'drizzle-orm/pg-core'
import { createId } from '@paralleldrive/cuid2'
"""
BILLING_COLS = """  plan: text('plan').notNull().default('free'),
  {p}CustomerId: text('{p}_customer_id').unique(),
  {p}SubscriptionId: text('{p}_subscription_id'),
  {p}PriceId: text('{p}_price_id'),
  {p}CurrentPeriodEnd: timestamp('{p}_current_period_end', { withTimezone: true }),
"""
USERS = """
export const users = pgTable('users', {
  id: text('id').primaryKey().$defaultFn(createId),
  email: text('email').notNull().unique(),
  name: text('name'),
  emailVerified: timestamp('email_verified', { withTimezone: true }),
{billing}  createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
})
"""
TENANT = """
export const {t}s = pgTable('{t}s', {{
  id: text('id').primaryKey().$defaultFn(createId),
  name: text('name').notNull(),
  slug: text('slug').notNull(),
{billing}  createdAt: timestamp('created_at', {{ withTimezone: true }}).defaultNow().notNull(),
}}, (t) => [uniqueIndex('{t}s_slug_idx').on(t.slug)])

// Every tenant-owned table carries {t}Id; every query filters on it.
export const {t}Members = pgTable('{t}_members', {{
  id: text('id').primaryKey().$defaultFn(createId),
  {t}Id: text('{t}_id').notNull().references(() => {t}s.id, {{ onDelete: 'cascade' }}),
  userId: text('user_id').notNull().references(() => users.id, {{ onDelete: 'cascade' }}),
  role: text('role').notNull().default('member'),
  joinedAt: timestamp('joined_at', {{ withTimezone: true }}).defaultNow().notNull(),
}}, (t) => [
  uniqueIndex('{t}_members_unique').on(t.{t}Id, t.userId),
  index('{t}_members_{t}_idx').on(t.{t}Id),
])
"""

HEALTH = "export function GET() {\n  return Response.json({ status: 'ok' })\n}\n"
NEXT_CONFIG = "import type { NextConfig } from 'next'\n\nconst nextConfig: NextConfig = {}\n\nexport default nextConfig\n"
TSCONFIG = {"compilerOptions": {"target": "ES2022", "lib": ["dom", "dom.iterable", "esnext"], "strict": True,
                                "module": "esnext", "moduleResolution": "bundler", "jsx": "preserve", "noEmit": True,
                                "esModuleInterop": True, "skipLibCheck": True, "resolveJsonModule": True,
                                "isolatedModules": True, "incremental": True, "plugins": [{"name": "next"}],
                                "paths": {"@/*": ["./*"]}},
            "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"]}

# Stub path prefix -> where the agent finds the implementation
STUB_SOURCES = [
    ("app/api/auth", f"{REF_AUTH} (Authentication Configuration)"),
    ("lib/auth.ts", f"{REF_AUTH} (Authentication Configuration)"),
    ("app/api/webhooks", f"{REF_AUTH} (Webhook Handler)"),
    ("app/api/billing", f"{REF_AUTH} (Checkout Session)"),
    ("lib/billing.ts", f"{REF_AUTH} (Stripe Billing Integration)"),
    ("lib/db.ts", f"{REF_SCHEMA} (Database Schema)"),
    ("db/seed.ts", f"{REF_SCHEMA} (Database Schema)"),
    ("hooks", f"{REF_AUTH} (Multi-Tenancy Patterns)"),
]


def build_tree(payments, tenancy, auth, features, next_major=16):
    """Return the list of relative file paths for the project."""
    files = ["proxy.ts" if next_major >= 16 else "middleware.ts"] + [
        "app/(auth)/login/page.tsx", "app/(auth)/register/page.tsx", "app/(auth)/layout.tsx",
        "app/(dashboard)/dashboard/page.tsx", "app/(dashboard)/settings/page.tsx", "app/(dashboard)/layout.tsx",
        "app/(marketing)/page.tsx", "app/(marketing)/pricing/page.tsx", "app/(marketing)/layout.tsx",
        "app/api/health/route.ts", "app/layout.tsx", "app/not-found.tsx", "app/globals.css",
        "components/dashboard/sidebar.tsx", "components/dashboard/header.tsx",
        "components/marketing/hero.tsx", "components/marketing/pricing-card.tsx",
        "lib/db.ts", "lib/validations.ts", "lib/utils.ts", "db/schema.ts", "db/seed.ts",
        "hooks/use-current-user.ts", ".env.example", "drizzle.config.ts",
        "postcss.config.mjs", "next.config.ts", "package.json", "tsconfig.json", "README.md",
    ]
    if auth == "nextauth":
        files += ["app/api/auth/[...nextauth]/route.ts", "lib/auth.ts"]
    if tenancy != "none":
        files += ["app/(dashboard)/settings/team/page.tsx", f"hooks/use-current-{tenancy}.ts"]
    if payments != "none":
        files += [f"app/api/webhooks/{payments}/route.ts", "app/api/billing/checkout/route.ts",
                  "app/api/billing/portal/route.ts", "app/(dashboard)/settings/billing/page.tsx",
                  "components/billing/plan-card.tsx", "lib/billing.ts", "hooks/use-subscription.ts"]
    for feat in features:
        slug = re.sub(r"[^a-z0-9-]+", "-", feat.lower()).strip("-")
        if slug:
            files.append(f"app/(dashboard)/{slug}/page.tsx")
    return sorted(set(files))


def render_tree(name, files):
    """Render file paths as an indented tree."""
    lines, seen = [f"{name}/"], set()
    for path in files:
        parts = path.split("/")
        for depth in range(1, len(parts)):
            d = "/".join(parts[:depth])
            if d not in seen:
                seen.add(d)
                lines.append("  " * depth + parts[depth - 1] + "/")
        lines.append("  " * len(parts) + parts[-1])
    return "\n".join(lines)


def schema_ts(tenancy, payments):
    """Billing columns live on the tenant table, or on users when there is no tenancy."""
    prefix = "stripe" if payments == "stripe" else "billing"
    billing = BILLING_COLS.replace("{p}", prefix) if payments != "none" else ""
    users = USERS.replace("{billing}", billing if tenancy == "none" else "")
    return SCHEMA_HEAD + users + ("" if tenancy == "none" else TENANT.format(t=tenancy, billing=billing))


def package_json(args):
    deps = dict(BASE_DEPS, **AUTH_DEPS[args.auth], **DB_DEPS[args.db], **PAY_DEPS[args.payments])
    deps["next"] = f"^{args.next_major}.0.0"  # keep the range in step with proxy.ts vs middleware.ts
    return json.dumps({
        "name": args.name, "version": "0.1.0", "private": True,
        "scripts": {"dev": "next dev", "build": "next build", "start": "next start", "lint": "eslint .",
                    "db:generate": "drizzle-kit generate", "db:migrate": "drizzle-kit migrate",
                    "db:seed": "tsx db/seed.ts"},
        "dependencies": dict(sorted(deps.items())), "devDependencies": dict(sorted(DEV_DEPS.items())),
    }, indent=2) + "\n"


def stub(path):
    """Content for a file the tool does not implement."""
    source = next((src for prefix, src in STUB_SOURCES if path.startswith(prefix)), None)
    note = f"Implement from the saas-scaffolder skill: {source}." if source else "Implement for your product."
    if path.endswith((".ts", ".tsx")):
        return f"// STUB generated by saas_scaffolder.py. {note}\nexport {{}}\n"
    if path.endswith(".css"):
        return '@import "tailwindcss";\n'
    return ""


def content_for(path, args):
    fixed = {
        "package.json": lambda: package_json(args),
        ".env.example": lambda: "\n".join("\n".join(ENV_BLOCKS[k]) + "\n" for k in ("app", "db", args.auth, args.payments)
                                          if k in ENV_BLOCKS),
        "proxy.ts": lambda: MIDDLEWARE[args.auth].replace("{fn}", "proxy"),  # Next 16+
        "middleware.ts": lambda: MIDDLEWARE[args.auth].replace("{fn}", "middleware"),
        "drizzle.config.ts": lambda: DRIZZLE_CONFIG,
        "db/schema.ts": lambda: schema_ts(args.tenancy, args.payments),
        "app/api/health/route.ts": lambda: HEALTH,
        "next.config.ts": lambda: NEXT_CONFIG,
        "tsconfig.json": lambda: json.dumps(TSCONFIG, indent=2) + "\n",
        "postcss.config.mjs": lambda: "export default { plugins: { '@tailwindcss/postcss': {} } }\n",
        "README.md": lambda: (f"# {args.name}\n\nScaffolded: auth={args.auth}, db={args.db}, payments={args.payments}, "
                              f"tenancy={args.tenancy}.\n\n1. `npm install` once and commit the lockfile: deps without a `^` range use npm tags,\n"
                              "   so the lockfile is what makes installs reproducible.\n"
                              + ("   Auth.js is now part of Better Auth; check authjs.dev before a new auth setup.\n"
                                 if args.auth == "nextauth" else "") + "2. Copy `.env.example` to `.env.local` and fill it in.\n"
                              "3. `npm run db:generate && npm run db:migrate`.\n"
                              "4. Replace every `// STUB` file (`grep -rl 'STUB generated' .`).\n"),
    }
    return fixed[path]() if path in fixed else stub(path)


def fail(msg):
    sys.exit(print(f"error: {msg}", file=sys.stderr) or 2)

def main():
    parser = argparse.ArgumentParser(
        description="Lay down a Next.js SaaS skeleton: tree, provider-specific package.json, .env.example, "
                    "Drizzle schema and middleware; other files are stubs that point at the references.",
        epilog="example: %(prog)s --name acme --auth clerk --payments none --output /tmp/acme --dry-run")
    parser.add_argument("--name", required=True, help="npm package name: lowercase letters, digits, - . _")
    parser.add_argument("--output", default=None, help="Output directory (default: ./<name>); must be empty or absent")
    parser.add_argument("--auth", choices=sorted(AUTH_DEPS), default="nextauth", help="Auth provider")
    parser.add_argument("--db", choices=sorted(DB_DEPS), default="neondb", help="Postgres host (driver dependency)")
    parser.add_argument("--payments", choices=sorted(PAY_DEPS), default="stripe", help="Billing provider")
    parser.add_argument("--tenancy", choices=["workspace", "organization", "none"], default="workspace",
                        help="Tenancy model (shapes the schema)")
    parser.add_argument("--features", default="", help="Comma-separated extra dashboard pages")
    parser.add_argument("--next-major", type=int, default=16, help="Next.js major: 16+ writes proxy.ts, older middleware.ts")
    parser.add_argument("--dry-run", action="store_true", help="Print the plan without writing files")
    parser.add_argument("--format", choices=["text", "json"], default="text", help="Output format")
    parser.add_argument("--json", action="store_const", const="json", dest="format", help="Same as --format json")
    args = parser.parse_args()

    if not re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,213}", args.name):
        fail(f"--name {args.name!r} is not a valid npm package name (lowercase letters, digits, '-', '.', '_')")
    output_dir = os.path.abspath(args.output or os.path.join(".", args.name))
    if os.path.exists(output_dir) and (not os.path.isdir(output_dir) or os.listdir(output_dir)):
        fail(f"{output_dir} exists and is not an empty directory; refusing to overwrite")
    features = [f.strip() for f in args.features.split(",") if f.strip()]
    files = build_tree(args.payments, args.tenancy, args.auth, features, args.next_major)

    written, stubs = [], []
    for rel in files:
        text = content_for(rel, args)
        stubs += [rel] if text.startswith("// STUB") else []
        if args.dry_run:
            continue
        path = os.path.join(output_dir, rel)
        try:
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(path, "w", encoding="utf-8") as f:
                f.write(text)
        except OSError as e:
            fail(f"cannot write {path}: {e.strerror}")
        written.append(rel)

    pkg = json.loads(package_json(args))
    result = {
        "project_name": args.name, "output_directory": output_dir, "auth_provider": args.auth,
        "database_provider": args.db, "payment_provider": args.payments, "tenancy_model": args.tenancy,
        "extra_features": features, "dry_run": args.dry_run, "files_planned": len(files),
        "files_written": len(written), "stub_files": stubs, "dependencies": sorted(pkg["dependencies"]),
        "tree": render_tree(args.name, files), "generated_at": datetime.now(timezone.utc).isoformat(),
    }
    if args.format == "json":
        return print(json.dumps(result, indent=2))
    print(f"SaaS Scaffolder: {args.name}  (auth={args.auth}, db={args.db}, payments={args.payments}, "
          f"tenancy={args.tenancy})")
    print(f"Output: {output_dir}{'  [dry run: nothing written]' if args.dry_run else ''}\n\n{result['tree']}")
    print(f"\nDependencies: {', '.join(result['dependencies'])}")
    print(f"{len(files) - len(stubs)} files with content, {len(stubs)} stubs to implement "
          f"(each names its reference section).")
    print("next/react/tailwind use ^ ranges; other deps use npm tags. Run npm install once and commit the lockfile.")


if __name__ == "__main__":
    main()
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall