spfn 0.2.0-beta.5 → 0.2.0-beta.51

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 INFLIKE Inc.
3
+ Copyright (c) 2025 FXY Inc.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,260 +1,358 @@
1
- # spfn
1
+ # spfn — the SPFN CLI (backend layer for Next.js)
2
2
 
3
- > Superfunction CLI - The Backend Layer for Next.js
3
+ `spfn` scaffolds and runs a Hono-based backend that lives inside a Next.js project.
4
+ It creates the server structure, runs the dev/build/start lifecycle, manages the
5
+ database (Drizzle Kit), generates the RPC route map, and validates environment variables.
4
6
 
5
- The official CLI tool for SPFN framework. Initialize projects, generate boilerplate code, and manage your database.
7
+ > Beta: install with the `@beta` tag (`spfn@beta`). The binary is `spfn`.
6
8
 
7
- ## Usage
9
+ ## Install
8
10
 
9
- > ⚠️ **Alpha Release**: SPFN is currently in alpha. Use `@alpha` tag for installation.
11
+ No global install needed run through your package manager's dlx/npx:
10
12
 
11
- ### Quick Start (New Project)
12
13
  ```bash
13
- # Create new project with all SPFN features pre-configured
14
- npx spfn@alpha create my-app
15
- cd my-app
16
- docker compose up -d
17
- npm run spfn:dev
14
+ npx spfn@beta <command>
15
+ pnpm dlx spfn@beta <command>
18
16
  ```
19
17
 
20
- ### Add to Existing Next.js Project
18
+ Or add it as a project dependency (`spfn init`/`spfn create` do this for you), then
19
+ call it via `pnpm spfn <command>` / `npm run spfn:<script>`.
20
+
21
+ Requirements: Node.js 18.18+, Next.js 15+ (App Router, `src/` dir), PostgreSQL (Redis optional).
22
+
23
+ ## Usage
24
+
21
25
  ```bash
22
- # Using npx (no installation required) - Recommended
23
- npx spfn@alpha init
26
+ # New project (runs create-next-app + spfn init)
27
+ npx spfn@beta create my-app
28
+ cd my-app
29
+ docker compose up -d # Postgres + Redis
30
+ cp .env.local.example .env.local
31
+ pnpm spfn:dev # Next.js :3790 + SPFN API :8790
24
32
 
25
- # Or install globally (alpha version)
26
- npm install -g spfn@alpha
27
- spfn init
33
+ # Add SPFN to an existing Next.js project
34
+ npx spfn@beta init
28
35
  ```
29
36
 
37
+ The package manager is auto-detected (pnpm > yarn > bun > npm) from lockfiles; override
38
+ with `--pm`. In a pnpm workspace, `create` installs from the workspace root.
39
+
40
+ ---
41
+
30
42
  ## Commands
31
43
 
32
- ### Create New Project
33
- ```bash
34
- spfn create <name> # Create new Next.js project with SPFN (all-in-one)
35
- spfn create my-app # Example: Create project with TypeScript, App Router, SVGR, and SPFN
36
- spfn create my-app --shadcn # Include shadcn/ui component library
37
- ```
44
+ Registered top-level commands: `create`, `init`, `add`, `dev`, `build`, `start`,
45
+ `codegen`, `db`, `env`, `key`, `setup`.
38
46
 
39
- ### Project Initialization
40
- ```bash
41
- spfn init # Initialize SPFN in existing Next.js project
42
- spfn init -y # Skip prompts, use defaults
43
- ```
47
+ ### `spfn create <name>`
44
48
 
