express-file-cluster 0.3.14 → 0.5.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.
Files changed (116) hide show
  1. package/README.md +204 -52
  2. package/dist/auth/index.cjs +12 -2
  3. package/dist/auth/index.cjs.map +1 -1
  4. package/dist/auth/index.d.cts +13 -2
  5. package/dist/auth/index.d.ts +13 -2
  6. package/dist/auth/index.js +12 -2
  7. package/dist/chunk-3VWD2ZED.js +60 -0
  8. package/dist/chunk-3VWD2ZED.js.map +1 -0
  9. package/dist/chunk-47K2532L.cjs +196 -0
  10. package/dist/chunk-47K2532L.cjs.map +1 -0
  11. package/dist/chunk-5PDAWMGF.js +438 -0
  12. package/dist/chunk-5PDAWMGF.js.map +1 -0
  13. package/dist/chunk-7YEX4MQV.cjs +38 -0
  14. package/dist/chunk-7YEX4MQV.cjs.map +1 -0
  15. package/dist/chunk-ALBDM5R3.cjs +60 -0
  16. package/dist/chunk-ALBDM5R3.cjs.map +1 -0
  17. package/dist/chunk-JJJJTACK.js +196 -0
  18. package/dist/chunk-JJJJTACK.js.map +1 -0
  19. package/dist/chunk-LJNSJFOL.js +38 -0
  20. package/dist/chunk-LJNSJFOL.js.map +1 -0
  21. package/dist/chunk-M7MUPWCE.js +116 -0
  22. package/dist/chunk-M7MUPWCE.js.map +1 -0
  23. package/dist/chunk-PMF4GMHD.js +154 -0
  24. package/dist/chunk-PMF4GMHD.js.map +1 -0
  25. package/dist/chunk-QTRGJ2EN.cjs +2635 -0
  26. package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
  27. package/dist/chunk-RSBW2B3D.cjs +126 -0
  28. package/dist/chunk-RSBW2B3D.cjs.map +1 -0
  29. package/dist/chunk-RTFJ32T5.js +2635 -0
  30. package/dist/chunk-RTFJ32T5.js.map +1 -0
  31. package/dist/chunk-SFVEQ2T5.cjs +438 -0
  32. package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
  33. package/dist/chunk-SZT36SGB.cjs +154 -0
  34. package/dist/chunk-SZT36SGB.cjs.map +1 -0
  35. package/dist/chunk-TI24L4XE.cjs.map +1 -1
  36. package/dist/chunk-ULQXD4YZ.cjs +116 -0
  37. package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
  38. package/dist/chunk-VYHJX54R.js +126 -0
  39. package/dist/chunk-VYHJX54R.js.map +1 -0
  40. package/dist/cli/db-runner.cjs +497 -0
  41. package/dist/cli/db-runner.cjs.map +1 -0
  42. package/dist/cli/db-runner.d.cts +2 -0
  43. package/dist/cli/db-runner.d.ts +2 -0
  44. package/dist/cli/db-runner.js +497 -0
  45. package/dist/cli/db-runner.js.map +1 -0
  46. package/dist/cli/index.cjs +447 -69
  47. package/dist/cli/index.cjs.map +1 -1
  48. package/dist/cli/index.js +473 -95
  49. package/dist/cli/index.js.map +1 -1
  50. package/dist/docs/api-reference/auth.md +232 -0
  51. package/dist/docs/api-reference/compose.md +78 -0
  52. package/dist/docs/api-reference/db.md +351 -0
  53. package/dist/docs/api-reference/http-error.md +109 -0
  54. package/dist/docs/api-reference/ignite.md +323 -0
  55. package/dist/docs/api-reference/table.md +250 -0
  56. package/dist/docs/api-reference/tasks.md +140 -0
  57. package/dist/docs/cli/db.md +38 -0
  58. package/dist/docs/cli/diagnostics.md +145 -0
  59. package/dist/docs/cli/generate.md +120 -0
  60. package/dist/docs/cli/index.md +48 -0
  61. package/dist/docs/cli/start.md +112 -0
  62. package/dist/docs/contributing/index.md +139 -0
  63. package/dist/docs/core-concepts/background-tasks.md +228 -0
  64. package/dist/docs/core-concepts/clustering.md +114 -0
  65. package/dist/docs/core-concepts/file-based-routing.md +235 -0
  66. package/dist/docs/core-concepts/index.md +79 -0
  67. package/dist/docs/core-concepts/middleware.md +144 -0
  68. package/dist/docs/getting-started/index.md +91 -0
  69. package/dist/docs/getting-started/project-structure.md +154 -0
  70. package/dist/docs/guides/ai-agents.md +48 -0
  71. package/dist/docs/guides/authentication.md +196 -0
  72. package/dist/docs/guides/caching.md +124 -0
  73. package/dist/docs/guides/database.md +217 -0
  74. package/dist/docs/guides/deployment.md +171 -0
  75. package/dist/docs/guides/environment-variables.md +106 -0
  76. package/dist/docs/guides/error-handling.md +172 -0
  77. package/dist/docs/guides/generated-portals.md +115 -0
  78. package/dist/docs/guides/logging.md +70 -0
  79. package/dist/docs/guides/mailer.md +166 -0
  80. package/dist/docs/guides/migrations.md +106 -0
  81. package/dist/docs/guides/rbac.md +89 -0
  82. package/dist/docs/guides/validation.md +95 -0
  83. package/dist/docs/index.md +93 -0
  84. package/dist/docs/skills/SKILL.md +44 -0
  85. package/dist/docs/skills/api-surface.md +308 -0
  86. package/dist/docs/skills/auth-internals.md +141 -0
  87. package/dist/docs/skills/pre-flight.md +142 -0
  88. package/dist/docs/skills/routing-rules.md +114 -0
  89. package/dist/docs/skills/tasks-internals.md +172 -0
  90. package/dist/docs/skills/what-not-to-invent.md +251 -0
  91. package/dist/index.cjs +289 -391
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +472 -7
  94. package/dist/index.d.ts +472 -7
  95. package/dist/index.js +283 -385
  96. package/dist/index.js.map +1 -1
  97. package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
  98. package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
  99. package/dist/pgboss-backend-UUJOVEYK.js +14 -0
  100. package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
  101. package/dist/tasks/index.cjs.map +1 -1
  102. package/dist/tasks/index.d.cts +1 -1
  103. package/dist/tasks/index.d.ts +1 -1
  104. package/dist/types-DJCPAsM4.d.cts +541 -0
  105. package/dist/types-DJCPAsM4.d.ts +541 -0
  106. package/package.json +28 -5
  107. package/dist/chunk-6522HS2J.cjs +0 -99
  108. package/dist/chunk-6522HS2J.cjs.map +0 -1
  109. package/dist/chunk-DGVOJNR6.cjs +0 -55
  110. package/dist/chunk-DGVOJNR6.cjs.map +0 -1
  111. package/dist/chunk-KOHLLUN7.js +0 -55
  112. package/dist/chunk-KOHLLUN7.js.map +0 -1
  113. package/dist/chunk-VIP3PFWZ.js +0 -99
  114. package/dist/chunk-VIP3PFWZ.js.map +0 -1
  115. package/dist/types-BusbSenn.d.cts +0 -162
  116. package/dist/types-BusbSenn.d.ts +0 -162
