express-file-cluster 0.10.0 → 0.11.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 (194) hide show
  1. package/dist/auth/index.cjs +7 -6
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +3 -1
  4. package/dist/auth/index.d.ts +3 -1
  5. package/dist/auth/index.js +5 -5
  6. package/dist/{chunk-73XJUT2S.js → chunk-2IDRC7RK.js} +163 -5
  7. package/dist/chunk-2IDRC7RK.js.map +1 -0
  8. package/dist/{chunk-QDEDOHP7.js → chunk-336IU55W.js} +9 -42
  9. package/dist/chunk-336IU55W.js.map +1 -0
  10. package/dist/{chunk-R52CUEGT.js → chunk-3SWI46YK.js} +2 -2
  11. package/dist/{chunk-7KO4DJRJ.cjs → chunk-6WTMRZS7.cjs} +14 -14
  12. package/dist/{chunk-7KO4DJRJ.cjs.map → chunk-6WTMRZS7.cjs.map} +1 -1
  13. package/dist/chunk-AGOYTFRO.cjs +42 -0
  14. package/dist/chunk-AGOYTFRO.cjs.map +1 -0
  15. package/dist/{chunk-RAB44UGX.js → chunk-B6MB6HEG.js} +1 -1
  16. package/dist/chunk-CGY7JU4Y.cjs +8 -0
  17. package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
  18. package/dist/chunk-DGYPIIJE.cjs +845 -0
  19. package/dist/chunk-DGYPIIJE.cjs.map +1 -0
  20. package/dist/{chunk-EGSSZUVO.js → chunk-DN4TCGYB.js} +38 -11
  21. package/dist/chunk-DN4TCGYB.js.map +1 -0
  22. package/dist/{chunk-YK4ZM3CA.cjs → chunk-DTMDJGRW.cjs} +15 -15
  23. package/dist/{chunk-YK4ZM3CA.cjs.map → chunk-DTMDJGRW.cjs.map} +1 -1
  24. package/dist/{chunk-R4XO4SVM.js → chunk-EJDZZ4KX.js} +4 -4
  25. package/dist/{chunk-NKLOE4AK.cjs → chunk-GWMW6XY7.cjs} +20 -53
  26. package/dist/chunk-GWMW6XY7.cjs.map +1 -0
  27. package/dist/{chunk-GBI77W5T.cjs → chunk-H2PVWCWC.cjs} +1 -1
  28. package/dist/{chunk-GBI77W5T.cjs.map → chunk-H2PVWCWC.cjs.map} +1 -1
  29. package/dist/{chunk-KFVFP2Q7.cjs → chunk-IEF6AEK3.cjs} +70 -55
  30. package/dist/chunk-IEF6AEK3.cjs.map +1 -0
  31. package/dist/{chunk-PGJQK36V.js → chunk-JBOMTZT5.js} +7 -5
  32. package/dist/{chunk-PGJQK36V.js.map → chunk-JBOMTZT5.js.map} +1 -1
  33. package/dist/chunk-LECHRAU3.js +845 -0
  34. package/dist/chunk-LECHRAU3.js.map +1 -0
  35. package/dist/{chunk-4DOHQU6I.cjs → chunk-M53GODCX.cjs} +39 -12
  36. package/dist/chunk-M53GODCX.cjs.map +1 -0
  37. package/dist/{chunk-NI2BNGGV.js → chunk-O2E7H2XA.js} +2 -2
  38. package/dist/{chunk-ATVD2HGC.js → chunk-OM2XJJWX.js} +4 -4
  39. package/dist/{chunk-DUADUR6R.cjs → chunk-QSIP7YLW.cjs} +172 -14
  40. package/dist/chunk-QSIP7YLW.cjs.map +1 -0
  41. package/dist/{chunk-7KC2H76D.js → chunk-R6GPQZLI.js} +62 -47
  42. package/dist/chunk-R6GPQZLI.js.map +1 -0
  43. package/dist/{chunk-WBLUGOAG.cjs → chunk-RPL2IFWK.cjs} +8 -5
  44. package/dist/chunk-RPL2IFWK.cjs.map +1 -0
  45. package/dist/{chunk-HBCY7ILD.cjs → chunk-SOU3PBJC.cjs} +97 -95
  46. package/dist/chunk-SOU3PBJC.cjs.map +1 -0
  47. package/dist/{chunk-DCJOWFVD.cjs → chunk-WHBSVYUY.cjs} +3 -3
  48. package/dist/{chunk-DCJOWFVD.cjs.map → chunk-WHBSVYUY.cjs.map} +1 -1
  49. package/dist/chunk-XPY5TQDK.js +42 -0
  50. package/dist/chunk-XPY5TQDK.js.map +1 -0
  51. package/dist/cli/db-runner.cjs +81 -42
  52. package/dist/cli/db-runner.cjs.map +1 -1
  53. package/dist/cli/db-runner.js +54 -16
  54. package/dist/cli/db-runner.js.map +1 -1
  55. package/dist/cli/index.cjs +23 -25
  56. package/dist/cli/index.cjs.map +1 -1
  57. package/dist/cli/index.js +12 -17
  58. package/dist/cli/index.js.map +1 -1
  59. package/dist/docs/api-reference/auth.md +23 -0
  60. package/dist/docs/api-reference/compose.md +1 -1
  61. package/dist/docs/api-reference/db.md +8 -0
  62. package/dist/docs/api-reference/ignite.md +8 -1
  63. package/dist/docs/api-reference/openapi.md +36 -0
  64. package/dist/docs/api-reference/testing.md +28 -0
  65. package/dist/docs/api-reference/websockets.md +23 -0
  66. package/dist/docs/cli/add.md +2 -2
  67. package/dist/docs/core-concepts/clustering.md +2 -0
  68. package/dist/docs/core-concepts/file-based-routing.md +4 -0
  69. package/dist/docs/core-concepts/middleware.md +2 -2
  70. package/dist/docs/getting-started/index.md +4 -0
  71. package/dist/docs/guides/authentication.md +33 -0
  72. package/dist/docs/guides/caching.md +2 -0
  73. package/dist/docs/guides/database.md +15 -0
  74. package/dist/docs/guides/environment-variables.md +6 -0
  75. package/dist/docs/guides/feature-matrix.md +9 -0
  76. package/dist/docs/guides/generated-portals.md +3 -1
  77. package/dist/docs/guides/logging.md +17 -0
  78. package/dist/docs/guides/migrations.md +4 -2
  79. package/dist/docs/guides/openapi.md +57 -0
  80. package/dist/docs/guides/testing.md +31 -0
  81. package/dist/docs/guides/validation.md +2 -0
  82. package/dist/docs/guides/websockets.md +60 -0
  83. package/dist/docs/index.md +4 -1
  84. package/dist/docs/skills/SKILL.md +8 -2
  85. package/dist/docs/skills/api-surface.md +30 -4
  86. package/dist/docs/skills/auth-internals.md +14 -1
  87. package/dist/docs/skills/pre-flight.md +8 -0
  88. package/dist/docs/skills/routing-rules.md +5 -1
  89. package/dist/docs/skills/what-not-to-invent.md +11 -1
  90. package/dist/docs/versioning.md +1 -1
  91. package/dist/index.cjs +100 -267
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +28 -3
  94. package/dist/index.d.ts +28 -3
  95. package/dist/index.js +52 -221
  96. package/dist/index.js.map +1 -1
  97. package/dist/openapi-cjs.cjs +5 -0
  98. package/dist/pgboss-backend-PQW6I3VF.js +14 -0
  99. package/dist/pgboss-backend-QVXISTLP.cjs +15 -0
  100. package/dist/pgboss-backend-QVXISTLP.cjs.map +1 -0
  101. package/dist/registry/index.json +27 -3
  102. package/dist/registry/js-mongo/account-security.json +1 -1
  103. package/dist/registry/js-mongo/admin-users.json +1 -1
  104. package/dist/registry/js-mongo/auth.json +1 -1
  105. package/dist/registry/js-mongo/auth@apple.json +1 -1
  106. package/dist/registry/js-mongo/auth@google.json +1 -1
  107. package/dist/registry/js-mongo/forgot-password.json +1 -1
  108. package/dist/registry/js-mongo/user-profile.json +1 -1
  109. package/dist/registry/js-mongo-collection/account-security.json +1 -1
  110. package/dist/registry/js-mongo-collection/admin-users.json +1 -1
  111. package/dist/registry/js-mongo-collection/auth.json +1 -1
  112. package/dist/registry/js-mongo-collection/auth@apple.json +1 -1
  113. package/dist/registry/js-mongo-collection/auth@google.json +1 -1
  114. package/dist/registry/js-mongo-collection/forgot-password.json +1 -1
  115. package/dist/registry/js-mongo-collection/user-profile.json +1 -1
  116. package/dist/registry/js-pg-model/account-security.json +1 -1
  117. package/dist/registry/js-pg-model/admin-users.json +1 -1
  118. package/dist/registry/js-pg-model/auth.json +1 -1
  119. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  120. package/dist/registry/js-pg-model/auth@google.json +1 -1
  121. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  122. package/dist/registry/js-pg-model/user-profile.json +1 -1
  123. package/dist/registry/js-pg-table/account-security.json +1 -1
  124. package/dist/registry/js-pg-table/admin-users.json +1 -1
  125. package/dist/registry/js-pg-table/auth.json +1 -1
  126. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  127. package/dist/registry/js-pg-table/auth@google.json +1 -1
  128. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  129. package/dist/registry/js-pg-table/user-profile.json +1 -1
  130. package/dist/registry/ts-mongo/account-security.json +1 -1
  131. package/dist/registry/ts-mongo/admin-users.json +1 -1
  132. package/dist/registry/ts-mongo/auth.json +1 -1
  133. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  134. package/dist/registry/ts-mongo/auth@google.json +1 -1
  135. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  136. package/dist/registry/ts-mongo/user-profile.json +1 -1
  137. package/dist/registry/ts-mongo-collection/account-security.json +1 -1
  138. package/dist/registry/ts-mongo-collection/admin-users.json +1 -1
  139. package/dist/registry/ts-mongo-collection/auth.json +1 -1
  140. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -1
  141. package/dist/registry/ts-mongo-collection/auth@google.json +1 -1
  142. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -1
  143. package/dist/registry/ts-mongo-collection/user-profile.json +1 -1
  144. package/dist/registry/ts-pg-model/account-security.json +1 -1
  145. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  146. package/dist/registry/ts-pg-model/auth.json +1 -1
  147. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  148. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  149. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  150. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  151. package/dist/registry/ts-pg-table/account-security.json +1 -1
  152. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  153. package/dist/registry/ts-pg-table/auth.json +1 -1
  154. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  155. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  156. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  157. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  158. package/dist/tasks/index.cjs +3 -2
  159. package/dist/tasks/index.cjs.map +1 -1
  160. package/dist/tasks/index.d.cts +3 -1
  161. package/dist/tasks/index.d.ts +3 -1
  162. package/dist/tasks/index.js +1 -1
  163. package/dist/testing-cjs.cjs +5 -0
  164. package/dist/testing.cjs +65 -0
  165. package/dist/testing.cjs.map +1 -0
  166. package/dist/testing.d.cts +30 -0
  167. package/dist/testing.d.ts +30 -0
  168. package/dist/testing.js +64 -0
  169. package/dist/testing.js.map +1 -0
  170. package/dist/thread-runner.cjs +4 -3
  171. package/dist/thread-runner.cjs.map +1 -1
  172. package/dist/thread-runner.js +2 -2
  173. package/dist/{types-Bnxvj3l0.d.ts → types-D3QmZgeX.d.cts} +88 -2
  174. package/dist/{types-Bnxvj3l0.d.cts → types-D3QmZgeX.d.ts} +88 -2
  175. package/package.json +11 -4
  176. package/dist/chunk-4DOHQU6I.cjs.map +0 -1
  177. package/dist/chunk-73XJUT2S.js.map +0 -1
  178. package/dist/chunk-7KC2H76D.js.map +0 -1
  179. package/dist/chunk-DUADUR6R.cjs.map +0 -1
  180. package/dist/chunk-EGSSZUVO.js.map +0 -1
  181. package/dist/chunk-HBCY7ILD.cjs.map +0 -1
  182. package/dist/chunk-KFVFP2Q7.cjs.map +0 -1
  183. package/dist/chunk-NKLOE4AK.cjs.map +0 -1
  184. package/dist/chunk-QDEDOHP7.js.map +0 -1
  185. package/dist/chunk-WBLUGOAG.cjs.map +0 -1
  186. package/dist/pgboss-backend-FW42SBSM.js +0 -14
  187. package/dist/pgboss-backend-RVHUBJTU.cjs +0 -14
  188. package/dist/pgboss-backend-RVHUBJTU.cjs.map +0 -1
  189. /package/dist/{chunk-R52CUEGT.js.map → chunk-3SWI46YK.js.map} +0 -0
  190. /package/dist/{chunk-RAB44UGX.js.map → chunk-B6MB6HEG.js.map} +0 -0
  191. /package/dist/{chunk-R4XO4SVM.js.map → chunk-EJDZZ4KX.js.map} +0 -0
  192. /package/dist/{chunk-NI2BNGGV.js.map → chunk-O2E7H2XA.js.map} +0 -0
  193. /package/dist/{chunk-ATVD2HGC.js.map → chunk-OM2XJJWX.js.map} +0 -0
  194. /package/dist/{pgboss-backend-FW42SBSM.js.map → pgboss-backend-PQW6I3VF.js.map} +0 -0