45
- **What `spfn init` creates:**
46
- - `src/lib/contracts/` - API contracts (shared between frontend and backend)
47
- - `src/server/routes/` - Backend route handlers
48
- - `src/server/entities/` - Database entities (Drizzle ORM)
49
- - `docker-compose.yml` - PostgreSQL + Redis for local development
50
- - `Dockerfile`, `.dockerignore`, `docker-compose.production.yml` - Production deployment
51
- - `.env.local.example` - Environment variable template
52
- - `spfn.config.js` - Deployment configuration with JSDoc type hints
53
- - `.spfnrc.json` - Code generation configuration
54
-
55
- **SPFN's Contract-Based Architecture:**
56
- - **Contracts** (`src/lib/contracts/`): Define API endpoints with absolute paths (e.g., `/users/:id`)
57
- - **Handlers** (`src/server/routes/`): Import contracts and implement business logic
58
- - **Frontend**: Import contracts for type-safe API calls
59
- - **Auto-generated Client**: `src/lib/api/` is auto-generated from contracts (via `spfn dev` or `spfn build`)
60
-
61
- ### Generate Function Modules
62
- ```bash
63
- spfn generate fn <name> # Generate new SPFN function module (interactive)
64
- spfn g fn <name> # Short alias
49
+ Runs `create-next-app` with SPFN-recommended flags (TypeScript, App Router, `src/`,
50
+ Tailwind, import alias `@/*`, no ESLint), sets up SVGR icons, then runs `init`.
65
51
 
66
- # With options
67
- spfn g fn blog -e posts,comments -y # Create blog module with posts & comments entities
68
- spfn g fn shop -d "E-commerce shop" -e products,orders,customers
69
- ```
52
+ | Option | Description |
53
+ |--------|-------------|
54
+ | `--pm <manager>` | Force package manager: `npm` \| `pnpm` \| `yarn` \| `bun` |
55
+ | `--shadcn` | Also run `shadcn init` |
56
+ | `--skip-install` | Skip dependency install |
57
+ | `--skip-git` | Skip `git init` |
58
+ | `-y, --yes` | Skip prompts, use defaults |
70
59
 
71
- **What `spfn generate fn` creates:**
72
- - `packages/<name>/` - New function module in monorepo
73
- - `src/server/entities/schema.ts` - **Exported schema** (ensures CREATE SCHEMA in migrations)
74
- - `src/server/entities/*.ts` - Drizzle ORM entity definitions (import schema)
75
- - `src/server/repositories/` - CRUD repository layer
76
- - `src/server/routes/` - RESTful API route handlers
77
- - `src/lib/contracts/` - TypeBox API contracts
78
- - `package.json` - Pre-configured with SPFN metadata
79
- - `tsup.config.ts` - Build configuration
80
- - `drizzle.config.ts` - Database migration setup
81
-
82
- **Database Schema Naming:**
83
- - Scope and module name are automatically converted to safe PostgreSQL schema names
84
- - Examples: `@my-company/blog` → `my_company_blog`, `@spfn/cms` → `spfn_cms`
85
- - Special characters (`.`, `!`, `-`) are converted to underscores
86
- - Names starting with numbers get `_` prefix (e.g., `@123company` → `_123company`)
87
- - Ensures PostgreSQL compatibility (lowercase, numbers, underscores only)
88
-
89
- **Options:**
90
- - `-e, --entities <list>` - Comma-separated entity names
91
- - `-d, --description <text>` - Module description
92
- - `--skip-routes` - Generate entities without routes
93
- - `--skip-cache` - Skip cache generation
94
- - `-y, --yes` - Skip all prompts
95
-
96
- **Example workflow:**
97
- ```bash
98
- # 1. Generate module
99
- spfn g fn blog -e posts,comments -y
60
+ ### `spfn init`
100
61
 
101
- # 2. Build the module
102
- cd packages/blog
103
- npm run build
62
+ Adds SPFN to an existing Next.js project: copies the server templates, wires the RPC
63
+ proxy route, Docker files, deploy + codegen config, updates `package.json` scripts/deps,
64
+ and installs. See [Scaffold structure](#scaffold-structure) for what lands on disk.
104
65
 
105
- # 3. Install in your app
106
- spfn add @spfn/blog
107
- ```
66
+ | Option | Description |
67
+ |--------|-------------|
68
+ | `-y, --yes` | Skip prompts, use defaults |
69
+
70
+ ### `spfn add <package>`
71
+
72
+ Installs an SPFN ecosystem package and applies its pre-built migrations. The package
73
+ name must be scoped (contain `/`).
108
74
 
109
- ### Install Ecosystem Packages
110
75
  ```bash
111
- spfn add <package> # Install SPFN ecosystem package with automatic DB setup
112
- spfn add @spfn/cms # Install CMS package
113
- spfn add @company/plugin # Install third-party SPFN package
76
+ pnpm spfn add @spfn/cms
77
+ pnpm spfn add @mycompany/spfn-analytics
114
78
  ```
115
79
 
116
- **What `spfn add` does:**
117
- 1. Installs the package via pnpm/npm
118
- 2. Discovers package's pre-built migrations
119
- 3. Applies package migrations to your database
120
- 4. ✅ Shows package-specific setup guide
80
+ How it works: if not already present it installs the package, then reads the package's
81
+ `spfn` field in its `package.json` (`migrations`, `setupMessage`) and applies any
82
+ function migrations to `DATABASE_URL`. If `DATABASE_URL` is unset, migration is skipped
83
+ with a hint to run `spfn db push` later. Works with published and workspace packages.
121
84
 
122
- **Example: Installing @spfn/cms**
123
- ```bash
124
- $ pnpm spfn add @spfn/cms
85
+ ### `spfn dev`
86
+
87
+ Starts the SPFN server + Next.js (and a codegen watcher). The server must report ready
88
+ (via a `.spfn/server-ready` signal file) before Next.js launches. Runs through `tsx`,
89
+ no pre-build needed.
90
+
91
+ | Option | Description | Default |
92
+ |--------|-------------|---------|
93
+ | `--server-only` | Run only the SPFN/Hono server (also auto-selected if Next.js isn't a dependency) | off |
94
+ | `--watch` | Restart the server on `src/server` changes (chokidar) | off |
95
+ | `-p, --port <port>` | Server port | from `server.config.ts` / env (`4000` in server-only fallback) |
96
+ | `-H, --host <host>` | Server host | `localhost` |
97
+ | `--routes <path>` | Routes directory path | server default |
98
+
99
+ Note: hot reload is **off by default** — pass `--watch` to restart on file changes.
100
+
101
+ ### `spfn build`
102
+
103
+ Runs codegen, builds Next.js (via the project's `build` script), and compiles
104
+ `src/server/**/*.ts` → `.spfn/server` with tsup. Also writes `.spfn/prod-server.mjs`
105
+ (the production entry consumed by `spfn start`).
106
+
107
+ | Option | Description |
108
+ |--------|-------------|
109
+ | `--server-only` | Build only the SPFN server (skip Next.js) |
110
+ | `--next-only` | Build only Next.js (skip the SPFN server) |
111
+ | `--turbo` | Use Turbopack for the Next.js build |
112
+
113
+ ### `spfn start`
114
+
115
+ Starts the production servers from build output. Requires `spfn build` first — it errors
116
+ if `.spfn/server`, `.spfn/prod-server.mjs`, or `.next` are missing.
117
+
118
+ | Option | Description | Default |
119
+ |--------|-------------|---------|
120
+ | `--server-only` | Run only the SPFN server | off |
121
+ | `--next-only` | Run only Next.js | off |
122
+ | `-p, --port <port>` | SPFN server port (sets `SPFN_PORT`) | `8790` |
123
+ | `-h, --host <host>` | SPFN server host (sets `SPFN_HOST`) | `0.0.0.0` |
124
+
125
+ Next.js is started on `0.0.0.0:3790`. Both run together via `concurrently --kill-others`.
126
+
127
+ ### `spfn codegen`
125
128
 
126
- 📦 Setting up @spfn/cms...
127
- Package installed
129
+ Manages code generators driven by `.spfnrc.ts`. The default generator is
130
+ `@spfn/core:route-map`, which emits `src/generated/route-map.ts` from `src/server/router.ts`
131
+ so the RPC proxy can resolve routes without importing server code. Generators also run
132
+ automatically during `spfn dev` and `spfn build`.
128
133
 
129
- 🗄️ Setting up database for @spfn/cms...
130
- ✓ Migrations applied
134
+ | Subcommand | Description |
135
+ |------------|-------------|
136
+ | `codegen init` | Create `.spfnrc.ts` (`--with-example` shows custom-generator usage) |
137
+ | `codegen list` (`ls`) | List configured generators and their watch patterns |
138
+ | `codegen run` | Run all generators once (no watch) |
131
139
 
132
- @spfn/cms installed successfully!
140
+ `package.json` exposes this as the `codegen` script (`spfn codegen run`).
133
141
 
134
- 📚 Setup Guide:
135
- 1. Import CMS components: import { useLabels } from '@spfn/cms'
136
- 2. View labels in Drizzle Studio: pnpm spfn db studio
137
- 3. Learn more: https://github.com/spfnio/spfn
142
+ To add a custom generator, implement the `Generator` interface from `@spfn/core/codegen`
143
+ and reference it in `.spfnrc.ts`:
144
+
145
+ ```ts
146
+ // .spfnrc.ts
147
+ import { defineConfig, defineGenerator } from '@spfn/core/codegen';
148
+
149
+ export default defineConfig({
150
+ generators: [
151
+ defineGenerator({
152
+ name: '@spfn/core:route-map',
153
+ routerPath: './src/server/router.ts',
154
+ outputPath: './src/generated/route-map.ts',
155
+ }),
156
+ ],
157
+ });
138
158
  ```
139
159
 
140
- **How it works:**
141
- - SPFN automatically discovers schemas from packages via `package.json`:
142
- ```json
143
- {
144
- "name": "@spfn/cms",
145
- "spfn": {
146
- "schemas": ["./dist/server/entities/*.js"],
147
- "migrations": { "dir": "./migrations" },
148
- "setupMessage": "📚 Next steps: ..."
149
- }
150
- }
151
- ```
152
- - Packages include pre-built migrations in their `migrations/` directory
153
- - Package migrations are applied first, then project migrations
154
- - Works with both published npm packages and local development (workspace packages)
155
-
156
- ### Development & Production
160
+ ### `spfn db`
161
+
162
+ Wraps Drizzle Kit with auto-generated config. Most commands read `DATABASE_URL` from the
163
+ loaded `.env` chain.
164
+
165
+ | Subcommand | Description |
166
+ |------------|-------------|
167
+ | `db generate` (`g`) | Generate migrations from schema changes (timestamp-prefixed) |
168
+ | `db push` | Apply schema to DB. Safe by default; destructive changes need confirmation. `--force` applies destructive changes, `--dry-run` previews |
169
+ | `db migrate` (`m`) | Run pending migrations. `--with-backup` snapshots first |
170
+ | `db studio` | Open Drizzle Studio. `-p, --port` (auto-finds a free port) |
171
+ | `db check` | Verify the database connection |
172
+ | `db drop` | Drop all tables **destructive**, double-prompts (see [Pitfalls](#pitfalls)) |
173
+ | `db backup` | Create a backup (`-f sql|custom`, `-o`, `-s`, `--data-only`, `--schema-only`, `--tag`, `--env`) |
174
+ | `db restore [file]` | Restore from a backup (`--drop`, `-s`, `--data-only`, `--schema-only`, `-v`) |
175
+ | `db backup:list` | List backups |
176
+ | `db backup:clean` | Prune backups (`-k, --keep <n>`, `-o, --older-than <days>`) |
177
+ | `db reindex` | Convert sequential migration prefixes to timestamps (`--dry-run`) |
178
+
179
+ > `db push` is for development. For production, use `db generate` + `db migrate` to keep
180
+ > migration history.
181
+
182
+ ### `spfn env`
183
+
184
+ Schema-driven environment variable tooling (schema comes from a package's `envSchema`,
185
+ default `@spfn/core`). Routes vars to the right file: `NEXT_PUBLIC_*` → `.env`/`.env.local`,
186
+ server vars → `.env.server`.
187
+
188
+ | Subcommand | Description |
189
+ |------------|-------------|
190
+ | `env list` | List vars from the schema (`-g` groups by target file) |
191
+ | `env stats` | Show variable statistics |
192
+ | `env search <query>` | Search vars by key or description |
193
+ | `env init` | Generate `.env` template files (`-e <env>` for per-env, `-f` to overwrite) |
194
+ | `env check` | Check `.env` files against the schema (`-e <env>` for a full env chain) |
195
+ | `env validate` | Validate `process.env` against the schema — for CI/CD (`-e <env>`, `-s` strict) |
196
+
197
+ All accept `-p, --package <pkg>` (`env validate` uses `-p, --packages <pkgs...>`).
198
+
199
+ ### `spfn key [preset]`
200
+
201
+ Generate cryptographically random secrets (base64url, 256-bit default).
202
+
157
203
  ```bash