@@ -0,0 +1,235 @@
1
+ # File-Based Routing
2
+
3
+ EFC turns your directory tree into your route tree. The scanner walks `src/api/` recursively (a fixed convention, not a configurable option), converts each file path to a URL, and mounts the handlers on Express — no explicit registration required.
4
+
5
+ ---
6
+
7
+ ## Naming rules
8
+
9
+ | Rule | Example file | Resolved URL |
10
+ |---|---|---|
11
+ | Plain file | `api/health.ts` | `/health` |
12
+ | `index.ts` in a directory | `api/users/index.ts` | `/users` |
13
+ | Nested directory | `api/posts/recent.ts` | `/posts/recent` |
14
+ | Dynamic segment | `api/users/[id].ts` | `/users/:id` |
15
+ | Dynamic directory | `api/posts/[slug]/comments.ts` | `/posts/:slug/comments` |
16
+ | Optional segment | `api/users/[[id]].ts` | `/users` **and** `/users/:id` |
17
+ | Catch-all | `api/docs/[...slug].ts` | `/docs/a`, `/docs/a/b/c`, … (not `/docs`) |
18
+ | Optional catch-all | `api/docs/[[...slug]].ts` | `/docs`, `/docs/a`, `/docs/a/b/c`, … |
19
+
20
+ **`[bracket]` → `:param`** — any path segment wrapped in square brackets becomes an Express route parameter accessible as `req.params.<name>`.
21
+
22
+ **`[[double]]` → optional** — `req.params.id` is `undefined` when the segment is absent.
23
+
24
+ **`[...spread]` → catch-all** — matches one or more remaining segments; `req.params.slug` is a **string array** (`/docs/a/b` → `['a', 'b']`, each segment URI-decoded). With double brackets it also matches zero segments (`[]`). A catch-all must be the last segment of the path — `[...slug]/edit.ts` is rejected at startup.
25
+
26
+ **`index.ts` → parent path** — a file named `index.ts` (or `.js`) inside a directory maps to the directory's URL without a trailing `/index`.
27
+
28
+ ---
29
+
30
+ ## Supported file extensions
31
+
32
+ The scanner recognises `.ts`, `.js`, `.mts`, `.mjs`, `.cts`, and `.cjs`.
33
+
34
+ ---
35
+
36
+ ## Route priority
37
+
38
+ Routes register most-specific first, compared segment by segment: at each position a **static** segment beats `[id]`, which beats `[[id]]`, then `[...slug]`, then `[[...slug]]`. Given:
39
+
40
+ ```
41
+ api/docs/intro.ts → /docs/intro (static)
42
+ api/docs/[id].ts → /docs/:id (dynamic)
43
+ api/docs/[[...slug]].ts → /docs/:slug*? (optional catch-all)
44
+ ```
45
+
46
+ `/docs/intro` hits the static route, `/docs/42` the dynamic one, and `/docs` or `/docs/a/b` fall through to the catch-all. Ties are ordered alphabetically. `efc routes` prints the resolved order.
47
+
48
+ ---
49
+
50
+ ## Exporting handlers
51
+
52
+ Each route file exports one or more uppercase HTTP method names as async functions:
53
+
54
+ ```ts
55
+ // src/api/users/index.ts
56
+ import type { Request, Response } from 'express';
57
+
58
+ export const GET = async (req: Request, res: Response) => {
59
+ res.json({ users: [] });
60
+ };
61
+
62
+ export const POST = async (req: Request, res: Response) => {
63
+ res.status(201).json({ id: 'new-id' });
64
+ };
65
+ ```
66
+
67
+ Supported method names: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`.
68
+
69
+ Any method not exported on a route that does export at least one method returns **405 Method Not Allowed** with an `Allow` header listing the implemented methods:
70
+
71
+ ```
72
+ HTTP/1.1 405 Method Not Allowed
73
+ Allow: GET, POST
74
+ Content-Type: application/json
75
+
76
+ { "error": "Method Not Allowed" }
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Dynamic parameters
82
+
83
+ ```ts
84
+ // src/api/users/[id].ts
85
+ import type { Request, Response } from 'express';
86
+ import { HttpError } from 'express-file-cluster';
87
+ import { User } from '../../model/User.js';
88
+
89
+ export const GET = async (req: Request, res: Response) => {
90
+ const user = await User.findById(req.params.id);
91
+ if (!user) throw new HttpError(404, 'User not found');
92
+ res.json(user);
93
+ };
94
+
95
+ export const DELETE = async (req: Request, res: Response) => {
96
+ await User.delete(req.params.id);
97
+ res.status(204).send();
98
+ };
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Route metadata (`meta` export)
104
+
105
+ A route file can export a `meta` object to provide documentation shown in the [dashboard](../api-reference/ignite.md#dashboard). `meta` is keyed by HTTP method — each method implemented in the file gets its own description and request/response example, rendered as a separate documentation block. All fields are optional.
106
+
107
+ ```ts
108
+ // src/api/users/[id].ts
109
+ export const meta = {
110
+ GET: {
111
+ description: 'Fetch a user by ID.',
112
+ request: {
113
+ headers: { Authorization: 'Bearer <token>' },
114
+ params: { id: 'usr_01HXZ' },
115
+ query: { include: 'profile' },
116
+ },
117
+ response: {
118
+ status: 200,
119
+ body: {
120
+ id: 'usr_01HXZ',
121
+ name: 'Ada Lovelace',
122
+ createdAt: '2026-01-01T00:00:00.000Z',
123
+ },
124
+ },
125
+ },
126
+ DELETE: {
127
+ description: 'Delete a user by ID.',
128
+ request: {
129
+ headers: { Authorization: 'Bearer <token>' },
130
+ params: { id: 'usr_01HXZ' },
131
+ },
132
+ response: { status: 204 },
133
+ },
134
+ };
135
+ ```
136
+
137
+ **`RouteMeta` / `RouteMethodMeta` interfaces:**
138
+
139
+ ```ts
140
+ type RouteMeta = Partial<Record<string, RouteMethodMeta>>;
141
+
142
+ interface RouteMethodMeta {
143
+ description?: string;
144
+ request?: {
145
+ headers?: Record<string, string>;
146
+ params?: Record<string, string>;
147
+ query?: Record<string, string>;
148
+ body?: unknown;
149
+ };
150
+ response?: {
151
+ status?: number;
152
+ body?: unknown;
153
+ };
154
+ }
155
+ ```
156
+
157
+ Only add an entry for methods you want documented — a method with no key in `meta` simply shows an undocumented block in the dashboard.
158
+
159
+ The dashboard renders `response.body` values as their **type names** (`String`, `Number`, `Boolean`, `Date`) rather than the literal values you provide. ISO 8601 date strings (e.g., `'2026-01-01T00:00:00.000Z'`) are automatically detected and shown as `Date`.
160
+
161
+ ---
162
+
163
+ ## Request validation (`schema` export)
164
+
165
+ Export `schema` to validate `params`, `query` and `body` before your handler runs. Any [Standard Schema](https://standardschema.dev) validator works — zod (3.24+), valibot, arktype — or anything with a zod-style `safeParse`. EFC never imports a validation library itself.
166
+
167
+ ```ts
168
+ // src/api/users/index.ts
169
+ import { z } from 'zod';
170
+
171
+ export const schema = {
172
+ POST: { body: z.object({ email: z.string().email(), age: z.coerce.number().min(18) }) },
173
+ GET: { query: z.object({ page: z.coerce.number().default(1) }) },
174
+ };
175
+
176
+ export const POST = async (req, res) => {
177
+ // req.body is the parsed output: coerced types, defaults applied
178
+ res.status(201).json(req.body);
179
+ };
180
+ ```
181
+
182
+ Key it by method as above, or pass `{ params, query, body }` directly to apply it to every method in the file. Validation runs **after** the file's `middlewares` (so `requireAuth` still answers 401 first). Failures return:
183
+
184
+ ```json
185
+ {
186
+ "error": "Validation failed",
187
+ "statusCode": 400,
188
+ "issues": [{ "location": "body", "path": "email", "message": "Invalid email address" }]
189
+ }
190
+ ```
191
+
192
+ See the [Validation guide](../guides/validation.md).
193
+
194
+ ---
195
+
196
+ ## Route-level middleware
197
+
198
+ Export a `middlewares` array from a route file. The middlewares apply to every handler in that file and run after global middleware.
199
+
200
+ ```ts
201
+ // src/api/admin/settings.ts
202
+ import { requireAuth } from 'express-file-cluster/auth';
203
+
204
+ export const middlewares = [requireAuth];
205
+
206
+ export const GET = async (req, res) => {
207
+ // Only reached if requireAuth passes
208
+ res.json({ settings: {} });
209
+ };
210
+ ```
211
+
212
+ ---
213
+
214
+ ## How the scanner works internally
215
+
216
+ `scanDir(dir)` in `packages/core/src/router/scan.ts`, called with the resolved `src/api/` path:
217
+
218
+ 1. Walks the directory recursively with `fs.readdirSync`.
219
+ 2. For each file, converts the path relative to `src/api/` to a URL:
220
+ - Strips the extension.
221
+ - Replaces `/index` with `''` (parent path).
222
+ - Replaces `[param]` with `:param`, `[[param]]` with `:param?`, `[...param]` with `:param*` and `[[...param]]` with `:param*?`.
223
+ - Prepends `/` if missing.
224
+ 3. Sorts results by per-segment specificity (see Route priority).
225
+ 4. Returns a `RouteEntry[]` array with `urlPath`, `filePath`, `params`, and — for catch-all routes, which Express 4's string paths can't express — a compiled `pattern` RegExp.
226
+
227
+ `mountRoutes(app, routes)` in `packages/core/src/router/mount.ts`:
228
+
229
+ 1. Iterates `RouteEntry[]`.
230
+ 2. Dynamically `import()`s each route module.
231
+ 3. Reads the optional `middlewares`, `schema` and `meta` exports.
232
+ 4. For each known HTTP method that is exported as a function, registers it with `app.<method>(urlPath, ...middlewares, validate?, asyncWrap(handler))`. Catch-all routes mount on their `pattern` behind a small mapper that turns positional captures back into named params.
233
+ 5. Registers an `app.all()` catch for unimplemented methods that returns 405.
234
+
235
+ `asyncWrap` wraps every handler in `Promise.resolve(...).catch(next)` so that thrown errors and rejected promises are forwarded to the Express error handler automatically.
@@ -0,0 +1,79 @@
1
+ # Core Concepts
2
+
3
+ EFC is built around four interlocking ideas. Understanding each one independently makes the whole system easy to reason about.
4
+
5
+ ---
6
+
7
+ ## 1. File-Based Routing
8
+
9
+ The directory tree under `src/api/` **is** the route tree. No `router.get(...)` registration, no explicit path strings — the file path is the URL path.
10
+
11
+ ```
12
+ src/api/users/[id].ts → GET /users/:id
13
+ ```
14
+
15
+ Each route file exports uppercase HTTP method names as async functions. Methods not exported return **405 Method Not Allowed** automatically.
16
+
17
+ → [File-Based Routing](./file-based-routing.md)
18
+
19
+ ---
20
+
21
+ ## 2. Multi-Core Clustering
22
+
23
+ With `cluster: true`, EFC forks `os.cpus().length` identical worker processes. Each worker runs the full **Pre-Flight lifecycle** independently (connect DB → configure auth → scan routes → register tasks → listen).
24
+
25
+ The OS round-robins incoming connections across workers. If a worker crashes, the master immediately forks a replacement.
26
+
27
+ → [Clustering](./clustering.md)
28
+
29
+ ---
30
+
31
+ ## 3. Background Tasks
32
+
33
+ The `src/tasks/` directory holds background jobs — work that should happen *off* the request/response cycle. Define a task with `defineTask()`, trigger it from any route handler with `enqueue()`, and the queue backend — **BullMQ** (Redis) or **pg-boss** (PostgreSQL) — handles retries, backoff, cron schedules, dead letters and concurrency.
34
+
35
+ CPU-bound tasks can opt into `worker_threads` execution with `{ thread: true }`, keeping the event loop free.
36
+
37
+ → [Background Tasks](./background-tasks.md)
38
+
39
+ ---
40
+
41
+ ## 4. Middleware System
42
+
43
+ EFC supports three tiers of middleware with clear, non-overlapping scopes:
44
+
45
+ - **Global** — configured in `ignite()`, applied to every request.
46
+ - **Route-level** — `export const middlewares = [...]` in a route file, applied only to handlers in that file.
47
+ - **Handler-level** — `compose(mw1, mw2, handler)`, applied to a single handler.
48
+
49
+ → [Middleware](./middleware.md)
50
+
51
+ ---
52
+
53
+ ## How the pieces fit together
54
+
55
+ ```
56
+ HTTP Request
57
+ │
58
+ ▼
59
+ Global Middleware (ignite({ globalMiddlewares }))
60
+ │
61
+ ▼
62
+ Route-Level Middleware (export const middlewares = [...])
63
+ │
64
+ ▼
65
+ Handler-Level Middleware (compose(...))
66
+ │
67
+ ▼
68
+ Route Handler (export const GET = ...)
69
+ │
70
+ ├── sync response → res.json(...)
71
+ │
72
+ └── heavy work → enqueue('TaskName', payload)
73
+ │
74
+ ▼
75
+ Queue Backend (BullMQ / pg-boss)
76
+ │
77
+ ├── I/O-bound → event loop
78
+ └── CPU-bound → worker_threads
79
+ ```
@@ -0,0 +1,144 @@
1
+ # Middleware
2
+
3
+ EFC supports three tiers of middleware. Each tier has a distinct scope — pick the right tier and you never apply middleware more broadly than you intend.
4
+
5
+ ---
6
+
7
+ ## Tier 1 — Global middleware
8
+
9
+ Configured in `ignite()`. Applied to **every** incoming request, before any route is matched.
10
+
11
+ ```ts
12
+ import rateLimit from 'express-rate-limit';
13
+
14
+ ignite({
15
+ globalMiddlewares: [
16
+ rateLimit({ windowMs: 60_000, max: 100 }),
17
+ ],
18
+ });
19
+ ```
20
+
21
+ > **CORS is built-in.** EFC applies its own CORS middleware based on the `cors` option in `ignite()` (see [`ignite()` reference](../api-reference/ignite.md#cors)). You do not need to pass a `cors()` call here — doing so would create a duplicate header.
22
+
23
+ ---
24
+
25
+ ## Tier 2 — Route-level middleware
26
+
27
+ Export a `middlewares` array from a route file. Applied to every handler exported from that file, after global middleware.
28
+
29
+ ```ts
30
+ // src/api/admin/users.ts
31
+ import { requireAuth } from 'express-file-cluster/auth';
32
+ import { authorize } from '../../middlewares/authorize';
33
+
34
+ export const middlewares = [requireAuth, authorize('admin')];
35
+
36
+ export const GET = async (req, res) => {
37
+ // Only reachable after requireAuth + authorize('admin') pass
38
+ res.json({ users: [] });
39
+ };
40
+
41
+ export const DELETE = async (req, res) => {
42
+ // Same guard applies here automatically
43
+ res.status(204).send();
44
+ };
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Tier 3 — Handler-level middleware (`compose`)
50
+
51
+ `compose(...handlers)` wraps a single handler with one or more middleware functions. Use it for guards that apply to exactly one method in a file.
52
+
53
+ ```ts
54
+ // src/api/users/index.ts
55
+ import { compose } from 'express-file-cluster';
56
+ import { validateBody } from '../../middlewares/validation';
57
+ import { CreateUserSchema } from '../../schemas/user';
58
+
59
+ export const GET = async (req, res) => {
60
+ res.json({ users: [] });
61
+ };
62
+
63
+ // Only POST gets body validation
64
+ export const POST = compose(
65
+ validateBody(CreateUserSchema),
66
+ async (req, res) => {
67
+ // req.body is guaranteed valid here
68
+ res.status(201).json({ id: 'new-id' });
69
+ },
70
+ );
71
+ ```
72
+
73
+ ---
74
+
75
+ ## How `compose` works
76
+
77
+ `compose(...handlers)` in `packages/core/src/compose.ts` returns a single `RequestHandler` that chains the provided handlers in sequence. Each handler calls `next()` to advance to the next one. If any handler throws or rejects, the error is forwarded to Express's error chain via `next(err)`.
78
+
79
+ ```ts
80
+ export function compose(...handlers: RequestHandler[]): RequestHandler {
81
+ return (req, res, next) => {
82
+ let index = 0;
83
+
84
+ function dispatch(i: number): void {
85
+ if (i >= handlers.length) { next(); return; }
86
+ const handler = handlers[i];
87
+ try {
88
+ Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);
89
+ } catch (err) {
90
+ next(err);
91
+ }
92
+ }
93
+
94
+ dispatch(index);
95
+ };
96
+ }
97
+ ```
98
+
99
+ ---
100
+
101
+ ## Middleware execution order
102
+
103
+ For a request that hits `POST /users` on a file that has both `export const middlewares` and a `compose` handler:
104
+
105
+ ```
106
+ global middlewares (ignite)
107
+ ↓
108
+ route-level middlewares (export const middlewares = [...])
109
+ ↓
110
+ handler-level middlewares (compose(mw1, mw2, handler))
111
+ ↓
112
+ the actual handler function
113
+ ```
114
+
115
+ ---
116
+
117
+ ## Writing a middleware
118
+
119
+ EFC middleware is a plain Express `RequestHandler`:
120
+
121
+ ```ts
122
+ // src/middlewares/authorize.ts
123
+ import type { Request, Response, NextFunction } from 'express';
124
+
125
+ export function authorize(role: string) {
126
+ return (req: Request, res: Response, next: NextFunction): void => {
127
+ const user = (req as any).user;
128
+ if (user?.role !== role) {
129
+ res.status(403).json({ error: 'Forbidden' });
130
+ return;
131
+ }
132
+ next();
133
+ };
134
+ }
135
+ ```
136
+
137
+ Scaffold a middleware file with the CLI:
138
+
139
+ ```bash
140
+ efc generate middleware authorize
141
+ # → src/middlewares/authorize.ts
142
+ ```
143
+
144
+ > Route-level role protection doesn't need a custom middleware like `authorize` above — `requireAuth` itself accepts role names: `requireAuth('admin')`. `create-efc-app`'s **RBAC** feature option scaffolds routes that use this shorthand (plus a `Role` model) instead of an inline guard. See [RBAC](../guides/rbac.md).
@@ -0,0 +1,91 @@
1
+ # Getting Started
2
+
3
+ ## Prerequisites
4
+
5
+ - Node.js 18 or later
6
+ - npm 9 or later
7
+ - (Optional) MongoDB or Redis if you need a database or background tasks
8
+
9
+ ---
10
+
11
+ ## Scaffold a new project
12
+
13
+ ```bash
14
+ npx create-efc-app my-api
15
+ ```
16
+
17
+ The interactive wizard walks through:
18
+
19
+ ```
20
+ ? Project name: my-api
21
+ ? Language: TypeScript | JavaScript
22
+ ? Database: MongoDB | PostgreSQL
23
+ ? Authentication strategy: http-only | localStorage
24
+ ? Features: (space to toggle)
25
+ ◉ Multi-core clustering
26
+ ◉ Background tasks
27
+ ◉ API route documentation
28
+ ◉ User portal
29
+ ◉ Admin portal
30
+ ◉ Role-based access control
31
+ ◯ Mailer
32
+ ```
33
+
34
+ Generated models and routes are identical for both databases — `defineModel` compiles to mongoose or Drizzle at runtime. See [Database](../guides/database.md).
35
+
36
+ Depending on what you toggle on, you'll see follow-up questions:
37
+
38
+ - **Background tasks** → pick a queue backend: `BullMQ` (Redis — `REDIS_URL` in `.env`) or `pg-boss` (stores jobs in your PostgreSQL, no Redis to run).
39
+ - **Mailer** → pick an email provider: `Gmail` (preconfigured `smtp.gmail.com`, no host/port to type) or `Other (custom SMTP)` (asks for host + port). Either way you're then asked for the sending email address and password. **For Gmail this must be a 16-character App Password, not your normal Gmail password** — the prompt validates the length and rejects anything that isn't 16 characters. See [Mailer](../guides/mailer.md) for the full walkthrough, including how to generate an App Password.
40
+ - **User portal / Admin portal** → scaffold a large set of ready-made models and routes (auth, profile, billing, support tickets, admin dashboard, content management, etc.). See [Generated Portals](../guides/generated-portals.md) for the complete list.
41
+ - **Role-based access control** → generates a `Role` model and swaps every protected route's `middlewares` export to use the `requireAuth('role')` shorthand instead of an inline guard. See [RBAC](../guides/rbac.md).
42
+
43
+ After confirmation it:
44
+
45
+ 1. Writes the full project tree (see [Project Structure](./project-structure.md)).
46
+ 2. Creates `efc.config.ts` pre-configured for your choices.
47
+ 3. Generates `.env` (gitignored, `JWT_SECRET` pre-filled with `openssl rand -hex 64`, plus `SMTP_*` vars if you enabled the mailer) and `.env.example` (committed, documented placeholders).
48
+ 4. Adds `.env` to `.gitignore`.
49
+ 5. Writes `package.json` lifecycle scripts (`dev`, `build`, `start`, `test`, `db:migrate`, `db:rollback`, `db:seed`, `db:studio`).
50
+ 6. With a User or Admin portal, writes `src/migrations/00000000000000_init` that creates every generated model's table/collection and indexes.
51
+ 7. Runs `npm install` with the dependencies for your selections, then installs the `efc` CLI globally.
52
+
53
+ ---
54
+
55
+ ## Generated `package.json` scripts
56
+
57
+ | Script | Expands to | When to use |
58
+ |---|---|---|
59
+ | `npm run dev` | `efc start dev` | Local development — hot-reload, single process |
60
+ | `npm run build` | `efc build prod` | CI/CD — type-check + compile to `dist/` |
61
+ | `npm start` | `efc start prod` | Production — runs `dist/` with clustering |
62
+ | `npm test` | `efc run tests` | Test suite via Vitest |
63
+ | `npm run db:migrate` | `efc db migrate` | Apply pending migrations |
64
+ | `npm run db:rollback` | `efc db rollback` | Revert the last migration batch |
65
+ | `npm run db:seed` | `efc db seed` | Run seed scripts |
66
+ | `npm run db:studio` | `efc db studio` | Browse the database (read-only) |
67
+
68
+ ---
69
+
70
+ ## First run
71
+
72
+ ```bash
73
+ cd my-api
74
+ npm run dev # tables / indexes are created on first use — no migration needed
75
+ # 12:00:01 INFO [primary] Worker primary listening on :3000
76
+ ```
77
+
78
+ The server is live at `http://localhost:3000`. The scaffolder creates a `src/api/health.ts` route at `/health` as a smoke test.
79
+
80
+ ---
81
+
82
+ ## Next steps
83
+
84
+ - [Project Structure](./project-structure.md) — understand every file the scaffolder created.
85
+ - [File-Based Routing](../core-concepts/file-based-routing.md) — learn the naming rules.
86
+ - [Generated Portals](../guides/generated-portals.md) — full model/route inventory if you enabled User or Admin portal.
87
+ - [RBAC](../guides/rbac.md) — role-based route protection.
88
+ - [Mailer](../guides/mailer.md) — Gmail app-password and custom SMTP setup.
89
+ - [Migrations & Seeds](../guides/migrations.md) — evolving the schema.
90
+ - [Validation](../guides/validation.md) — `export const schema` with zod & co.
91
+ - [CLI Reference](../cli/index.md) — all `efc` commands.