@dokebi/web 0.1.2 → 0.4.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.
- package/AI.md +191 -45
- package/README.md +59 -33
- package/dist/compilers.d.ts +9 -0
- package/dist/compilers.js +58 -0
- package/dist/dependency.d.ts +4 -0
- package/dist/dependency.js +14 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.js +106 -0
- package/dist/extension.d.ts +95 -0
- package/dist/extension.js +52 -0
- package/dist/index.d.ts +50 -8
- package/dist/index.js +766 -285
- package/dist/install.d.ts +25 -0
- package/dist/install.js +23 -0
- package/dist/options.d.ts +19 -0
- package/dist/options.js +92 -0
- package/dist/points.d.ts +53 -0
- package/dist/points.js +5 -0
- package/dist/responses.d.ts +80 -0
- package/dist/responses.js +246 -0
- package/dist/seal.d.ts +83 -0
- package/dist/seal.js +273 -0
- package/options.schema.json +68 -14
- package/package.json +43 -13
- package/templates/extension.ts +14 -0
package/AI.md
CHANGED
|
@@ -1,80 +1,226 @@
|
|
|
1
|
-
# AI
|
|
1
|
+
# AI guide — @dokebi/web 0.4.0
|
|
2
2
|
|
|
3
|
-
Fastify 5 HTTP
|
|
3
|
+
A plugin through which the app owns a Fastify 5 HTTP server. It blocks requests before the app is ready and while it shuts down (503), serves health routes, drains requests in progress, swaps cluster workers without downtime and handles trusted proxies. Routers, controllers, views and DBs are not required. Node >=24.0.0, core ^0.4.0. Details are in the [README](README.md).
|
|
4
4
|
|
|
5
|
-
## 1.
|
|
5
|
+
## 1. Install and configure
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
npx dokebi add @dokebi/web # src/infra/web/
|
|
8
|
+
npx dokebi add @dokebi/web # src/infra/web/extension.ts (the requires list + an empty AppWeb extension)
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
> `npx dokebi` is the @dokebi/cli installed in the project (`dokebi init` adds it to devDependencies). The npm package `dokebi` is not this CLI, so never use `npx -y dokebi`. Without an installed CLI use `npx -y @dokebi/cli …`.
|
|
12
|
+
|
|
11
13
|
```yaml
|
|
12
14
|
dokebi-web:
|
|
13
|
-
host: 127.0.0.1 #
|
|
14
|
-
port: 3000 #
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
healthRoutes: { live: /health/live, ready: /health/ready } # false
|
|
18
|
-
trustProxy: [127.0.0.1, "::1"] #
|
|
15
|
+
host: 127.0.0.1 # default; 0.0.0.0 to accept outside traffic (a front proxy is recommended)
|
|
16
|
+
port: 3000 # default 0 (an ephemeral port), 0..65535
|
|
17
|
+
maxBodyBytes: 1048576 # 1 B..64 MiB (named bodyLimit before 0.4.0)
|
|
18
|
+
requestTimeoutMs: 30000 # limit for receiving a request, not for running the work (named requestTimeout before 0.4.0)
|
|
19
|
+
healthRoutes: { live: /health/live, ready: /health/ready } # false registers none
|
|
20
|
+
trustProxy: [127.0.0.1, "::1"] # exact IPs only, up to 64
|
|
21
|
+
sealDriftMs: 60000 # seal hosts (D-0062): allowed ts drift of sealed bodies
|
|
22
|
+
sealExclude: [/webhooks] # path prefixes that stay plain on seal hosts
|
|
23
|
+
formBody: true # HTML forms (application/x-www-form-urlencoded) into request.body; default false
|
|
24
|
+
formMaxFields: 1000 # field limit per form, 1..10000; above it 413 FORM_BODY_TOO_MANY_FIELDS
|
|
25
|
+
developmentErrors: true # outside production (NODE_ENV=production) error bodies also carry fix and details; false always answers like production
|
|
19
26
|
```
|
|
20
27
|
|
|
21
|
-
|
|
28
|
+
| Key | Type | Default | Description |
|
|
29
|
+
|---|---|---|---|
|
|
30
|
+
| `host` | string | `127.0.0.1` | listen address |
|
|
31
|
+
| `port` | integer | 0 | 0..65535; 0 picks an ephemeral port |
|
|
32
|
+
| `maxBodyBytes` | integer | 1048576 | request body limit, 1 B..64 MiB |
|
|
33
|
+
| `bodyLimit` | integer | — | deprecated name of `maxBodyBytes` (D-0071): warns `OPTION_DEPRECATED`; setting both is `INVALID_OPTIONS` |
|
|
34
|
+
| `requestTimeoutMs` | integer | 30000 | time to receive a request, 1..2147483647 ms; not a limit on the work |
|
|
35
|
+
| `requestTimeout` | integer | — | deprecated name of `requestTimeoutMs` (D-0071) |
|
|
36
|
+
| `healthRoutes` | `{ live?, ready? }` or `false` | `{ live: /health/live, ready: /health/ready }` | missing keys use the default path; paths start with `/`, have no `?`, `#` or spaces, and differ; `false` registers neither |
|
|
37
|
+
| `trustProxy` | string[] | `[]` | exact IPv4/IPv6 proxy addresses (up to 64) whose `X-Forwarded-*` headers are trusted |
|
|
38
|
+
| `sealDriftMs` | integer | 60000 | allowed timestamp drift of sealed bodies, 1000..600000; nonces are kept twice as long |
|
|
39
|
+
| `sealExclude` | string[] | `[]` | path prefixes (with a `/` boundary) that stay plain on seal hosts, up to 64 |
|
|
40
|
+
| `formBody` | boolean | false | parse `application/x-www-form-urlencoded` bodies |
|
|
41
|
+
| `formMaxFields` | integer | 1000 | field limit per form, 1..10000 |
|
|
42
|
+
| `developmentErrors` | boolean | true | outside production, error bodies carry `fix` and `details`; false answers like production everywhere |
|
|
22
43
|
|
|
23
|
-
|
|
44
|
+
**To accept HTML forms set `formBody: true`** (off by default, D-0068). While off, a form request gets 415 `{ error: 'FORM_BODY_DISABLED', fix }` before the handler, and the `fix` and a warn log (`HTTP form body refused`, `code: FORM_BODY_DISABLED`, once per route every 10 seconds) name this option. When on, the body is decoded with `node:querystring` into `request.body`: an object without a prototype, repeated names become arrays, `+` and `%XX` are decoded, and `maxBodyBytes` applies. It is off by default because a form POST is a request other sites can send without a preflight (a CORS simple request): cookie-authenticated apps keep the session cookie `SameSite=Lax` (the @dokebi/session default) or `Strict`, or check a CSRF token. Seal hosts still refuse forms with 415 `SEAL_REQUIRED` when it is on (§3.1).
|
|
24
45
|
|
|
25
|
-
|
|
46
|
+
`dokebi verify` starts the app with `DOKEBI_VERIFY_TOKEN` (random), and only when that variable is set does this plugin add the header `x-dokebi-verify: <token>` to every response. verify counts only answers with the right header, so another app on the same port is never mistaken for yours (D-0065 §11). Without the variable (normal runs and production) the hook does not exist. A malformed value is ignored with warn `VERIFY_TOKEN_INVALID`.
|
|
26
47
|
|
|
27
|
-
|
|
48
|
+
`dokebi start` gives the app a random per-start `DOKEBI_INSTANCE_TOKEN` (D-0073). While that variable is set, a request carrying a challenge in the header `x-dokebi-instance` (16–128 characters of `A-Za-z0-9_-`) is answered at once with `204` and `x-dokebi-instance: <base64url HMAC-SHA256(token, challenge)>`; no route or app code runs, and the token itself never goes on the wire. Requests without that header are served as usual. `dokebi stop` and `status` use it to prove a recorded pid is this app where `ps` is blocked. A malformed token is ignored with warn `INSTANCE_TOKEN_INVALID`; without the variable no hook exists.
|
|
49
|
+
|
|
50
|
+
Fastify construction options such as HTTPS, HTTP/2, `serverFactory` or the query-string parser are not dokebi.yaml options; give them through the extension hook `fastifyOptions` (§8). Usually TLS ends at a front proxy.
|
|
51
|
+
|
|
52
|
+
## 2. Usage
|
|
53
|
+
|
|
54
|
+
Usually @dokebi/app, module and router build routes on top of web. To use it directly:
|
|
55
|
+
|
|
56
|
+
```ts snippet
|
|
28
57
|
import cors from '@fastify/cors';
|
|
29
58
|
import { dependency as web } from '@dokebi/web';
|
|
30
|
-
// dependencies/requires
|
|
59
|
+
// put web into dependencies/requires, then in setup:
|
|
31
60
|
const http = context.getDependency(web);
|
|
32
61
|
http.route({ method: 'GET', url: '/ping', handler: async () => ({ ok: true }) });
|
|
33
|
-
http.register(cors, { origin: ['https://a.com'] }); // Fastify
|
|
62
|
+
http.register(cors, { origin: ['https://a.com'] }); // Fastify plugin (options required; {} when none)
|
|
34
63
|
http.route({ method: 'POST', url: '/import', handler: async (request, reply) => {
|
|
35
|
-
void http.track(() => importLater(request.body)); //
|
|
64
|
+
void http.track(() => importLater(request.body)); // work that outlives the response joins the drain via track
|
|
36
65
|
return reply.code(202).send({ accepted: true });
|
|
37
66
|
}});
|
|
38
67
|
```
|
|
39
68
|
|
|
40
|
-
| API |
|
|
69
|
+
| API | Meaning |
|
|
41
70
|
|---|---|
|
|
42
|
-
| `route(options)` | Fastify RouteOptions(
|
|
43
|
-
| `register(plugin, options)` | Fastify async
|
|
44
|
-
| `constraint(strategy)` |
|
|
45
|
-
| `track(() => work)` |
|
|
46
|
-
| `requestHost(request)` |
|
|
47
|
-
| `
|
|
71
|
+
| `route(options)` | Fastify RouteOptions (types and schema kept). Setup only; afterwards `FROZEN` |
|
|
72
|
+
| `register(plugin, options)` | a Fastify async or callback plugin (scope, decorators and hooks kept). Setup only |
|
|
73
|
+
| `constraint(strategy)` | adds a route constraint strategy (`dokebiApp` of @dokebi/app). Setup only, before the routes that use it |
|
|
74
|
+
| `track(() => work)` | makes drain wait for work whose lifetime differs from the HTTP response |
|
|
75
|
+
| `requestHost(request)` | the request host under the trusted-proxy rules (lower case, port kept) |
|
|
76
|
+
| `route({ ..., seal })` | `seal: false` stays plain even on a seal host (webhooks, server to server); `true` or a function seals on any host (D-0062) |
|
|
77
|
+
| `sealCodec(provider)` · `sealRequests(predicate)` · `sealOf(request)` · `sealing` | the HTTP seal slot (D-0062). @dokebi/seal provides the codec and @dokebi/app registers the decision; you rarely call them yourself |
|
|
78
|
+
| `errorResponder(responder)` | adds an error responder (D-0074, §6): asked before web writes an error answer, the last added first; `(response) => boolean \| Promise<boolean>`, true when it sent the answer itself. @dokebi/app (error views) and template-inertia (validation redirect, error page) use it. Setup only |
|
|
79
|
+
| `address` | the real address after listen (undefined before). In a cluster worker it is set after core `ready`, so other plugins read it in `ready`. A process with `runtime.serving` false (a migration tool and so on) never listens, so it stays undefined |
|
|
80
|
+
|
|
81
|
+
- `dependency` of `@dokebi/web/dependency` (also exported from the root) is the provider descriptor for plugins and app code that always install web (D-0063 §6; a small module that does not load Fastify).
|
|
82
|
+
- `@dokebi/web/points` exports the contribution points `viewEngines` (`dokebi-web:view-engine`) and `realtime` (`dokebi-web:realtime`) and their value types (`WebViewEngine`, `WebRealtimeTransport`, `WebRealtimeScope`): template-ejs and template-inertia contribute view engines, websocket and sse contribute realtime transports, and @dokebi/app collects them.
|
|
83
|
+
- web also contributes Fastify `inject` to the `inject` slot of `@dokebi/core/testing` (`dokebi-testing:inject`), so `await inject('/health/live')` runs without a socket.
|
|
84
|
+
- Other exports: `options` (the `defineOptions` declaration) and `WebOptions`, `WebError`, `validationError` and `WebValidationError` (§6), `errorFormat` and the responder types (`WebErrorResponder`, `WebErrorResponse`, `WebErrorFormat`, `WebFieldError`), `WebExtension` and its types, `SEALED_PATH_HEADER` (`x-dokebi-sealed-path`) and the seal types.
|
|
85
|
+
|
|
86
|
+
## 3. Start and request blocking
|
|
87
|
+
|
|
88
|
+
- web listens in its start, after every setup. **A cluster worker (`context.runtime.role === 'worker'`) listens in the core `ready` hook** (D-0034), so only workers whose whole app is ready get connections. With `runtime.serving` false it never listens (D-0063 §4).
|
|
89
|
+
- Until the app has started and health is ready, business requests get 503 `{ error: 'SERVICE_UNAVAILABLE', reason }` (reason `STARTING`, `NOT_READY` or `DRAINING`); a browser page (§6 format rule) gets the same as a small HTML page. The status, headers (`retry-after` and so on) and body can be changed with the extension hook `unavailable` (§8); a hook body of the error shape (`{ error, … }`) is still drawn as a page for a browser. The request is refused either way, so drain stays correct. Error responders are not asked for these refusals (the app is starting or draining).
|
|
90
|
+
- Health routes: live 200/503, ready 200/503 (app state and the health checks). `dokebi-health` is an optional dependency: when registered it is connected automatically, otherwise only the app state counts. Health is per app, not a cluster-wide aggregate.
|
|
91
|
+
|
|
92
|
+
### 3.1 HTTP on seal hosts (D-0062)
|
|
93
|
+
|
|
94
|
+
With @dokebi/seal and @dokebi/app, requests to a seal host behave like this: JSON responses (4xx included) go out as an `E:<ts>:<b64>` body with `Content-Type: application/vnd.dokebi-seal` and `x-dokebi-sealed-path`, and request bodies must be sealed. Plain JSON, urlencoded and text bodies get **415 `SEAL_REQUIRED`** before the handler (multipart uploads pass). Browsers use `sealedFetch` and `sealInertia` of `@dokebi/seal/http`. Routes that cannot be sealed, such as webhooks, opt out with `seal: false` or `sealExclude`. HTML responses (EJS) stay as they are. Asking for sealing without a provider fails the start with `SEAL_PROVIDER_MISSING`. Sealing is obfuscation and replay protection; confidentiality comes from TLS.
|
|
95
|
+
|
|
96
|
+
## 4. Shutdown (drain)
|
|
48
97
|
|
|
49
|
-
|
|
98
|
+
- Single process: new requests get 503, and drain waits for responses in progress, handler Promises (including the part that continues after the response was sent), request hooks, after-response hooks (`onResponse`, `onError`, `onTimeout`, `onRequestAbort`) and `track` work. When a client disconnects first, drain still waits for that request's hooks and handler (D-0023). Requests are counted without a Promise each (D-0068). When the core drain deadline (default 20 s) passes or on `stop({ force: true })`, remaining connections are cut and drain returns (core records `DRAIN_TIMEOUT`). After every drain succeeded, cleanup calls `Fastify.close` (onClose runs).
|
|
99
|
+
- Cluster worker (D-0036): the listen socket closes first so the primary sends new connections to other workers; requests on open keep-alive connections are served and then closed with `Connection: close`. The worker stays up at least 100 ms. A request sent at the moment an idle keep-alive connection closes can get `ECONNRESET` (inherent to HTTP); non-browser clients retry an idempotent request on a reused socket once.
|
|
50
100
|
|
|
51
|
-
|
|
52
|
-
- 앱 start 완료와 health ready 전에는 업무 요청에 503 `{ error: 'SERVICE_UNAVAILABLE', reason }`(reason: `STARTING`·`NOT_READY`·`DRAINING`).
|
|
53
|
-
- health 경로: live 200/503, ready 200/503(앱 상태와 health check). 앱마다 독립이고 cluster 전체 집계가 아니다.
|
|
101
|
+
## 5. Ownership rules (important)
|
|
54
102
|
|
|
55
|
-
|
|
103
|
+
- **Put every Dokebi resource that a Fastify `onClose` hook uses into `entry.requires`** (in a CLI project, `requires` of `src/infra/web/extension.ts`). Cleanup runs in reverse initialisation order, so web must depend on the resource for the resource to close after Fastify.close. Entries are plugin instances (converted with core `dependencyOf`) or `PluginDependency` descriptors. Putting a `dokebi-health` instance there makes it required instead of optional.
|
|
104
|
+
- Never close a borrowed DB pool or similar in a handler.
|
|
105
|
+
- For callback hooks the end is done or the end of the response; for async hooks it is the returned Promise. Do not mix async and done. Work that continues in raw streams, timers or outside events must be awaited with `track` or the owning plugin's drain.
|
|
106
|
+
- Calling `listen`/`close` directly, overwriting root hooks or bypassing the reserved `dokebiHealth` config are outside the contract.
|
|
56
107
|
|
|
57
|
-
|
|
58
|
-
- cluster 워커(D-0036): listen 소켓부터 닫아 primary가 새 연결을 다른 워커로 보내게 하고, 열린 keep-alive 연결의 요청은 처리한 뒤 `Connection: close`로 닫는다. 최소 100ms 살아 있는다. 쉬는 keep-alive가 닫히는 순간 보낸 요청은 `ECONNRESET`일 수 있다(HTTP 본질). 브라우저가 아닌 클라이언트는 재사용 소켓의 멱등 요청을 한 번 재시도한다.
|
|
108
|
+
## 6. Errors
|
|
59
109
|
|
|
60
|
-
|
|
110
|
+
**Response mapping (D-0063 §1).** Errors thrown by handlers and hooks are answered like this.
|
|
61
111
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
112
|
+
| Thrown | Status | Body |
|
|
113
|
+
|---|---|---|
|
|
114
|
+
| a Dokebi error (`DokebiError`, or that shape with a `plugin`) with `status` | that `status` | `{ error: code, message, hint?, data? }` |
|
|
115
|
+
| a Dokebi error without `status` | Fastify's 4xx `statusCode` if any, else 500 | the same |
|
|
116
|
+
| a refused route schema of the body or the query string (D-0074) | 422 | `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }` |
|
|
117
|
+
| `throw validationError({ name: 'Already taken' })` from a handler (D-0074) | 422 | the same shape (`fields`, `errors`) |
|
|
118
|
+
| an unknown route (D-0074) | 404 | `{ error: 'NOT_FOUND', message, hint }` |
|
|
119
|
+
| any other 4xx (malformed JSON, media type, size, a `params` or `headers` schema) | Fastify's value | `{ error: 'INVALID_REQUEST' }` (plus Fastify's `message` in development) |
|
|
120
|
+
| anything else (unknown errors, errno and so on) | 500 | `{ error: 'INTERNAL_SERVER_ERROR' }` |
|
|
66
121
|
|
|
67
|
-
|
|
122
|
+
- **Production** (`NODE_ENV=production` or `developmentErrors: false`) never carries `fix`, `details` or stacks, and a 5xx `message` becomes a generic sentence (`Internal Server Error`, `Service Unavailable` and so on). `code`, `hint`, `data`, `fields` and `errors` are sent in production too. **Development** also sends `fix` and `details` (when they fit in 16 KB of JSON).
|
|
123
|
+
- The body is a flat object extending the old `{ error: '<CODE>' }` shape (`error` is the code). Clients branch on `body.error`.
|
|
124
|
+
- The extension hook `errorBody` can change status and body (§8). In production web removes `fix`, `details` and `stack` whatever the hook returns.
|
|
68
125
|
|
|
69
|
-
|
|
126
|
+
**Validation errors (D-0074).** A field is the property path without `body/`: `name`, `address.city`, `items.0.name`; a missing property is named itself (`required` → `name`: `is required`); a query string field is `query.page`; a body that is wrong as a whole is `_body`. Fastify stops at the first failing rule (Ajv `allErrors: false`, its safe default), so a schema answer usually names one field. Refuse input in handler code the same way, so clients see one shape:
|
|
70
127
|
|
|
71
|
-
|
|
128
|
+
```ts snippet
|
|
129
|
+
import { validationError } from '@dokebi/web';
|
|
130
|
+
if (await users.exists(body.name)) throw validationError({ name: 'This name is taken' });
|
|
131
|
+
// or a list: validationError([{ field: 'name', message: '…' }], { message, hint, data })
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Do not answer validation with your own `reply.code(422).send(…)`: template-inertia only turns a `VALIDATION_FAILED` answer into the Inertia validation redirect. `fields` keeps every message in order; `errors` is the first message per field (the shape of Inertia `useForm().errors`).
|
|
135
|
+
|
|
136
|
+
**JSON or HTML (D-0074, `errorFormat(headers, sealed)`).** One rule for every error answer (thrown errors, refused schemas, unknown routes, 413/415 bodies, seal errors, the 503 refusals):
|
|
137
|
+
|
|
138
|
+
- **JSON** when any of: `X-Inertia` is present; `X-Requested-With: XMLHttpRequest`; `Authorization: Bearer …`; the request body is JSON (`Content-Type` `application/json` or `+json`: a script sent it); the request is sealed (D-0062: only sealed JSON leaves a seal host); `Accept` prefers JSON or is `*/*` (`fetch()`).
|
|
139
|
+
- **HTML** (a small page with the code, message, hint, the refused fields and, in development, `fix`) only otherwise and only when `Accept` prefers `text/html`: a browser navigation or an HTML form post.
|
|
140
|
+
|
|
141
|
+
| Client \ error | 404 route | 400 bad JSON | 413 | 415 form off | 422 schema | 422 `validationError` | 401/403 | 500 | 503 refused |
|
|
142
|
+
|---|---|---|---|---|---|---|---|---|---|
|
|
143
|
+
| browser navigation (GET, `Accept: text/html`) | HTML | – | – | – | HTML (query) | HTML | HTML | HTML | HTML |
|
|
144
|
+
| HTML form post (urlencoded, `formBody` on) | HTML | – | HTML | HTML | HTML | HTML | HTML | HTML | HTML |
|
|
145
|
+
| `fetch` with JSON | JSON | JSON | JSON | – | JSON | JSON | JSON | JSON | JSON |
|
|
146
|
+
| XHR (`X-Requested-With`) | JSON | JSON | JSON | JSON | JSON | JSON | JSON | JSON | JSON |
|
|
147
|
+
| Bearer API | JSON | – | – | – | JSON (query) | JSON | JSON | JSON | JSON |
|
|
148
|
+
| Inertia visit (GET, `X-Inertia`) | JSON | – | – | – | JSON | JSON | JSON | JSON | JSON |
|
|
149
|
+
| Inertia POST | JSON | JSON | JSON | – | JSON | JSON | JSON | JSON | JSON |
|
|
150
|
+
| sealed request (seal host) | JSON (sealed) | – | JSON (sealed) | 415 `SEAL_REQUIRED` JSON (plain) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) | JSON (sealed) |
|
|
151
|
+
|
|
152
|
+
(`–`: that client cannot send that request. The table is `tests/error-matrix.test.ts`.) With @dokebi/template-inertia an Inertia request refused with 422 goes back instead (303, `errors` in the session flash), and an app's error views or Inertia error page may draw the HTML answer: both through error responders.
|
|
72
153
|
|
|
73
|
-
|
|
154
|
+
**Error responders (D-0074).** `web.errorResponder((response) => …)` (setup only) is asked before web writes an error answer, the last added first. `response` is `{ request, reply, error, status, body, format, production, sealed }` with the final status and body (after `errorBody`, production-cut). Return true after sending the answer yourself (`reply.redirect`, a rendered view), false to pass. A responder that throws (or returns true without sending) is logged once per route and interval as `error` `Web error responder failed` (`code: WEB_ERROR_RESPONDER_FAILED`, `status`, `errorCode`, `error`) and web sends its own answer. @dokebi/app answers an app's hosts with its error views; template-inertia does the validation redirect and the error page. Responders are not asked for the 503 refusals.
|
|
155
|
+
|
|
156
|
+
<!-- docs-check: complete-error-codes WebErrorCode -->
|
|
157
|
+
`WebError` (`plugin: 'dokebi-web'`, always a `fix`; request errors also have `status` and `hint`):
|
|
158
|
+
|
|
159
|
+
| Code | When |
|
|
160
|
+
|---|---|
|
|
161
|
+
| `INVALID_ENTRY` | the entry module exports something other than `requires` and `default`, or exports the extension class under a name (the cause of `INVALID_PLUGIN_INPUT`) |
|
|
162
|
+
| `INVALID_ROUTE` | a route's `seal` is neither boolean nor function |
|
|
163
|
+
| `INVALID_HOOK` | an async Fastify hook takes the done argument |
|
|
164
|
+
| `INVALID_ARGUMENT` | `sealRequests` or `errorResponder` got something other than a function, or `validationError` got no field or a non-string message |
|
|
165
|
+
| `INVALID_EXTENSION_RESULT` | an extension hook returned the wrong shape (`fastifyOptions` fails setup; `errorBody` and `unavailable` fall back to the default answer plus error log `WEB_EXTENSION_FAILED`) |
|
|
166
|
+
| `FROZEN` | `route`, `register`, `constraint`, `errorResponder` or a seal setting after setup |
|
|
167
|
+
| `CLOSED` | `track` after close |
|
|
168
|
+
| `FORM_BODY_DISABLED` | 415, form bodies are off (`fix` says how to turn them on; warn log) |
|
|
169
|
+
| `FORM_BODY_TOO_MANY_FIELDS` | 413, `data.maxFields` |
|
|
170
|
+
| `SEAL_PROVIDER_MISSING` | start: sealing is wanted but there is no provider |
|
|
171
|
+
| `SEAL_PROVIDER_INVALID` | the provider has the wrong shape or was registered twice |
|
|
172
|
+
| `SEAL_REQUIRED` | 415, a plain body on a sealed request (answered in plain text) |
|
|
173
|
+
| `SEAL_BODY_REFUSED` | 400, a sealed body could not be opened (the reason is only in the warn log) |
|
|
174
|
+
| `SEAL_BODY_NOT_JSON` | 400, the opened body is not JSON |
|
|
175
|
+
| `SEAL_STREAM_UNSUPPORTED` | 500, JSON for a sealed request was sent as a stream (error log) |
|
|
176
|
+
| `VALIDATION_FAILED` | 422, a refused body or query string schema, or `validationError()`; `fields` and `errors` in the body |
|
|
177
|
+
| `NOT_FOUND` | 404, no route for the method and path |
|
|
178
|
+
|
|
179
|
+
Option errors are core `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS` with paths such as `trustProxy[0]` in `details.issues`). A 500 leaves the `error` log `HTTP request failed` (`code: WEB_REQUEST_FAILED`, `requestId`, `method`, `route` (the route pattern, no query), `status`, `errorCode`, `error` (name, full message, stack and `Caused by:` causes; only URL credentials are removed as `//***@`, cut above 16 KB)). The same route and error is logged once per 10 seconds and the count in between appears as `repeated` in the next record (D-0047). A 4xx is debug `HTTP request rejected` (`status`, `route`, the full `error` text, `errorCode`). If you register your own error handler, its security is your responsibility.
|
|
180
|
+
|
|
181
|
+
The info log `Web server listening` (`address`, `urls` (every bound address; `localhost` means 127.0.0.1 and ::1), `host`, `ms`) is what `dokebi start` reads to show the address. Debug logs (`DOKEBI_LOG_LEVEL=debug`): `Web server configured` (options, only the number of trustProxy entries, and `schemaCompilers`: `lazy` loads Fastify's default validation and serialization compilers when the first route with a schema appears — about 15 ms faster startup with the same behaviour, header schema names still case-insensitive; `extension` when the extension's `fastifyOptions` supplies a `schemaController`, D-0070), `Web routes frozen`, `Web drain started` (`pending`: requests, handlers, hooks and track work in progress at that moment), `Web worker stopped listening`, `Web drain cut connections`, `Web drain finished`, `Web server closed`; per request `HTTP request refused` (reason, method and path without the query; built only when debug is on), and when a client leaves before the response `HTTP client left before the response` and `HTTP request without client finished`.
|
|
182
|
+
|
|
183
|
+
## 7. Cautions
|
|
184
|
+
|
|
185
|
+
- Behind a proxy, list **only the proxy addresses** in `trustProxy`; never trust Host or X-Forwarded-* headers yourself, use `requestHost(request)`.
|
|
186
|
+
- Authentication, rate limiting, CORS and security headers are Fastify plugins the app chooses (none are built in).
|
|
187
|
+
- `requestTimeoutMs` is not a limit on the work. Send long work to job.
|
|
188
|
+
- Do not treat the end of a response or a client disconnect as the work being done.
|
|
189
|
+
|
|
190
|
+
## 8. Extension (D-0064 §9)
|
|
191
|
+
|
|
192
|
+
When the default export of `src/infra/web/extension.ts` (created by `dokebi add @dokebi/web`) extends `WebExtension`, only the overridden hooks are called. Left empty, it costs nothing per request. There are three hooks, all synchronous. No constructor parameters, and hooks do not call each other (`INVALID_EXTENSION`).
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
import {
|
|
196
|
+
type WebErrorAnswer,
|
|
197
|
+
type WebErrorContext,
|
|
198
|
+
WebExtension,
|
|
199
|
+
type WebFastifyOptions,
|
|
200
|
+
type WebUnavailableAnswer,
|
|
201
|
+
type WebUnavailableContext,
|
|
202
|
+
} from '@dokebi/web';
|
|
203
|
+
|
|
204
|
+
export const requires = [] as const;
|
|
205
|
+
|
|
206
|
+
export default class AppWeb extends WebExtension {
|
|
207
|
+
// Fastify construction options (https, http2, serverFactory, routerOptions and so on). return503OnClosing and forceCloseConnections cannot change.
|
|
208
|
+
protected override fastifyOptions(defaults: WebFastifyOptions): WebFastifyOptions {
|
|
209
|
+
return { ...defaults, requestIdHeader: 'x-request-id' };
|
|
210
|
+
}
|
|
211
|
+
// Status and body of error responses (in production web removes fix, details and stack).
|
|
212
|
+
protected override errorBody(error: unknown, context: WebErrorContext): WebErrorAnswer {
|
|
213
|
+
void error;
|
|
214
|
+
return { status: context.answer.status, body: { ...context.answer.body, requestId: context.request.id } };
|
|
215
|
+
}
|
|
216
|
+
// Status, headers and body of refusals before ready and during drain (the request is refused either way).
|
|
217
|
+
protected override unavailable(context: WebUnavailableContext): WebUnavailableAnswer {
|
|
218
|
+
return { ...context.answer, headers: { 'retry-after': '5' } };
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
```
|
|
74
222
|
|
|
75
|
-
-
|
|
76
|
-
-
|
|
77
|
-
- `requestTimeout`은 업무 시간 제한이 아니다. 긴 작업은 job으로 보낸다.
|
|
78
|
-
- 응답 종료·클라이언트 연결 끊김을 업무 완료로 보지 않는다.
|
|
223
|
+
- Projects created before 0.4.0 keep `src/infra/web/requires.ts` as their entry (upgrade does not move it). Add `export default class AppWeb extends WebExtension {}` to that file.
|
|
224
|
+
- The extension surface (hook signatures and their types) is fingerprinted in `scripts/release/extensions.json`.
|
|
79
225
|
|
|
80
|
-
|
|
226
|
+
References: `examples/29-extension` (errorBody, unavailable), `examples/22-web` (API and HTML), `examples/12-cluster` and `24-template-inertia --cluster` (rolling replacement), `examples/21-db` (DB and drain), `examples/25-playground`, D-0034, D-0036, D-0062, D-0068, D-0071.
|
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
# @dokebi/web 0.
|
|
1
|
+
# @dokebi/web 0.4.0
|
|
2
2
|
|
|
3
|
-
Node >=24.0.0
|
|
3
|
+
An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). It owns an HTTP server built on Fastify 5.12.7; DBs, routers, controllers and views are not required.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Public contract
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
It follows plugin contract v2 ([D-0028](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0028-plugin-contract-v2.md)): `createPlugin({ app, options?, entry? })` → `app.register(plugin)` → `app.start()` → `app.get(plugin)`. `app` (the Application's `app.view`) is required. Without `options` it uses `app.config['dokebi-web']`, or `{}` when that is missing too. Create a new plugin instance per Application. The old `health`, `requires` and `dependencies` inputs are gone.
|
|
8
8
|
|
|
9
|
-
```ts
|
|
9
|
+
```ts snippet
|
|
10
10
|
import { Application } from '@dokebi/core';
|
|
11
11
|
import { createPlugin as createWeb } from '@dokebi/web';
|
|
12
12
|
|
|
@@ -15,59 +15,85 @@ const web = createWeb({ app: app.view, entry: { requires: [sessionStore] } });
|
|
|
15
15
|
app.register(web);
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
-
|
|
19
|
-
- `entry.requires`: Fastify `onClose
|
|
20
|
-
-
|
|
18
|
+
- Dependencies: `dokebi-health` is an optional dependency (`optionalDependency`). When health is registered in the same app it is connected automatically; otherwise only the app state counts. To choose the instance, register it under the same name first, as in `app.register(createHealth({ app: app.view }))`.
|
|
19
|
+
- `entry.requires`: the Dokebi resources that Fastify `onClose` hooks use. Entries are plugin instances (converted with core `dependencyOf`) or `PluginDependency` descriptors. See "Start, shutdown and ownership" below. A `dokebi-health` instance there is used as a required dependency instead of the optional one.
|
|
20
|
+
- Descriptor for other plugins: `import { dependency } from '@dokebi/web/dependency'` (also exported from the root). When no provider is registered, web is created from this package.
|
|
21
21
|
|
|
22
|
-
- `route<T>(options)`: Fastify RouteOptions
|
|
23
|
-
- `register(plugin, options)`: Fastify async
|
|
24
|
-
- `address`:
|
|
25
|
-
- `track(() => work)`:
|
|
22
|
+
- `route<T>(options)`: keeps Fastify RouteOptions and the Params/Body/Reply types. Register during setup.
|
|
23
|
+
- `register(plugin, options)`: passes a Fastify async or callback plugin and its options (`{}` when none). Native plugins keep their scope, decorators, schemas and hooks.
|
|
24
|
+
- `address`: the real address after listen, undefined before. In a node:cluster worker it is set only after core `ready` (D-0034); other plugins read it in `ready`, not `start`. After shutdown the last address remains, so do not take it as a sign of availability.
|
|
25
|
+
- `track(() => work)`: puts explicit work whose lifetime differs from the HTTP response into drain and returns a Promise. The caller handles its failure and stops accepting new work.
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
web becomes ready and listens in its start, after every Dokebi setup. In a `node:cluster` worker it listens in the core `ready` hook instead ([D-0034](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0034-ready-before-traffic.md)): the primary hands connections to a worker as soon as it listens, so only workers whose whole app is ready should take them. After that, `route` and `register` are FROZEN. Inside a Fastify registration function, register routes on the scope you were given. Adding plugins while running is not supported.
|
|
28
28
|
|
|
29
|
-
## YAML
|
|
29
|
+
## YAML options
|
|
30
30
|
|
|
31
31
|
```yaml
|
|
32
32
|
options:
|
|
33
33
|
dokebi-web:
|
|
34
34
|
host: 127.0.0.1
|
|
35
35
|
port: 3000
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
healthRoutes: # false
|
|
36
|
+
maxBodyBytes: 1048576
|
|
37
|
+
requestTimeoutMs: 30000
|
|
38
|
+
healthRoutes: # false registers no health routes
|
|
39
39
|
live: /health/live
|
|
40
40
|
ready: /health/ready
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
The defaults are host 127.0.0.1, port 0 (an ephemeral port), maxBodyBytes 1 MiB and requestTimeoutMs 30 seconds. Allowed are port 0..65535, maxBodyBytes 1..64 MiB and requestTimeoutMs 1..2147483647 ms. `requestTimeoutMs` limits receiving a request; it is not a limit on running the work and does not cancel DB calls. Before 0.4.0 the keys were `bodyLimit` and `requestTimeout`; those names are still accepted with an `OPTION_DEPRECATED` warning, and setting old and new together is an error ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)). Fastify construction options such as HTTPS, HTTP/2 and `serverFactory` go through the extension hook `fastifyOptions` (AI.md §8).
|
|
44
44
|
|
|
45
|
-
`healthRoutes
|
|
45
|
+
`healthRoutes` defaults to `{ live: '/health/live', ready: '/health/ready' }`. Keys missing from the object use the default path. Paths start with `/`, contain no `?`, `#` or spaces, and live and ready must differ. `false` registers neither route (when an external health server is used). The options are one `defineOptions` declaration in `src/options.ts`, which is the parser, and the build writes `options.schema.json` from it (D-0063 §3). Invalid options fail in the factory with `CoreError('INVALID_PLUGIN_OPTIONS')` (cause: core `INVALID_OPTIONS`, with paths in `details.issues`).
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
Other options: `trustProxy` (below), `sealDriftMs` and `sealExclude` (seal hosts), `formBody` and `formMaxFields` (HTML form bodies, off by default), `developmentErrors` (error details outside production). The [AI guide](AI.md) has the full table.
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
## Start, shutdown and ownership
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
Until the whole Application has started and the optional health is ready, business requests get 503 with the body `{ error: 'SERVICE_UNAVAILABLE', reason }`, where reason is one of `DRAINING`, `STARTING` and `NOT_READY`. A browser page gets the same as a small HTML page (D-0074). The same reason goes to the debug log `HTTP request refused`. The health routes (default `/health/live`, `/health/ready`) are reserved paths and answer 200/503. Health is per app, not an aggregate over the parent cluster.
|
|
52
52
|
|
|
53
|
-
|
|
53
|
+
In a **node:cluster worker** (D-0036), drain first closes the listen socket so the primary sends new connections to other workers. Requests arriving on already open keep-alive connections are served instead of refused and the connection is then closed with `Connection: close`. The worker stays up at least 100 ms after closing listen so connections the primary was handing over are not dropped. A request sent on an idle keep-alive connection at the moment it closes can get `ECONNRESET`. This is an inherent HTTP race, so non-browser clients retry an idempotent request on a reused socket once (as the Node docs recommend). A single process keeps listening and answers 503, as below (the load balancer takes it out through health).
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
In a single process, drain refuses new requests with 503 and then waits for responses, handler Promises, registered request lifecycle hooks and track work. When the core drain deadline (`shutdown.drainTimeoutMs`, default 20 seconds) passes or `stop({ force: true })` aborts `context.drainSignal`, it stops waiting, cuts the remaining connections with `server.closeAllConnections()` and returns; core then records `DRAIN_TIMEOUT`. A client disconnect never marks handler or hook work as done. Fastify.close runs in the deferred cleanup only after every plugin's drain succeeded, and native onClose hooks run then. Shutdown failures and delays are never hidden, and the DB is never closed before unfinished work. A final forced kill in a cluster is a process policy, not a successful drain.
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
**Rule: put every Dokebi resource a Fastify `onClose` hook uses into `entry.requires`.** For example `createWeb({ app: app.view, entry: { requires: [dbPlugin] } })`. Cleanup runs in reverse initialisation order, so web must depend on the resource for the resource to be cleaned up after Fastify.close. If the resource depends on web instead, the resource closes first. Business modules declare the web, router, controller and DB they use in their own requires. Never close a borrowed pool on your own.
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
For native callback hooks, done or the normal end of the response marks the end of the work; async hooks are awaited until their returned Promise settles. Work that continues after the response, and async work in user raw streams, parsers, custom error handlers, timers or outside events, is not tracked automatically: wait for it with track or the owning plugin's drain. Do not mix async and done in a hook. `listen`/`close`, overwriting root hooks and bypassing the reserved `dokebiHealth` config are outside the extension contract.
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
Error responses follow the D-0063 §1 mapping: a Dokebi error answers with its `status` and `{ error: code, message, hint?, data? }` (plus `fix` and `details` in development); an unknown error answers 500 `{ error: 'INTERNAL_SERVER_ERROR' }`. In production (`NODE_ENV=production` or `developmentErrors: false`) `fix` and `details` are left out and 5xx messages become generic sentences. One rule picks the format ([D-0074](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0074-error-responses.md)): Inertia requests, XHR, Bearer API clients, JSON request bodies, sealed requests and `fetch()` get JSON; only a browser page (a navigation, an HTML form post) gets the same content as a small HTML page. A refused body or query string schema is 422 `{ error: 'VALIDATION_FAILED', message, hint, fields: [{ field, message }], errors: { field: message } }`, and `throw validationError({ name: 'Already taken' })` from a handler gives the same answer; an unknown route is 404 `NOT_FOUND` in the same shape. Error responders (`web.errorResponder`) let @dokebi/app draw an app's error views and @dokebi/template-inertia answer Inertia requests (validation redirect, error page). A 500 leaves the error log `WEB_REQUEST_FAILED` (with the full error text). The table is in [AI.md](AI.md) §6. If you register your own error handler, its security is your responsibility. HTTP authentication, rate limiting, CORS and so on are Fastify plugins the app chooses.
|
|
62
62
|
|
|
63
|
-
|
|
63
|
+
## Install and run
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
`dokebi add` creates the entry file `src/infra/web/extension.ts` (`export const requires = [] as const;` and an empty `export default class AppWeb extends WebExtension {}`) through the install module (`dist/install.js`). In projects created before 0.4.0, `src/infra/web/requires.ts` stays the entry after upgrade. The generated code passes this module as `entry`. When you compose the app in your own main, do not edit generated files or register the same ID twice. The repository's runnable example is `examples/22-web/main.ts`; the real DB and cluster example is `examples/21-db/main.ts`.
|
|
66
66
|
|
|
67
|
-
|
|
67
|
+
Plugins with an entry file are left out of the generated code's manifest dependency check, so the entry file's `requires` works on the CLI path too (the same generated-code rule was run with controller and module entry files on 2026-10-14, [ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-04). Dependencies added through an entry file are invisible to the CLI's remove and doctor decisions; a missing one shows up at run time as `MISSING_DEPENDENCY`.
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
## HTTP on seal hosts (D-0062, 0.2.0)
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
web owns the **slot** that seals HTTP data of seal hosts (@dokebi/app `domains.<host>.seal: true`) and of `seal: true` routes. @dokebi/seal fills in the algorithm with `sealCodec(provider)` (this package never imports seal). See [D-0062](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0062-http-seal.md).
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
- The decision (once per request): health → plain, route `seal: false` → plain, `seal: true` or `seal(request)` → sealed, a `sealExclude` prefix (`/` boundary) → plain, any `sealRequests(predicate)` true → sealed. `seal` becomes `config.dokebiSeal` whether given to `route()`, a Fastify `register` scope or a router `mount`.
|
|
74
|
+
- Bodies of sealed requests: when the content type is the provider's `contentType` (`application/vnd.dokebi-seal`), the parser opens it and puts the JSON into `request.body` (drift, replay and tampering are 400, with the reason only in warn `SEAL_BODY_REFUSED`). A body that is neither sealed nor `multipart/form-data` gets `415 { error: 'SEAL_REQUIRED', fix }` **before the parser** (warn `SEAL_REQUIRED`, once per route every 10 seconds).
|
|
75
|
+
- JSON responses of sealed requests (`application/json`, `+json`, 4xx and 5xx included) are sealed in `onSend` and get `Content-Type: application/vnd.dokebi-seal` and `x-dokebi-sealed-path` (the path used for sealing; the final path after redirects). HTML, file and hijacked responses stay as they are. Streamed JSON cannot be sealed and becomes a 500 (plain text is never sent).
|
|
76
|
+
- Code that writes its own body (the Inertia first page, SSE) gets `{ path, encode }` from `sealOf(request)`.
|
|
77
|
+
- When something wants sealing (a registered decision or a sealed route) but no provider exists, start fails with `SEAL_PROVIDER_MISSING`.
|
|
78
|
+
|
|
79
|
+
```yaml
|
|
80
|
+
options:
|
|
81
|
+
dokebi-web:
|
|
82
|
+
sealDriftMs: 60000 # allowed ts drift of sealed bodies (1000..600000); nonces are kept twice as long
|
|
83
|
+
sealExclude: [/webhooks] # path prefixes that stay plain on seal hosts (up to 64)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
| API | Meaning |
|
|
87
|
+
|---|---|
|
|
88
|
+
| `sealCodec(provider)` | fills the HTTP seal slot (setup, once). dokebi-seal calls it |
|
|
89
|
+
| `sealRequests(predicate)` | seals the requests this predicate accepts (setup). dokebi-app calls it for seal domains |
|
|
90
|
+
| `sealOf(request)` | `{ path, encode(text) }` for a sealed request, otherwise undefined |
|
|
91
|
+
| `sealing` | whether a provider is registered |
|
|
92
|
+
|
|
93
|
+
## Route constraint strategies (D-0030)
|
|
94
|
+
|
|
95
|
+
`constraint(strategy)` adds a Fastify route constraint strategy (`addConstraintStrategy`) during setup. Call it before the routes that use the constraint. @dokebi/app uses it to pick the app by Host (`dokebiApp`), so several routes can share one path, split by constraint value. A call after start is `FROZEN`.
|
|
96
|
+
|
|
97
|
+
## Trusted proxies (2026-10-14)
|
|
98
|
+
|
|
99
|
+
Only requests from `trustProxy: [address...]` (exact IPv4 and IPv6 addresses, up to 64) have their `X-Forwarded-Host` (and For and Proto) trusted. The same list goes to Fastify's `trustProxy`. `requestHost(request)` returns the host the request asked for under that rule, in lower case with the port kept. @dokebi/app's domain decision and @dokebi/websocket's Origin check use it. Example: a Cloudflare tunnel on the same machine is `[127.0.0.1, ::1]` ([ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-20).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { FastifyInstance, FastifyServerOptions } from 'fastify';
|
|
2
|
+
export type SchemaControllerOptions = NonNullable<FastifyServerOptions['schemaController']>;
|
|
3
|
+
/** A fresh controller option for one Fastify instance (each instance has its own pools). */
|
|
4
|
+
export declare function lazyCompilers(): SchemaControllerOptions;
|
|
5
|
+
/**
|
|
6
|
+
* After `fastify()`: when the server uses `controller` (not an extension's own), mark its compilers
|
|
7
|
+
* as the defaults again so header schemas keep Fastify's case-insensitive names.
|
|
8
|
+
*/
|
|
9
|
+
export declare function restoreDefaultCompilers(server: FastifyInstance, given: unknown, controller: SchemaControllerOptions): boolean;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Fastify's default schema compilers, built on first use (D-0070 §5).
|
|
3
|
+
*
|
|
4
|
+
* `fastify()` builds its validator compiler (@fastify/ajv-compiler: Ajv, its JTD and draft-07
|
|
5
|
+
* vocabularies) and its serializer compiler (fast-json-stringify) in the constructor, whether or
|
|
6
|
+
* not any route has a schema: about 15 ms of every start, the largest single cost after the JSON
|
|
7
|
+
* Schema check of dokebi.yaml was removed. Here the same two factories are handed to Fastify as
|
|
8
|
+
* `schemaController.compilersFactory` and loaded the first time a route needs one — the same
|
|
9
|
+
* packages, resolved from Fastify's own folder, called with the same arguments.
|
|
10
|
+
*
|
|
11
|
+
* Fastify treats any given `buildValidator` as a custom compiler and then skips one default
|
|
12
|
+
* behaviour: lower-casing the property names of `headers` schemas. These are the default
|
|
13
|
+
* compilers, so the server's flag is put back to "default" right after construction (Fastify's
|
|
14
|
+
* internal schema controller; fastify is pinned, and a web test checks that a header schema with
|
|
15
|
+
* an upper-case name still validates and that Ajv stays unloaded until a schema route exists).
|
|
16
|
+
* Extensions that set their own `schemaController` keep it untouched.
|
|
17
|
+
*/
|
|
18
|
+
const { createRequire } = process.getBuiltinModule('node:module');
|
|
19
|
+
const fromWeb = createRequire(import.meta.url);
|
|
20
|
+
/** Requires a package the way Fastify itself does (its dependencies, not this plugin's). */
|
|
21
|
+
const fromFastify = createRequire(fromWeb.resolve('fastify'));
|
|
22
|
+
/** A fresh controller option for one Fastify instance (each instance has its own pools). */
|
|
23
|
+
export function lazyCompilers() {
|
|
24
|
+
const buildValidator = once('@fastify/ajv-compiler');
|
|
25
|
+
const buildSerializer = once('@fastify/fast-json-stringify-compiler');
|
|
26
|
+
const compilersFactory = {
|
|
27
|
+
buildValidator: (schemas, options) => buildValidator()(schemas, options),
|
|
28
|
+
buildSerializer: (schemas, options) => buildSerializer()(schemas, options),
|
|
29
|
+
};
|
|
30
|
+
return { compilersFactory };
|
|
31
|
+
}
|
|
32
|
+
/** The builder a Fastify compiler package exports, made on the first call and kept. */
|
|
33
|
+
function once(name) {
|
|
34
|
+
let builder;
|
|
35
|
+
return () => {
|
|
36
|
+
if (!builder)
|
|
37
|
+
builder = fromFastify(name)();
|
|
38
|
+
return builder;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* After `fastify()`: when the server uses `controller` (not an extension's own), mark its compilers
|
|
43
|
+
* as the defaults again so header schemas keep Fastify's case-insensitive names.
|
|
44
|
+
*/
|
|
45
|
+
export function restoreDefaultCompilers(server, given, controller) {
|
|
46
|
+
if (given !== controller)
|
|
47
|
+
return false;
|
|
48
|
+
const { kSchemaController } = fromFastify('./lib/symbols.js');
|
|
49
|
+
const schemas = kSchemaController === undefined
|
|
50
|
+
? undefined
|
|
51
|
+
: server[kSchemaController];
|
|
52
|
+
if (!schemas || typeof schemas.isCustomValidatorCompiler !== 'boolean')
|
|
53
|
+
// Only a Fastify other than the pinned one gets here; never leave headers schemas changed.
|
|
54
|
+
throw new Error('Fastify schema controller not found: @dokebi/web needs the fastify version it pins');
|
|
55
|
+
schemas.isCustomValidatorCompiler = false;
|
|
56
|
+
schemas.isCustomSerializerCompiler = false;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { WebApi } from './index.js';
|
|
2
|
+
export declare const provider: import("@dokebi/core").ProviderDescriptor<WebApi>;
|
|
3
|
+
/** Required: created from @dokebi/web when no `dokebi-web` plugin is registered. */
|
|
4
|
+
export declare const dependency: import("@dokebi/core").PluginDependency<WebApi>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineProvider } from '@dokebi/core';
|
|
2
|
+
/*
|
|
3
|
+
* The one place dokebi-web states its name, package and range (D-0063 §6). Plugins and user code
|
|
4
|
+
* that always install @dokebi/web import `dependency` from '@dokebi/web/dependency' (a small
|
|
5
|
+
* module: it does not load Fastify).
|
|
6
|
+
*/
|
|
7
|
+
export const provider = defineProvider({
|
|
8
|
+
name: 'dokebi-web',
|
|
9
|
+
version: '^0.4.0',
|
|
10
|
+
packageName: '@dokebi/web',
|
|
11
|
+
load: () => import('./index.js'),
|
|
12
|
+
});
|
|
13
|
+
/** Required: created from @dokebi/web when no `dokebi-web` plugin is registered. */
|
|
14
|
+
export const dependency = provider.dependency;
|