158
- # Development
159
- spfn dev # Start both Next.js (3790) + API server (8790)
160
- spfn dev --server-only # Start API server only (8790)
161
- spfn dev --no-watch # Disable hot reload
162
-
163
- # Production
164
- spfn build # Build Next.js + compile server
165
- spfn start # Start production server
166
- spfn start --server-only # Start API server only (no Next.js)
204
+ spfn key # generic 256-bit secret
205
+ spfn key auth-encryption -c # preset key, copy to clipboard
206
+ spfn key --list # list presets
207
+ spfn key gen -b 64 # raw value only, no metadata (alias of `key generate`)
167
208
  ```
168
209
 
169
- ### Database Management
170
- ```bash
171
- spfn db generate # Generate database migrations
172
- spfn db push # Push schema to database (no migrations)
173
- spfn db migrate # Run pending migrations
174
- spfn db studio # Open Drizzle Studio (database GUI)
175
- spfn db check # Check database connection
176
- spfn db drop # Drop all tables (⚠️ dangerous!)
210
+ Presets: `auth-encryption`, `nextauth-secret`, `jwt-secret`, `session-secret`, `api-key`.
211
+ Options: `-l, --list`, `-b, --bytes <n>` (1–128), `-e, --env <name>`, `-c, --copy`.
212
+ The command prints the value to stdout for you to paste into an env file — it does **not**
213
+ write any file.
214
+
215
+ ### `spfn setup icons`
216
+
217
+ Install and configure SVGR for SVG-as-component imports (Next.js only).
218
+
219
+ ---
220
+
221
+ ## Scaffold structure
222
+
223
+ `spfn init` (and `create`, which calls it) produces:
224
+
225
+ ```
226
+ src/
227
+ app/api/rpc/[routeName]/route.ts # RPC proxy — re-exports { GET, POST } from @spfn/core/nextjs/server
228
+ generated/route-map.ts # generated by codegen (run `spfn codegen run` if missing)
229
+ lib/
230
+ api-client.ts # createApi<AppRouter>() — the type-safe client
231
+ server/
232
+ router.ts # defineRouter({ ...routes }) → export type AppRouter
233
+ server.config.ts # defineServerConfig().port(8790).host('0.0.0.0').routes(appRouter)
234
+ config/env.config.ts # environment schema
235
+ entities/ # Drizzle tables (example.entity.ts, config.ts)
236
+ repositories/ # BaseRepository subclasses (example.repository.ts)
237
+ routes/ # route DSL handlers: root.ts, health.ts, examples.ts
238
+ tsconfig.json, tsup.config.ts
239
+ .spfnrc.ts # codegen config (route-map generator)
240
+ spfn.config.js # deployment config (subdomain/region/domains) — committed
241
+ docker-compose.yml # Postgres + Redis (dev)
242
+ docker-compose.production.yml
243
+ Dockerfile, .dockerignore
244
+ .env.example # committed, shared non-secret defaults
245
+ .env.local.example # gitignored target template (Next.js local overrides)
246
+ .env.server.example # → copy to .env.server (gitignored, server secrets)
177
247
  ```