@@ -267,3 +267,26 @@ Accepts any value the [`jose`](https://github.com/panva/jose) library supports:
267
267
  ## Algorithm
268
268
 
269
269
  Tokens are signed with **HS256** (HMAC-SHA256). The secret is UTF-8 encoded before signing. Asymmetric algorithms (RS256, ES256) are not currently supported.
270
+
271
+ ## Generated account-security routes
272
+
273
+ These are app templates, not exports from `/auth`. `POST /auth/change-password` verifies the authenticated account's old password, hashes the replacement, clears stored refresh credentials, and uses `revokeAllSessions` (cache required). Its 200 response is `{ message: 'Password changed successfully' }`; invalid input returns 400, invalid credentials 401, and suspended accounts 403. Revocation failures propagate. Existing access tokens, including the caller's, are revoked.
274
+
275
+ Generated 2FA routes (app code, not additional core exports):
276
+
277
+ | Method/path | Input | Result |
278
+ |---|---|---|
279
+ | `GET /auth/2fa/setup` | authenticated | `{ enabled, method, methods }` |
280
+ | `POST /auth/2fa/setup` | authenticated; `{ password, method }` | TOTP secret/`otpauthUrl` (200), or email `codeSent` (202) |
281
+ | `POST /auth/2fa/setup` | authenticated; `{ password, method, code }` | confirms enrollment; revokes sessions (200) |
282
+ | `POST /auth/login`, `POST /auth/2fa/verify` | `{ email, password, code? }` | no tokens until the enrolled factor passes; missing/invalid code returns 401 with `twoFactorRequired` and `method`; a password-verified email request without code sends one |
283
+ | `POST /auth/2fa/disable` | authenticated; `{ password, code? }` | email without code sends a disable code (202); valid password/code disables and revokes sessions (200) |
284
+
285
+ `TWO_FACTOR_METHOD=totp|email|both` limits enrollment choices. Each account has one method. TOTP is six-digit SHA-1 with 30-second steps (±1 step); email codes last five minutes. Accepted codes cannot be reused. Enrollment/disable require the current password. See [the full flow and upgrade steps](../guides/authentication.md#two-factor-authentication-totp-or-email-otp).
286
+
287
+ Device-session `/auth/sessions` (GET) and `/auth/sessions/:id` (DELETE) remain authenticated 501 extension points.
288
+
289
+
290
+ Generated User/Admin logout requires authentication, compare-and-sets the account's stored refresh token to empty (including bearer logout with no refresh cookie/body), then revokes the current access token and clears cookies. Login persists refresh credentials only while the password hash still matches its verified snapshot. Generated login/refresh tokens carry `efc_auth_at`, captured before credential reads; revocation rejects a token whose authentication started at or before the cutoff, even if it was signed afterwards. Custom token issuers may include this numeric epoch-millisecond claim for the same protection; it can only restrict access, never override a later server-issued time. Existing generated apps must update their owned auth routes as well as the framework to receive these fixes.
291
+
292
+ Password reset atomically consumes the matching, still-unexpired reset token while replacing the password and clearing stored refresh credentials and pending 2FA challenges. Concurrent use has one winner; expiry is rechecked in the database after hashing. Active 2FA enrollment remains enabled. Password changes also invalidate outstanding reset links. Custom auth-entity logout propagates revocation-store failures instead of returning a false success. Existing apps must update their owned reset-password, change-password, two-factor helper and custom logout files.
@@ -41,7 +41,7 @@ export const POST = compose(
41
41
  ## Behaviour
42
42
 
43
43
  - Handlers are called in the order they are passed.
44
- - Each handler receives the real `next` function of its predecessor; calling `next()` advances to the next handler in the chain.
44
+ - Calling `next()` (or `next(null)`) advances to the next handler in the chain. Calling `next(err)` stops the chain and forwards the error to Express; `next('route')` and `next('router')` are forwarded to Express as well.
45
45
  - If the last handler calls `next()`, control passes to the surrounding Express middleware chain (equivalent to the route calling `next()`).
46
46
  - If any handler throws synchronously or returns a rejected promise, the error is forwarded to `next(err)` and bubbles up to the global error handler.
47
47
 
@@ -350,3 +350,11 @@ It throws if accessed before Pre-Flight completes (e.g. at module load time) —
350
350
  ### `getDbClient()` / `setDbClient()`
351
351
 
352
352
  Read or replace the client behind `db` — mainly for tests that bypass `ignite()`.
353
+
354
+ ## PostgreSQL statement preparation
355
+
356
+ `ignite({ databasePool: { preparedStatements: true | false | { max?: number } } })` controls automatic naming of Drizzle model queries, including transaction queries. Default: `true`, with 100 names per physical connection. `max` must be a nonnegative safe integer; zero disables. Reused SQL shapes share names across values; excess new shapes use unnamed execution. The native `db` Pool and explicitly named driver queries retain their behavior. EFC schema sync/drop invalidates reusable shapes without exceeding the connection's lifetime name budget. Reconnect after external DDL; disable for incompatible poolers. See [database guide](../guides/database.md#postgresql-prepared-statements).
357
+
358
+ ## Query metrics
359
+
360
+ `getQueryMetrics(): QueryMetricsSnapshot` and `resetQueryMetrics(): void` are exported from the main package. Opt in using `logging.queries.metrics: true | { maxEntries?: number }` (default off; enabled default limit 1000; zero disables). A snapshot contains `enabled`, `since` (epoch ms), `dropped` (untracked completed-call observations), and detached `entries: ReadonlyArray<QueryMetric>`. Each metric has `model`, `op`, `calls`, `errors`, `statements`, `totalMs`, `minMs`, `maxMs`, `meanMs`, `slow`. Reset starts a new process-local window and leaves collection enabled. Values/SQL/error strings are never included. Nested calls' statement counts are inclusive. [Details](../guides/logging.md#query-metrics).
@@ -31,7 +31,7 @@ interface EFCConfig {
31
31
  // Database
32
32
  database?: 'mongodb' | 'postgresql';
33
33
  databaseUrl?: string;
34
- databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number };
34
+ databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number; preparedStatements?: boolean | { max?: number } };
35
35
 
36
36
  // Auth
37
37
  authStrategy?: 'http-only' | 'bearer'; // 'localStorage' = old name for 'bearer'
@@ -171,6 +171,7 @@ databasePool: { max: 5, idleTimeoutMs: 30_000, connectionTimeoutMs: 5_000 },
171
171
  | Option | PostgreSQL (`pg` Pool) | MongoDB (mongoose) |
172
172
  |---|---|---|
173
173
  | `max` | `max` — default 10 | `maxPoolSize` — default 100 |
174
+ | `preparedStatements` | `true` (default): up to 100 named statements per connection; `{ max: n }` changes the lifetime budget, `false` / `{ max: 0 }` disables | ignored |
174
175
  | `idleTimeoutMs` | `idleTimeoutMillis` — default 10000 | `maxIdleTimeMS` — default: never |
175
176
  | `connectionTimeoutMs` | `connectionTimeoutMillis` — default: no limit | `serverSelectionTimeoutMS` (default 30000) and `waitQueueTimeoutMS` (default: no limit) |
176
177
 
@@ -362,3 +363,9 @@ ignite({ port: 3000 })
362
363
  | `timeoutMs` | `number` | `10_000` | Force-exit after this many milliseconds if `server.close()` hasn't finished |
363
364
 
364
365
  On a worker, the signal closes the HTTP server (in-flight requests finish), drains running task jobs, then exits. On the cluster primary it relays `SIGTERM` to every worker — so `docker stop` / Kubernetes, which signal only PID 1, still shut down gracefully — and force-exits after `timeoutMs + 2s` if a worker hangs. Repeated signals are ignored rather than killing a worker mid-drain.
366
+
367
+ `logging.queries.metrics: true | { maxEntries?: number }` enables bounded per-process query counters and latency summaries (default off; enabled default limit 1000). Read/reset through `getQueryMetrics` / `resetQueryMetrics` from the main package; see [query metrics](../guides/logging.md#query-metrics).
368
+
369
+ ## Since 0.11.0: OpenAPI and WebSockets
370
+
371
+ `openapi?: boolean | OpenAPIOptions` opts into `/openapi.json` (or `path`) with route-derived OpenAPI 3.1 JSON. `websocket?: false | WebSocketOptions` configures file `WS` upgrades; they attach automatically when exported, unless disabled. Both features share global middleware. See [OpenAPI](./openapi.md) and [WebSockets](./websockets.md) for exact options and lifecycle.
@@ -0,0 +1,36 @@
1
+ # OpenAPI API (since 0.11.0)
2
+
3
+ Exported from `express-file-cluster`:
4
+
5
+ ```ts
6
+ generateOpenAPI(
7
+ routes: MountedRoute[] | string, // explicit API directory or already loaded metadata
8
+ options?: OpenAPIOptions & { basePath?: string },
9
+ ): Promise<OpenAPIDocument>
10
+ ```
11
+
12
+ `OpenAPIDocument` contains `openapi: '3.1.0'`, `info`, `paths`, `components.schemas`, and optional `servers`. A directory argument scans/imports route files. A loaded-route argument uses existing metadata. Generation uses HTTP methods, metadata and request schemas. It does not change validation or execute handlers.
13
+
14
+ `ignite({ openapi: true | OpenAPIOptions })` and `createTestApp({ openapi: true | OpenAPIOptions })` generate once and serve the document. Default: disabled.
15
+
16
+ | Option | Default | Purpose |
17
+ |---|---|---|
18
+ | `path?: string` | `/openapi.json` | Absolute static document URL; reserved before API routes. |
19
+ | `info?: { title; version; description? }` | project package metadata in ignite; EFC API/1.0.0 in standalone/testing | Required OpenAPI info. |
20
+ | `servers?: { url; description? }[]` | omitted | Deployment URLs. |
21
+ | `components?: Record<string, unknown>` | generated schemas | Explicit components such as security schemes; generated component names avoid collisions. |
22
+ | `schemaToJSONSchema?: (validator: Validator) => JSONSchema \| Promise<JSONSchema>` | Standard JSON Schema input conversion | Adapter for validators without the standard JSON Schema protocol. |
23
+
24
+ `JSONSchema = boolean | Record<string, unknown>`. `RouteMethodMeta` adds `summary`, `tags`, `operationId`, and `openapi: Record<string, unknown> & { hidden?: boolean }`. The explicit operation fields override generated defaults; author-supplied OpenAPI objects must be valid. Only `hidden` is stripped. IDs are normalized for optional path expansions and duplicates are rejected.
25
+
26
+ See [the guide](../guides/openapi.md) for conversion, security and catch-all semantics.
27
+
28
+ The CommonJS generator delegates asynchronously to the ESM implementation, preserving native ESM route imports (including top-level await). It has the same Promise return type in both formats.
29
+
30
+ Document URL collisions are checked against actual GET/HEAD route matchers before hidden operations are filtered. Equivalent optional path variants are collapsed using the first parameter binding; ambiguous templates across routes throw.
31
+
32
+ Query/params object combinators are expanded into parameter fields. Unions retain branch-specific fields as optional and require only fields required by every branch; intersections combine requirements. `x-efc-query-schema` points to the full query schema for cross-field constraints. Object query fields use `deepObject` with `explode: true`. Non-object parameter shapes require explicit `meta.METHOD.openapi.parameters`; generation otherwise reports the route and location instead of omitting inputs.
33
+
34
+ Array query parameters expose the bracketed wire name (`tags[]`), `style: form`, and `explode: true`; the request property remains `tags`. External field references are retained without fetching, and explicit local type hints enable object/array style inference. Uninspectable root parameter objects still require explicit operation parameters.
35
+
36
+ `requestBody.required` is inferred from whether the converted schema accepts `{}`, the missing-body value supplied by Express. Local refs and logical constraints are evaluated without running validators; unresolved external/dynamic references conservatively remain required. Explicit `meta.METHOD.openapi.requestBody` overrides this inference. Example-only bodies are optional.
@@ -0,0 +1,28 @@
1
+ # `createTestApp(options)`
2
+
3
+ ```ts
4
+ import { createTestApp } from 'express-file-cluster/testing';
5
+ import type { TestAppOptions } from 'express-file-cluster/testing';
6
+ ```
7
+
8
+ Returns `Promise<express.Express>` with real file-based routes mounted, without starting a listener or booting services.
9
+
10
+ | Option | Default | Behavior |
11
+ |---|---|---|
12
+ | `apiDir: string` | required | Absolute path, or path resolved against the current working directory; rejects a nonexistent/non-directory path. |
13
+ | `basePath?: string` | `/v1/api` | Mount point for the API router. |
14
+ | `globalMiddlewares?: RequestHandler[]` | `[]` | Runs after body/cookie parsing and before file middleware/validation. |
15
+ | `auth?: { secret; strategy?; expiresIn?; cookieDomain? }` | unchanged | Configures process-wide auth; strategy defaults to `http-only`, expiry to `1h`. |
16
+ | `requestTimeout?: number` | disabled | Production request timeout in milliseconds; responds 408. |
17
+ | `trustProxy?` | Express default | Same value type as `EFCConfig.trustProxy`; supports client-IP tests behind a proxy. |
18
+ | `onError?: ErrorRequestHandler` | production error handler | Express error middleware mounted after the API. |
19
+
20
+ Shared behavior with production: JSON/form/cookie parsing, AsyncLocalStorage request context, request IDs, bigint JSON serialization, route scanning/order, file middleware, schema validation, method dispatch, and safe error responses. CORS, logging, the dashboard and service initialization are disabled/omitted. Auth/logging and imported modules retain process-wide state; see [test isolation](../guides/testing.md).
21
+
22
+ This helper's `apiDir` is **not** a new `ignite()` option. `createTestApp` is exported only from `/testing`; no `/db`, `/router` or `/middleware` subpaths are added.
23
+
24
+ The CommonJS `/testing` entry delegates to the ESM helper using native `import()`, so dynamically imported ESM routes share its authentication and request context. The Node/runner must support the route files' module format.
25
+
26
+ The ESM and CommonJS builds share process-wide auth configuration, request AsyncLocalStorage and cache state. CommonJS `requireAuth` global middleware therefore sees helper auth options, preserves `getCurrentUser()` across awaits into ESM routes, and observes the same revocations. Model/queue fixtures are still configured separately.
27
+
28
+ Since 0.11.0: `openapi?: boolean | OpenAPIOptions` enables the same document endpoint for tests. For WS tests, use `http.createServer(app)` and `attachWebSockets(server, app)`, then close the server in cleanup. The helper itself still never starts a listener.
@@ -0,0 +1,23 @@
1
+ # WebSocket API (since 0.11.0)
2
+
3
+ ```ts
4
+ import { attachWebSockets, closeWebSockets } from 'express-file-cluster';
5
+ import type { WebSocketHandler, WebSocketOptions } from 'express-file-cluster';
6
+ ```
7
+
8
+ `WebSocketHandler = (socket: ws.WebSocket, request: express.Request) => void | Promise<void>`. Export it as `WS` from a route file. An invalid non-function `WS` export fails boot. File middleware runs before connection; `schema.WS` validates the HTTP handshake.
9
+
10
+ `attachWebSockets(server: http.Server, app: express.Express, options?: WebSocketOptions): ws.WebSocketServer` attaches upgrade handling once. Used automatically by ignite when WS routes exist, or explicitly with an EFC test app/custom server. It also integrates socket draining with `server.close()`.
11
+
12
+ `closeWebSockets(server: http.Server, timeoutMs = 1000): Promise<void>` sends 1001 and waits for clients to disconnect, terminating remaining peers at the deadline. Pending handshake sockets are destroyed immediately, including connections waiting in middleware. It is idempotent, and stops heartbeats. Calling it prevents further upgrades on that attachment.
13
+
14
+ | Option | Default | Behavior |
15
+ |---|---|---|
16
+ | `maxPayload?: number` | 1048576 | Integer inbound message byte limit from 1 through 2147483647. Compression is disabled. |
17
+ | `origins?: string[]` | same-origin | Exact HTTP(S) browser origins. Missing Origin is allowed; malformed/opaque origins are refused. |
18
+ | `heartbeatIntervalMs?: number` | 30000 | Integer ping/pong interval from 0 through 2147483647 ms; 0 disables. |
19
+ | `handshakeTimeoutMs?: number` | 10000 | Integer deadline from 1 through 2147483647 ms for upgrade middleware. |
20
+
21
+ `ignite({ websocket: false })` disables automatic attachment. No new import subpath is added. See [the guide](../guides/websockets.md) for middleware, authentication, async context, error handling, cluster boundaries and test cleanup.
22
+
23
+ Upgrades pipelined behind an unfinished HTTP response close the connection without throwing an uncaught socket-assignment error.
@@ -47,7 +47,7 @@ efc diff # compare installed features with the regi
47
47
  | `auth@apple` | Sign in with Apple: `GET /auth/apple` → Apple → `POST /auth/apple/callback` (+ `OAuthAccount`). Asks for Services ID, Team ID, Key ID and the `.p8` key | auth |
48
48
  | `user-profile` | `GET/PUT /user/profile` | auth |
49
49
  | `forgot-password` | `/auth/forgot-password`, `/auth/reset-password` | auth |
50
- | `account-security` | change password, 2FA, sessions, token refresh + `Session` model | auth |
50
+ | `account-security` | password changes, token refresh, TOTP/email OTP (asks allowed methods); device-session extension points return 501; `Session` model | auth |
51
51
  | `email-verification` | `/auth/verify-email`, resend | auth |
52
52
  | `account-settings` | avatar, settings, account, dashboard, activity | auth |
53
53
  | `notifications` | `Notification` model + `/user/notifications` | auth |
@@ -140,7 +140,7 @@ Wrong answers are asked again. A question is only asked for a variable the app d
140
140
 
141
141
  ```json
142
142
  {
143
- "registry": "0.10.0",
143
+ "registry": "0.11.0",
144
144
  "language": "typescript",
145
145
  "database": "postgresql",
146
146
  "modelApi": "defineTable",
@@ -112,3 +112,5 @@ Pass a custom timeout (milliseconds) as the second argument:
112
112
  ```ts
113
113
  gracefulShutdown(server, 30_000); // 30-second drain window
114
114
  ```
115
+
116
+ WebSockets (since 0.11.0): each worker owns its accepted connections. Broadcasts are worker-local unless the application uses pub/sub. Graceful worker shutdown closes sockets with 1001, waits for acknowledgments, and terminates unresponsive peers within its drain budget.
@@ -23,6 +23,8 @@ EFC turns your directory tree into your route tree. The scanner walks `src/api/`
23
23
 
24
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
25
 
26
+ Catch-all paths are split into segments **before** each segment is URI-decoded once. `/docs/100%25/a%2Fb/a%252Fb` produces `['100%', 'a/b', 'a%2Fb']`; an encoded slash stays inside its original segment. Named parameters preceding the catch-all are also decoded once.
27
+
26
28
  **`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
29
 
28
30
  ---
@@ -233,3 +235,5 @@ export const GET = async (req, res) => {
233
235
  5. Registers an `app.all()` catch for unimplemented methods that returns 405.
234
236
 
235
237
  `asyncWrap` wraps every handler in `Promise.resolve(...).catch(next)` so that thrown errors and rejected promises are forwarded to the Express error handler automatically.
238
+
239
+ Since 0.11.0: route files can also export a `WS` connection handler, sharing the file's middleware and params with HTTP methods. See [WebSockets](../guides/websockets.md). Opt-in [OpenAPI](../guides/openapi.md) documents loaded HTTP method/meta/schema exports.
@@ -74,7 +74,7 @@ export const POST = compose(
74
74
 
75
75
  ## How `compose` works
76
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)`.
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. Calling `next(err)` stops the composed chain and forwards the error; `next('route')` and `next('router')` retain their Express meanings. If any handler throws or rejects, the error is forwarded to Express's error chain via `next(err)`.
78
78
 
79
79
  ```ts
80
80
  export function compose(...handlers: RequestHandler[]): RequestHandler {
@@ -85,7 +85,7 @@ export function compose(...handlers: RequestHandler[]): RequestHandler {
85
85
  if (i >= handlers.length) { next(); return; }
86
86
  const handler = handlers[i];
87
87
  try {
88
- Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);
88
+ Promise.resolve(handler(req, res, (err) => err ? next(err) : dispatch(i + 1))).catch(next);
89
89
  } catch (err) {
90
90
  next(err);
91
91
  }
@@ -98,3 +98,7 @@ The server is live at `http://localhost:3000`. The scaffolder creates a `src/api
98
98
  - [Migrations & Seeds](../guides/migrations.md) — evolving the schema.
99
99
  - [Validation](../guides/validation.md) — `export const schema` with zod & co.
100
100
  - [CLI Reference](../cli/index.md) — all `efc` commands.
101
+
102
+ ### Choosing two-factor authentication
103
+
104
+ Select **Account security** in the init feature picker, then choose **Authenticator app (TOTP)**, **Email OTP**, or **Both — users choose**. Email/both automatically adds the SMTP email client and asks for mail settings. Each user or admin can enroll one allowed method. The generated `TWO_FACTOR_METHOD` setting controls the choices and `TWO_FACTOR_KEY` protects stored secrets; keep the key stable across deployments. See [enrollment, login and disable](../guides/authentication.md#two-factor-authentication-totp-or-email-otp).
@@ -282,3 +282,36 @@ future default doesn't lock anyone out. Apps scaffolded before 0.9.2 stored **bc
282
282
  `verifyPassword` deliberately rejects (EFC carries no bcrypt code or dependency): those users reset
283
283
  their password once — the reset route stores a scrypt hash. See the
284
284
  [auth API reference](../api-reference/auth.md#hashpassword--verifypassword--passwordneedsrehash).
285
+
286
+ ## Generated password changes and security extension points
287
+
288
+ `efc add account-security` adds a protected `POST /auth/change-password`. Send nonempty strings `oldPassword` and `newPassword`. The route verifies the current password for the authenticated User or Admin, stores a new `hashPassword()` hash, invalidates its stored refresh token, and revokes existing access tokens with `revokeAllSessions`. The current session is also revoked: log in again with the new password. The endpoint limits attempts to ten per account per fifteen minutes and needs the scaffolded cache.
289
+
290
+ Revocation errors propagate instead of reporting success. Because the database update precedes cache revocation, a cache failure can leave the new password persisted even though the request fails; restore cache access and log in again.
291
+
292
+ Device-session list/revoke routes remain authenticated 501 extension points. Two-factor authentication is implemented as generated app code, described below.
293
+
294
+ ## Two-factor authentication: TOTP or email OTP
295
+
296
+ When selecting **Account security** during `create-efc-app`, choose **Authenticator app (TOTP)**, **Email OTP**, or **Both — users choose**. Email-capable choices also add the email-client integration and ask for SMTP settings. `efc add account-security` asks the same method question; install `efc add email-client` as well when choosing email or both. `TWO_FACTOR_METHOD=totp|email|both` controls allowed methods; each User or Admin enrolls one allowed method. Changing the app setting does not silently downgrade enrolled accounts: an account using a method you disable cannot sign in until you restore it or migrate the account.
297
+
298
+ Keep the generated `TWO_FACTOR_KEY` (64 hex characters / 32 random bytes) in your secret store and identical across instances. It encrypts TOTP secrets with AES-256-GCM and authenticates stored email-code digests, independently of `JWT_SECRET`. Keep it when upgrading or rotating JWT keys. Replacing it without migrating/re-enrolling the accounts prevents verification of existing secrets.
299
+
300
+ 1. Authenticate, then `GET /auth/2fa/setup` to see `{ enabled, method, methods }`.
301
+ 2. Start enrollment with `POST /auth/2fa/setup`, body `{ password, method: 'totp' | 'email' }`. The current password is required. TOTP returns `{ secret, otpauthUrl, expiresIn: 600 }`: enter the secret in an authenticator or render the URI as a QR code in your UI. Email sends a six-digit code to the account's stored email and returns 202 `{ method: 'email', codeSent: true, expiresIn: 300 }`.
302
+ 3. Confirm with `POST /auth/2fa/setup`, body `{ password, method, code }`. The method must match the pending enrollment. Only a valid, unexpired code enables 2FA. Successful enrollment clears refresh credentials and revokes existing access tokens, including the current session.
303
+ 4. Sign in with `POST /auth/login` or `/auth/2fa/verify`, body `{ email, password, code }`. Both endpoints run the same credential checks and rate limit. Without a code, an enrolled account gets 401 `{ twoFactorRequired: true, method }` and no access/refresh token. For email accounts, this password-verified request sends the OTP; repeat with the received code. For TOTP, use the current authenticator code. Wrong passwords never send an email code.
304
+ 5. Disable with authenticated `POST /auth/2fa/disable`, body `{ password, code }`. Email users first send `{ password }` to request a purpose-specific disable code (202), then submit it. Disable requires the current password and a fresh code, erases secrets, clears refresh credentials, and revokes access tokens. To switch methods, disable the current one and enroll the other. Disable email 2FA before changing the email address through the profile route.
305
+
306
+ TOTP uses [RFC 6238](https://www.rfc-editor.org/rfc/rfc6238) SHA-1, six digits and 30-second intervals, accepting one interval of clock drift. Accepted time steps are atomically recorded so the same code cannot be reused, even across workers. Enrollment consumes its code too: wait for the next authenticator code before logging in. Email codes expire in five minutes, are purpose/account/address bound, and are consumed atomically; resending replaces the previous code. Only a keyed digest is stored. Pending TOTP secrets expire after ten minutes. Secret/code fields are stripped from generated record responses; enrollment responses use `Cache-Control: no-store`.
307
+
308
+ Login and verification share a ten-attempt per-account, fifteen-minute limit across both paths; management endpoints share a separate limit. These limits require the scaffolded cache and reject requests when it is unavailable. Use Redis across multiple app instances. SMTP settings and a working task backend are required for email delivery; queue failures invalidate the pending code and propagate instead of reporting success.
309
+
310
+ Refresh tokens are issued only after completing 2FA. Enabling/disabling clears older refresh tokens, and refresh rotation uses a database compare-and-set to reject replay. OAuth sign-in refuses accounts with 2FA enabled; use password plus verification code instead, so OAuth cannot bypass this app-level second factor. OAuth-only accounts must set a password before enrolling. Password reset does not disable 2FA. Recovery codes and automated lost-device recovery are not implemented; provide a separately verified support process before offering enrollment to end users.
311
+
312
+ Existing apps must update their auth-owned models, login/refresh/OAuth helpers and record sanitizers as well as the 2FA routes. Review `efc diff auth account-security`, preserve edited files, and run the normal model migration process if auto-sync is disabled. Set `TWO_FACTOR_KEY` and configure the mailer before enabling email OTP. Updating only the setup endpoint leaves other login paths unchanged.
313
+
314
+
315
+ Generated User/Admin logout requires authentication, compare-and-sets the account's stored refresh token to empty (including bearer logout with no refresh cookie/body), then revokes the current access token and clears cookies. Login persists refresh credentials only while the password hash still matches its verified snapshot. Generated login/refresh tokens carry `efc_auth_at`, captured before credential reads; revocation rejects a token whose authentication started at or before the cutoff, even if it was signed afterwards. Custom token issuers may include this numeric epoch-millisecond claim for the same protection; it can only restrict access, never override a later server-issued time. Existing generated apps must update their owned auth routes as well as the framework to receive these fixes.
316
+
317
+ Password reset atomically consumes the matching, still-unexpired reset token while replacing the password and clearing stored refresh credentials and pending 2FA challenges. Concurrent use has one winner; expiry is rechecked in the database after hashing. Active 2FA enrollment remains enabled. Password changes also invalidate outstanding reset links. Custom auth-entity logout propagates revocation-store failures instead of returning a false success. Existing apps must update their owned reset-password, change-password, two-factor helper and custom logout files.
@@ -153,3 +153,5 @@ cache: { backend: 'redis', url: process.env.REDIS_URL, onRevocationCheckError: '
153
153
  Either way the failure is logged (at most every 30 seconds), and calling `revokeSession` / `revokeAllSessions` during an outage **throws**, so a failed logout is never reported as a success. Plain `cache.get/set` calls are unaffected — they degrade to misses.
154
154
 
155
155
  `revokeToken(res)` still exists and only clears the cookie — prefer `revokeSession` when a cache is configured.
156
+
157
+ ESM and CommonJS imports share the configured backend, key prefix, pending cache fills and revocation failure policy within one process. A backend configured by one build is used by the other; closing it closes the shared backend. Use one application/cache configuration per process.
@@ -232,3 +232,18 @@ export default defineTask({ schedule: '0 * * * *' }, async () => {
232
232
  await Session.deleteMany({ expiresAt: { $lt: new Date() } });
233
233
  });
234
234
  ```
235
+
236
+ ## PostgreSQL prepared statements
237
+
238
+ EFC's PostgreSQL model queries use named prepared statements by default, through node-postgres. SQL shapes are reused across parameter values on each connection, including inside `transaction()`. Drizzle's encoders, row mode and result parsers are preserved; query logging still counts one execution as one statement. Native `db.query()` is unchanged.
239
+
240
+ ```ts
241
+ ignite({
242
+ databaseUrl: process.env.DATABASE_URL,
243
+ databasePool: { max: 5, preparedStatements: { max: 100 } },
244
+ });
245
+ ```
246
+
247
+ The default budget is 100 automatically named statements per physical connection. Existing shapes are reused; when the budget is full, new shapes run unnamed. There is no concurrent eviction/DEALLOCATE. Server statements remain bounded until the connection closes. EFC invalidates reusable shapes after its schema sync/drop changes a table, keeping the same lifetime budget. It does not automatically invalidate after DDL issued outside EFC: reconnect after external schema changes. Named statements explicitly supplied by an application are preserved and are outside this automatic budget. DDL, transaction control and multi-statement SQL are not automatically prepared.
248
+
249
+ Set `databasePool.preparedStatements: false` for transaction poolers that do not support named protocol statements. For PgBouncer, check its [prepared-statement configuration](https://www.pgbouncer.org/config.html#max_prepared_statements); do not assume every deployment supports it. MongoDB ignores this option. This feature avoids repeated parse work for reused SQL; it does not promise faster performance for every query.
@@ -104,3 +104,9 @@ SMTP_FROM=you@example.com
104
104
  In development (`efc start dev`), the CLI loads `.env` into `process.env` before your app runs, so `efc.config.ts`'s `process.env.X` reads see it. It re-reads `.env` fresh on every `tsx watch` restart — editing `.env` and saving a source file is enough to pick up the change, no need to stop and restart `efc start dev` itself. Variables already present in `process.env` (e.g. real OS-exported vars, CI-injected secrets) take precedence over `.env`.
105
105
 
106
106
  In production (`efc start prod`), `.env` is loaded if one exists in the working directory — handy on a plain VPS. Platforms (Docker, Kubernetes, Railway, Heroku) that inject secrets directly into `process.env` always win: the file only fills in variables that aren't already set.
107
+
108
+ ## Generated two-factor authentication
109
+
110
+ - `TWO_FACTOR_METHOD`: `totp` (default), `email`, or `both`. Init asks when Account security is selected; with both, each account chooses one method at enrollment. Disabling a method does not silently disable enrolled accounts.
111
+ - `TWO_FACTOR_KEY`: independent 32-byte encryption/HMAC key as 64 hex characters (`openssl rand -hex 32`). Init generates it for auth. Keep it stable and shared across instances; changing it requires migrating encrypted secrets or re-enrolling accounts. `ignite()` does not read it; generated `src/lib/two-factor` does.
112
+ - Email OTP needs the email-client's `SMTP_*` settings and a running task backend. Init automatically adds the email client for email/both; with `efc add account-security`, add `efc add email-client` too. Codes expire after five minutes.
@@ -56,3 +56,12 @@ What each model API does on which engine — and the test that proves it. Every
56
56
  | Query logging + N+1 warnings | ✓ | ✓ | ✓ | ✓ | `db/query-log.integration.test.ts: warns once per request about an N+1 pattern` |
57
57
  | `efc db studio --write` (through the model) | ✓ | ✓ | ✓ | ✓ | `db/studio.integration.test.ts: inserts, edits and deletes through the model` · `db/studio.integration.test.ts: writes through defineCollection` |
58
58
  | Same table from `defineModel` and `defineTable` | — | ✓ | ✓ | — | `db/table.integration.test.ts: defineModel and defineTable over the same table` |
59
+
60
+ ## HTTP contracts and WebSockets (since 0.11.0)
61
+
62
+ | Feature | Status | Evidence |
63
+ |---|---|---|
64
+ | OpenAPI 3.1 endpoint/offline generation, adapters, query/body contracts and optional paths | Implemented; opt-in | `openapi.test.ts: generates versioned paths, metadata, examples, JSON-schema parameters and request bodies from Zod` |
65
+ | File WS exports, middleware/auth/context, origin and payload limits, heartbeat and drain | Implemented; worker-local | `websocket.test.ts: shares real middleware, auth, decoded params and async request context, while HTTP coexists` |
66
+
67
+ No automatic auth-policy inference, message-schema validation, cross-worker broadcast bus or Swagger UI is included.
@@ -17,13 +17,15 @@ The user and admin portals are a set of **registry items**: ready-made models an
17
17
 
18
18
  ---
19
19
 
20
+ The route inventory includes extension points as well as implemented handlers. In `account-security`, password changes, refresh rotation and 2FA (TOTP/email OTP) work. Init asks which methods the app allows; users enroll one of them. Device-session list/revoke still return **501 Not Implemented** until you connect a device-session store. See [the 2FA flow](./authentication.md#two-factor-authentication-totp-or-email-otp). Other portal templates can also contain TODOs and need application logic before use.
21
+
20
22
  ## User portal
21
23
 
22
24
  | Item | Routes below |
23
25
  |---|---|
24
26
  | `user-profile` | Profile: `/user/profile` |
25
27
  | `forgot-password` | Auth: forgot / reset password |
26
- | `account-security` | Auth: refresh, change password, 2FA, sessions (+ `Session`) |
28
+ | `account-security` | Auth: refresh, change password, TOTP/email OTP; 501 device-session extension points (+ `Session` model) |
27
29
  | `email-verification` | Auth: verify email |
28
30
  | `account-settings` | Profile: avatar, settings, account, dashboard, activity |
29
31
  | `notifications` | Notifications (+ `Notification`) |
@@ -106,3 +106,20 @@ Unhandled errors are logged at `error` with the request ID and full stack (`err`
106
106
  ## Shipping logs
107
107
 
108
108
  JSON lines on stdout is what log collectors (Datadog, Loki, CloudWatch, Vector) expect — no transport configuration needed. For custom pino transports, set `pretty: false` and pipe stdout.
109
+
110
+ ## Query metrics
111
+
112
+ Opt in with `logging: { queries: { metrics: true } }`, or `{ metrics: { maxEntries: 500 } }`. The default limit when enabled is 1000 distinct model/operation pairs per worker process; zero disables metrics. Logging and slow/N+1 options remain independent.
113
+
114
+ ```ts
115
+ import { getQueryMetrics, resetQueryMetrics } from 'express-file-cluster';
116
+
117
+ const snapshot = getQueryMetrics();
118
+ // { enabled, since, dropped, entries: [{ model, op, calls, errors, statements,
119
+ // totalMs, minMs, maxMs, meanMs, slow }] }
120
+ resetQueryMetrics(); // optional: start a fresh window without disabling collection
121
+ ```
122
+
123
+ Snapshots are detached from internal state and contain no SQL, parameter values, error details or request IDs. Each entry aggregates completed calls, failures, inclusive statement counts and durations in milliseconds. Nested model calls retain their own entries; their statements also count toward the outer operation, so summing entries is not a global database statement total. `slow` counts calls at or above `slowMs`.
124
+
125
+ When the entry limit is reached, existing pairs keep updating; observations for new pairs increment `dropped`. Reset/reconfiguration clears entries, dropped counts and the `since` timestamp. Metrics are off by default. These are per-process counters, not a cluster-wide service or an OpenTelemetry exporter; collect from each worker/instance separately and secure any diagnostic endpoint you add.
@@ -117,7 +117,9 @@ efc db pull --out pulled # somewhere else, to compare
117
117
  - **Indexes:** unique, plain, compound and text indexes.
118
118
  - **Relations:** foreign keys become `ref`s with `onDelete`. A column like `authorId` becomes an `author` field that keeps the `authorId` column. EFC join tables become many-to-many arrays, and every target model gets back-`relations`.
119
119
 
120
- A schema EFC created pulls back to models that sync finds nothing to change in. For a schema EFC didn't create, anything that has no EFC equivalent is noted at the top of the file: expression or partial indexes, other CHECKs, composite keys, and other defaults. Existing files are kept unless you pass `--force`.
120
+ A schema EFC created pulls back to models that sync finds nothing to change in. For a schema EFC didn't create, anything that has no EFC equivalent is noted at the top of the file: expression or partial indexes, other CHECKs, composite keys, and other defaults.
121
+
122
+ Models already in the output directory keep their names: a table one of them maps (`AuditLog` → `auditlogs`) is pulled under that name, so refs to it name it too, and it's never written to a second file. Existing files are kept unless you pass `--force`, which refreshes a model in its own `<Model>.ts` but never overwrites a model defined in another file, or a file whose name differs only in case (the same file on macOS and Windows).
121
123
 
122
124
  ## Pulling an existing database (MongoDB)
123
125
 
@@ -132,7 +134,7 @@ MongoDB has no schema to read, so `pull` samples each collection (`$sample`) and
132
134
  - **Required:** only when every sampled document had a non-null value. A field with mixed types (or only nulls) becomes `{ type: 'object' }` (any value) with a note.
133
135
  - **Refs:** an `objectId` field gets `ref` when its name matches another collection (`owner`, `ownerId` → `Owner`) or when every sampled id exists in exactly one other collection; otherwise a note asks you to add it.
134
136
  - **Indexes:** single-field unique, plain, `text`, `2dsphere` and `hashed` indexes go on the field; compound, partial and TTL indexes into `indexes`.
135
- - **Names and timestamps:** a model per collection (`audit_log` → `AuditLog`, with `collection: 'audit_log'` when mongoose wouldn't pick that name); `createdAt`/`updatedAt` dates map to the default `timestamps`, otherwise `timestamps: false`.
137
+ - **Names and timestamps:** a model per collection (`audit_log` → `AuditLog`, with `collection: 'audit_log'` when mongoose wouldn't pick that name); `createdAt`/`updatedAt` dates map to the default `timestamps`, otherwise `timestamps: false`. Existing models in the output directory keep their names here too, as for PostgreSQL.
136
138
 
137
139
  `_id` and `__v` are left to defineCollection. Read the generated files before using them: a sample shows what the data *has*, not what it must have.
138
140
 
@@ -0,0 +1,57 @@
1
+ # OpenAPI generation (since 0.11.0)
2
+
3
+ Enable an OpenAPI 3.1 JSON document for your real HTTP routes:
4
+
5
+ ```ts
6
+ ignite({
7
+ ...config,
8
+ openapi: {
9
+ path: '/openapi.json',
10
+ info: { title: 'My API', version: '1.0.0' },
11
+ },
12
+ });
13
+ ```
14
+
15
+ `openapi: true` uses `/openapi.json` and the project's package name/version. It is off by default. Global middleware applies to the document endpoint too. Its URL is reserved before API routing; a conflicting GET or HEAD route fails startup, including hidden routes, dynamic matches, case variants and trailing slashes. Import the JSON into an OpenAPI viewer or client generator.
16
+
17
+ The generator reads HTTP method exports, `meta`, and each method's request `schema`. Existing validation behavior stays the same. Validators that implement [Standard JSON Schema](https://standardschema.dev/json-schema) convert automatically using their input representation (including recent Zod 4 versions). A Standard Schema validator without JSON Schema support needs the `schemaToJSONSchema(validator)` adapter; enabling OpenAPI without one reports which route/location could not be converted. The adapter may be async. Runtime validation does not require JSON Schema support when OpenAPI is off.
18
+
19
+ ```ts
20
+ // src/api/users/[id].ts
21
+ import { z } from 'zod';
22
+
23
+ export const schema = {
24
+ GET: { params: z.object({ id: z.string().uuid() }) },
25
+ };
26
+ export const meta = {
27
+ GET: {
28
+ summary: 'Get a user',
29
+ tags: ['users'],
30
+ response: { status: 200, body: { id: 'example-id', name: 'Jane' } },
31
+ },
32
+ };
33
+ export const GET = async (req, res) => {
34
+ res.json({ id: req.params.id, name: 'Jane' });
35
+ };
36
+ ```
37
+
38
+ Body schemas become JSON request bodies; object properties in query/params schemas become parameters. Named object schemas behind local `$ref` are resolved for parameter fields. Object unions/intersections (`anyOf`, `oneOf`, `allOf`) retain their fields; a union field is required only when every branch requires it. The operation’s `x-efc-query-schema` references the complete query schema, preserving constraints between fields that individual OpenAPI parameters cannot express. Non-object parameter schemas fail generation with the route/location; supply explicit `meta.METHOD.openapi.parameters` to document a custom representation. Object query fields use `style: deepObject` and `explode: true`, matching Express bracket syntax such as `?filter[name]=Alice`. Nested `$defs` and local JSON Schema pointers are rebased into components; explicit `$id` resource scopes keep their local-reference semantics. Example request headers/query/body and response status/body come from `meta`. A request-validation 400 response is documented. Response schemas, alternative content types and authorization requirements can be supplied explicitly with `meta.METHOD.openapi` (an OpenAPI Operation Object). Auth middleware is not inspected to infer security policy.
39
+
40
+ ```ts
41
+ // In ignite options:
42
+ openapi: {
43
+ components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer' } } },
44
+ }
45
+ // In a route:
46
+ export const meta = {
47
+ GET: { openapi: { security: [{ bearerAuth: [] }] } },
48
+ };
49
+ ```
50
+
51
+ `meta.GET.openapi.hidden: true` omits an operation. `summary`, `tags`, `description` and `operationId` are also supported directly in `meta.GET`. Explicit IDs must be unique; optional URL expansions get an index suffix. The document includes `basePath`. Optional URL segments expand into separate paths so every documented path parameter is required, as [OpenAPI requires](https://spec.openapis.org/oas/v3.1.0). Equivalent optional expansions use Express’s greedy binding (`[[first]]/[[second]]` with one segment binds `first`); other routes with equivalent templates but different parameter names fail generation rather than emitting an invalid document. Catch-all paths carry `x-efc-catch-all: true`: their slash-separated URL semantics need client-specific handling. WebSocket-only routes do not appear as HTTP operations.
52
+
53
+ For offline use, call `await generateOpenAPI('/absolute/path/to/src/api', { basePath, ...options })`, then write the returned object as JSON. This scans and imports route modules but does not listen, execute handlers or boot services; use the same TS loader/build output as the app, and keep service startup out of route module top-level code. Advanced callers can pass loaded `MountedRoute[]` directly instead. Plain `scanDir()` entries do not contain loaded HTTP exports/schemas. The `/testing` helper accepts the same `openapi` option for document tests.
54
+
55
+ Array query fields use bracketed wire names (`tags[]`) with `style: form` and `explode: true`, so one item and repeated items both reach Express as arrays. For example, `?tags[]=one&tags[]=two` becomes `req.query.tags`. An empty array has no entries to serialize; use an optional query field when omission is allowed. External field `$ref` values are preserved without network requests; provide a local `type` hint or explicit operation parameters if their object/array serialization cannot be inferred. Root parameter objects still need an inspectable local shape or explicit parameters.
56
+
57
+ Request-body requiredness follows whether the converted JSON Schema accepts the empty object Express supplies for a missing body. Required properties keep the body mandatory; optional object bodies allow omission. Local references and logical schema combinations are considered without executing application validators. Unknown external/dynamic body references remain required conservatively. Use `meta.METHOD.openapi.requestBody` to override inference, especially when middleware changes the body or validation uses custom rules. A body example alone does not make a body required.
@@ -0,0 +1,31 @@
1
+ # Testing file-based routes
2
+
3
+ `createTestApp()` from `express-file-cluster/testing` mounts your real route files on an Express app. Use it with supertest or another HTTP test harness. It shares the production HTTP middleware, router and error handler with `ignite()`, including JSON/form/cookie parsing, request context, validation, catch-all decoding and 405 handling.
4
+
5
+ ```ts
6
+ import { createTestApp } from 'express-file-cluster/testing';
7
+ import request from 'supertest';
8
+ import path from 'node:path';
9
+
10
+ const app = await createTestApp({
11
+ apiDir: path.resolve('src/api'),
12
+ auth: { secret: 'test-only-secret', strategy: 'bearer' },
13
+ });
14
+
15
+ const response = await request(app).get('/v1/api/health');
16
+ expect(response.status).toBe(200);
17
+ ```
18
+
19
+ Install the test harness in your app (`npm i -D supertest @types/supertest`). Your test runner must be able to import the route files: Configure the runner/loader to transform dynamically imported TypeScript routes when needed; a plain Node process can point at built JavaScript or use a TypeScript loader.
20
+
21
+ `apiDir` is required and must be an existing directory. It is specific to this helper; `ignite()` still discovers `src/api` by convention and has no `apiDir` option. Creating multiple apps does not change the working directory. Each app has its own router and middleware stack.
22
+
23
+ The helper returns an Express app without calling `listen()`, forking workers, scanning tasks, initializing database/cache/queue services, or adding signal handlers. It disables CORS and logging for tests and omits the development dashboard. Supertest can open its own temporary HTTP listener when making a request. For database and queue tests, configure real service fixtures separately, or use `ignite()` to exercise the complete boot lifecycle. The helper does not provide model mocks or an `enqueue()` implementation.
24
+
25
+ Authentication and logging are process-wide in EFC. The helper disables the process logger and configures auth when `auth` is supplied; use one auth configuration per test process, and isolate suites that require different secrets/strategies. Calling the helper without `auth` does not reset an existing auth configuration. Imported route modules follow normal module caching. Global model/cache/task state is not reset between apps.
26
+
27
+ See the [API reference](../api-reference/testing.md) for all options.
28
+
29
+ The CommonJS `/testing` entry delegates to the ESM helper using native `import()`, so dynamically imported ESM routes share its authentication and request context. The Node/runner must support the route files' module format.
30
+
31
+ The ESM and CommonJS builds share process-wide auth configuration, request AsyncLocalStorage and cache state. CommonJS `requireAuth` global middleware therefore sees helper auth options, preserves `getCurrentUser()` across awaits into ESM routes, and observes the same revocations. Model/queue fixtures are still configured separately.
@@ -93,3 +93,5 @@ So authentication in `middlewares` still responds 401/403 before any 400 — una
93
93
  ## Model-level validation is separate
94
94
 
95
95
  `schema` validates the HTTP request. `defineModel` validates what you write to the database (types, `required`, `enum`, `min`/`max`, `match`, custom `validate`) and throws a `ModelValidationError` — also a 400 with `issues`. Use both: request schemas for the API contract, model rules for data integrity. See [Database](./database.md).
96
+
97
+ Since 0.11.0: `schema.WS` validates WebSocket handshake params/query through the same pipeline, before upgrade; message validation belongs in the handler. Opt-in OpenAPI conversion uses a separate Standard JSON Schema input protocol or an explicit adapter; Standard Schema validation alone does not guarantee JSON Schema conversion. See [OpenAPI](./openapi.md).
@@ -0,0 +1,60 @@
1
+ # File-based WebSockets (since 0.11.0)
2
+
3
+ Export `WS` from a route file. `ignite()` serves its upgrade on the same HTTP server and `basePath` as HTTP routes.
4
+
5
+ ```ts
6
+ // src/api/chat/[room].ts
7
+ import type { WebSocketHandler } from 'express-file-cluster';
8
+ import { requireAuth, getCurrentUser } from 'express-file-cluster/auth';
9
+
10
+ export const middlewares = [requireAuth];
11
+ export const WS: WebSocketHandler = (socket, req) => {
12
+ socket.on('message', (data, isBinary) => {
13
+ const user = getCurrentUser();
14
+ socket.send(JSON.stringify({ room: req.params.room, userId: user?.id, text: data.toString(), isBinary }));
15
+ });
16
+ };
17
+ ```
18
+
19
+ Connect to `ws://localhost:3000/v1/api/chat/general` (use `wss://` behind TLS). `WS` receives a [ws WebSocket](https://github.com/websockets/ws/blob/master/doc/ws.md) and the Express request. An HTTP `GET`/`POST` export can coexist in the same file. HTTP clients do not invoke `WS`, and upgrading an HTTP-only or unknown route returns 404.
20
+
21
+ Middleware response headers (including cookies and request IDs) are included in successful upgrades; protocol framing/negotiation headers remain owned by the WebSocket server. Global and file middleware, cookie parsing, request context and named/optional/catch-all params apply before upgrade. `requireAuth` checks cookies/bearer tokens and revocation during the handshake; auth failure is an HTTP 401/403/503 rather than a WebSocket connection. Use method-keyed `schema.WS` for query/params handshake validation. It does not validate message frames. `getCurrentUser()` and the request logger remain available in message/close/error callbacks and across awaits. Handle errors inside application event listeners; EFC catches errors thrown/rejected by the exported connection handler and closes with 1011.
22
+
23
+ Browser clients use cookies; the browser WebSocket API cannot set arbitrary Authorization headers. Authorization and session changes during an already established connection are application policy: recheck sensitive message operations or close affected sockets when sessions end. Handshake authentication is not repeated for every frame.
24
+
25
+ ```ts
26
+ ignite({
27
+ ...config,
28
+ websocket: {
29
+ origins: ['https://app.example.com'],
30
+ maxPayload: 1024 * 1024,
31
+ heartbeatIntervalMs: 30_000,
32
+ handshakeTimeoutMs: 10_000,
33
+ },
34
+ });
35
+ ```
36
+
37
+ Upgrades are enabled when a `WS` export exists. `websocket: false` disables them. Browser origins default to same-origin using Express's protocol/host; configure `trustProxy` correctly behind a proxy. An explicit origin list replaces this default. Opaque/malformed/cross-origin handshakes are rejected with 403. Clients without an Origin header (such as trusted Node clients) are allowed and still pass auth middleware.
38
+
39
+ `maxPayload` accepts integers from 1 through 2147483647 bytes; larger values fail configuration instead of overflowing the receiver’s limit. Both timer options also have a 2147483647 ms ceiling. Inbound messages default to a 1 MiB limit, compression is disabled, and heartbeat pings terminate unresponsive peers. Set `heartbeatIntervalMs: 0` to disable heartbeat. Pending middleware has a 10-second upgrade deadline; the HTTP `requestTimeout` may reject it earlier. Once upgraded, HTTP request timers are cleared.
40
+
41
+ Pipelined upgrades received while an earlier HTTP response still owns the connection close that connection safely.
42
+
43
+ `server.close()` immediately destroys pending handshake sockets, closes established sockets with code 1001 and terminates unresponsive peers after a drain interval. `gracefulShutdown(server)` drains WebSockets with HTTP/task shutdown, including signals forwarded to workers. Every cluster worker owns its connections; broadcasts through a server's `clients` set stay within that worker. Use application pub/sub for cross-worker/instance messages.
44
+
45
+ ## Testing and custom HTTP servers
46
+
47
+ ```ts
48
+ import http from 'node:http';
49
+ import { attachWebSockets } from 'express-file-cluster';
50
+ import { createTestApp } from 'express-file-cluster/testing';
51
+
52
+ const app = await createTestApp({ apiDir: '/absolute/path/to/api' });
53
+ const server = http.createServer(app);
54
+ const sockets = attachWebSockets(server, app);
55
+ server.listen(0);
56
+ // Connect a ws client; sockets.clients contains this server's connections.
57
+ // Close server in cleanup; upgraded sockets are drained too.
58
+ ```
59
+
60
+ The test helper itself still does not start a listener. `attachWebSockets` rejects duplicate attachment. Each server has its own limits, connections and heartbeat; app auth/cache state follows the process-wide isolation rules in the testing guide.
@@ -2,7 +2,7 @@
2
2
 
3
3
  **express-file-cluster (EFC)** is an opinionated backend framework built on Express. It removes routing ceremony, saturates every CPU core automatically, and ships a production-grade background-task subsystem — all from a single `ignite()` call.
4
4
 
5
- > **Status: v0.10.0 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, migrations (written for you from model changes: `efc db generate`, plus `efc db pull` and `efc import-prisma`), and the `efc add` feature registry (auth, admin, billing… copied into your app as source you own) are all implemented.
5
+ > **Status: v0.11.0 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, migrations (written for you from model changes: `efc db generate`, plus `efc db pull` and `efc import-prisma`), and the `efc add` feature registry (auth, admin, billing… copied into your app as source you own) are all implemented.
6
6
 
7
7
  ---
8
8
 
@@ -47,6 +47,9 @@
47
47
  | [Migrations & Seeds](./guides/migrations.md) | `efc db generate / migrate / rollback / pull / seed / studio`, drift checks |
48
48
  | [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
49
49
  | [Coming from mongoose](./guides/coming-from-mongoose.md) | `defineCollection` for mongoose users: schema and query mapping |
50
+ | [Testing](./guides/testing.md) | `createTestApp` for real file-based routes without service boot |
51
+ | [OpenAPI (since 0.11.0)](./guides/openapi.md) | Opt-in OpenAPI JSON from route metadata and request schemas |
52
+ | [WebSockets (since 0.11.0)](./guides/websockets.md) | WS file exports, middleware/auth, limits and shutdown |
50
53
  | [Validation](./guides/validation.md) | Route `schema` exports with zod, valibot, arktype |
51
54
  | [Logging](./guides/logging.md) | pino, request IDs, `getLogger()` |
52
55
  | [Caching & Sessions](./guides/caching.md) | `cache`, `cacheResponse`, revoking JWT sessions |