178
248
 
179
- ### Setup Features
180
- ```bash
181
- spfn setup icons # Setup SVGR for SVG icon management
249
+ `init` also patches `package.json` (scripts: `spfn:dev`, `spfn:server`, `spfn:next`,
250
+ `spfn:build`, `spfn:start`, `codegen`; deps: `@spfn/core`, `spfn`, `drizzle-orm`,
251
+ `@sinclair/typebox`, `concurrently`, etc.), excludes `src/server` from the root
252
+ `tsconfig.json` (Vercel compat), and adds `.spfn/`, `.env.local`, `.env.server` to
253
+ `.gitignore`.
254
+
255
+ ### Route DSL (the current architecture)
256
+
257
+ Routes are defined with the `route` builder and collected by `defineRouter`. There is no
258
+ separate "contract" layer — the router's type *is* the contract; the client infers from it.
259
+
260
+ ```ts
261
+ // src/server/routes/examples.ts
262
+ import { route } from '@spfn/core/route';
263
+ import { Type } from '@sinclair/typebox';
264
+
265
+ export const getExample = route.get('/examples/:id')
266
+ .input({ params: Type.Object({ id: Type.String() }) })
267
+ .handler(async (c) =>
268
+ {
269
+ const { params } = await c.data();
270
+ return { id: params.id };
271
+ });
182
272
  ```
183
273
 
184
- ### Utilities
185
- ```bash
186
- spfn key # Generate encryption key for .env
274
+ ```ts
275
+ // src/server/router.ts
276
+ import { defineRouter } from '@spfn/core/route';
277
+ import { getExample } from './routes/examples';
278
+
279
+ export const appRouter = defineRouter({ getExample });
280
+ export type AppRouter = typeof appRouter;
187
281
  ```
188
282
 
189
- ## Configuration
190
-
191
- ### spfn.config.js
192
-
193
- SPFN uses `spfn.config.js` for deployment configuration with full JSDoc type support for IDE autocomplete.
194
-
195
- **Basic Configuration:**
196
- ```javascript
197
- /**
198
- * @type {import('spfn').SpfnConfig}
199
- */
200
- export default {
201
- packageManager: 'pnpm',
202
- deployment: {
203
- // Your app's subdomain on spfn.app
204
- // Creates region-specific domains:
205
- // - myapp.us.spfn.app (Next.js)
206
- // - api-myapp.us.spfn.app (API)
207
- subdomain: 'myapp',
208
-
209
- // Optional: Deployment region (defaults to 'us')
210
- // Available: 'us' (Virginia, default), 'kr' (Seoul), 'jp', 'sg', 'eu' (coming soon)
211
- region: 'us',
212
-
213
- // Optional: Add custom domains
214
- customDomains: {
215
- nextjs: ['www.example.com', 'example.com'],
216
- spfn: ['api.example.com']
217
- },
218
-
219
- // Optional: Environment variables for both Next.js and SPFN backend
220
- // ⚠️ WARNING: These values are committed to Git
221
- // Do NOT put sensitive credentials here!
222
- env: {
223
- NEXT_PUBLIC_API_URL: 'https://api-myapp.us.spfn.app',
224
- NODE_ENV: 'production'
225
- }
226
- }
227
- }
283
+ ```ts
284
+ // src/lib/api-client.ts
285
+ import { createApi } from '@spfn/core/nextjs';
286
+ import type { AppRouter } from '@/server/router';
287
+
288
+ export const api = createApi<AppRouter>();
289
+ const example = await api.getExample.call({ params: { id: '123' } });
228
290
  ```
229
291
 
230
- **Features:**
231
- - **JSDoc Type Hints** - IDE autocomplete via `@type {import('spfn').SpfnConfig}`
232
- - **Multi-Region Deployment** - Deploy to Seoul (kr), Virginia (us), and more
233
- - **Dual Domain Setup** - Automatic `{subdomain}.{region}.spfn.app` and `api-{subdomain}.{region}.spfn.app`
234
- - **Custom Domains** - Support for multiple custom domains
235
- - **Environment Variables** - Shared between Next.js and SPFN backend
236
- - **ESM/CJS Support** - Works with both module systems
292
+ Client calls go through the Next.js RPC proxy (`/api/rpc/[routeName]`), which forwards to
293
+ the SPFN API with cookie forwarding and interceptors, resolving routes via the generated
294
+ `route-map.ts`.
295
+
296
+ ---
237
297
 
238
- **Security Note:**
239
- - `spfn.config.js` is committed to Git
240
- - Only use for non-sensitive configuration
241
- - For secrets (DB passwords, API keys), use CI/CD secrets management
298
+ ## Deployment
242
299
 
243
- ## Documentation
300
+ `spfn build` then `spfn start`, or use the generated Docker files.
244
301
 
245
- For complete documentation and guides, see:
246
- - **[SPFN Framework](../../README.md)** - Getting started
247
- - **[@spfn/core](../core/README.md)** - API reference and core concepts
302
+ ```bash
303
+ # Build + run locally
304
+ pnpm spfn:build
305
+ pnpm spfn:start # Next.js :3790 + SPFN API :8790
248
306
 
249
- ## Requirements
307
+ # Docker (single image runs both)
308
+ docker compose -f docker-compose.production.yml up --build -d
309
+ ```
250
310
 
251
- - Node.js 18+
252
- - Next.js 15+ (App Router)
253
- - PostgreSQL (optional: Redis)
311
+ The Dockerfile (`node:22-alpine`) installs with `pnpm --frozen-lockfile`, runs
312
+ `pnpm run spfn:build`, prunes dev deps, exposes `3790`/`8790`, health-checks
313
+ `http://localhost:8790/health`, and starts via `pnpm run spfn:start`.
254
314
 
255
- ## Links
315
+ Run migrations against the target DB before/with deploy:
316
+
317
+ ```bash
318
+ docker exec <container> npx spfn db migrate
319
+ ```
256
320
 
257
- - 🌐 Website: [superfunction.xyz](https://superfunction.xyz)
258
- - 📦 npm: [spfn](https://npmjs.com/package/spfn) (CLI)
259
- - 📦 npm: [@spfn/core](https://npmjs.com/package/@spfn/core) (Core)
260
- - 💬 GitHub: [spfn/spfn](https://github.com/spfn/spfn)
321
+ `spfn.config.js` (committed) configures the managed `*.spfn.app` deployment: `subdomain`,
322
+ `region` (`us` default, `kr`, …), `customDomains`, and non-secret `env`. Its `SpfnConfig`
323
+ type ships from `spfn` (`@type {import('spfn').SpfnConfig}`).
324
+
325
+ ---
326
+
327
+ ## Pitfalls
328
+
329
+ - **`.env.server` is gitignored and server-only.** Put DB/secret values there, not in
330
+ `.env` (committed) and not in `.env.local` (that's Next.js's local file). There is no
331
+ `.env.server.local`. Copy `.env.server.example` → `.env.server`. Load order is the
332
+ standard dotenv chain ending with `.env.server`.
333
+ - **Never commit secrets in `spfn.config.js`.** It's checked into Git; its `env` block is
334
+ for non-sensitive values only. Use CI/CD secret management for credentials.
335
+ - **`spfn dev` does not hot-reload by default.** Add `--watch` to restart on `src/server`
336
+ changes.
337
+ - **`spfn start` needs a prior `spfn build`.** It hard-fails without `.spfn/server`,
338
+ `.spfn/prod-server.mjs`, and `.next`.
339
+ - **Destructive DB commands are guarded.** `db drop` double-confirms (and verifies the
340
+ target); `db push` applies additive changes but withholds destructive ones unless
341
+ `--force`/confirmed. Prefer `db generate` + `db migrate` for production; `db push` is dev-only.
342
+ - **`spfn add` requires a scoped package name** (must contain `/`) and only applies
343
+ migrations when `DATABASE_URL` is set — otherwise it skips with a hint.
344
+ - **Package manager is auto-detected from lockfiles.** If detection is wrong (e.g. mixed
345
+ lockfiles), pass `--pm` to `create`. In a pnpm workspace, `create` installs from the
346
+ workspace root, not the new project dir.
347
+ - **Regenerate the route map after route changes outside dev.** If
348
+ `src/generated/route-map.ts` is missing or stale, run `spfn codegen run` — the RPC proxy
349
+ depends on it.
350
+
351
+ ---
352
+
353
+ ## Related
354
+
355
+ - `@spfn/core` — server, route DSL, codegen, db, client runtime.
356
+ - Project root README — framework overview and getting started.
357
+ </content>
358
+ </invoke>
package/bin/spfn.js CHANGED
@@ -1,10 +1,52 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import('../dist/index.js').then(({ run }) =>
3
+ /**
4
+ * SPFN CLI Entry Point
5
+ *
6
+ * Re-spawns with --import tsx when .ts schema loading is needed.
7
+ * This avoids ERR_REQUIRE_CYCLE_MODULE on Node.js 22+ where
8
+ * tsx.register() causes CJS/ESM interop cycles.
9
+ */
10
+
11
+ const TSX_FLAG = '--import';
12
+ const TSX_MODULE = 'tsx';
13
+
14
+ // Already running with tsx loader — just run
15
+ if (process.execArgv.some(arg => arg.includes(TSX_MODULE)))
16
+ {
17
+ import('../dist/index.js').then(({ run }) => run()).catch(abort);
18
+ }
19
+ else
20
+ {
21
+ // Try to re-spawn with --import tsx for .ts schema support
22
+ tryRelaunchWithTsx().catch(() =>
23
+ {
24
+ // tsx not available — run without it
25
+ import('../dist/index.js').then(({ run }) => run()).catch(abort);
26
+ });
27
+ }
28
+
29
+ async function tryRelaunchWithTsx()
4
30
  {
5
- run();
6
- }).catch((error) =>
31
+ // Verify tsx is resolvable
32
+ await import('tsx/esm/api');
33
+
34
+ const { spawn } = await import('child_process');
35
+ const child = spawn(
36
+ process.execPath,
37
+ [TSX_FLAG, TSX_MODULE, ...process.execArgv, process.argv[1], ...process.argv.slice(2)],
38
+ { stdio: 'inherit' },
39
+ );
40
+
41
+ child.on('close', (code) => process.exit(code ?? 0));
42
+ child.on('error', () =>
43
+ {
44
+ import('../dist/index.js').then(({ run }) => run()).catch(abort);
45
+ });
46
+ }
47
+
48
+ function abort(error)
7
49
  {
8
50
  console.error('Error:', error);
9
51
  process.exit(1);
10
- });
52
+ }