@dokebi/web 0.2.0 → 0.4.1

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/dist/index.js CHANGED
@@ -1,173 +1,55 @@
1
- import cluster from 'node:cluster';
2
- import { isIP, Server } from 'node:net';
1
+ import { createHmac } from 'node:crypto';
2
+ import { Server } from 'node:net';
3
+ import { parse as parseQuery } from 'node:querystring';
3
4
  import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
4
5
  import { types } from 'node:util';
5
- import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
6
+ import { createExtension, definePlugin, definePoint, dependencyOf, EXTENSION_BRAND, optionalDependency, } from '@dokebi/core';
7
+ import { diagnostics } from '@dokebi/core/libraries';
6
8
  import Fastify, {} from 'fastify';
9
+ import { lazyCompilers, restoreDefaultCompilers } from './compilers.js';
10
+ import { WebError } from './errors.js';
11
+ import { WebExtension, webHooks, } from './extension.js';
12
+ import { options as declaration } from './options.js';
13
+ import { errorAnswer, errorFormat, errorPage, productionBody, sendableDetails, validAnswer, } from './responses.js';
7
14
  import { checkSealSetting, sealExclude, WebSealing, } from './seal.js';
15
+ export { validationError, WebError, WebValidationError, } from './errors.js';
16
+ export { WebExtension, } from './extension.js';
17
+ export { formBackTarget, formFieldErrors, formOldInput, isFormSubmission, } from './forms.js';
18
+ export { options } from './options.js';
19
+ export { errorFormat, } from './responses.js';
8
20
  export { SEALED_PATH_HEADER, } from './seal.js';
9
- export class WebError extends Error {
10
- code;
11
- constructor(code) {
12
- super(`Web: ${code}`);
13
- this.code = code;
14
- this.name = 'WebError';
15
- }
16
- }
17
- /** IPv4-mapped IPv6 (`::ffff:127.0.0.1`) compares as plain IPv4. */
18
- const plainAddress = (address) => address.replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/, '');
19
- function trustProxy(input) {
20
- if (input === undefined)
21
- return Object.freeze([]);
22
- if (!Array.isArray(input) ||
23
- input.length > 64 ||
24
- !input.every((item) => typeof item === 'string' && isIP(item)))
25
- throw new WebError('INVALID_OPTIONS');
26
- return Object.freeze([...new Set(input.map((item) => plainAddress(item)))]);
27
- }
28
- const DEFAULT_HEALTH_ROUTES = Object.freeze({
29
- live: '/health/live',
30
- ready: '/health/ready',
31
- });
32
- /** Copies own string-keyed data properties; Proxies and accessors are rejected unevaluated. */
33
- function dataRecord(input, keys) {
34
- if (!input ||
35
- typeof input !== 'object' ||
36
- Array.isArray(input) ||
37
- types.isProxy(input) ||
38
- ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
39
- return undefined;
40
- const result = Object.create(null);
41
- for (const key of Reflect.ownKeys(input)) {
42
- const descriptor = Object.getOwnPropertyDescriptor(input, key);
43
- if (typeof key !== 'string' || !descriptor || !('value' in descriptor) || !keys.includes(key))
44
- return undefined;
45
- result[key] = descriptor.value;
46
- }
47
- return result;
48
- }
49
- const ROUTE_PATH = /^\/[^?#\s]{0,2047}$/;
21
+ /** Set by `dokebi verify` on the app it starts (D-0065 §11); the header echoes it. */
22
+ const VERIFY_TOKEN_ENV = 'DOKEBI_VERIFY_TOKEN';
23
+ const VERIFY_HEADER = 'x-dokebi-verify';
50
24
  /**
51
- * The full text of a caught value for the `error` log field (D-0047): name, whole message and
52
- * stack, then each `cause` the same way. Only credentials in URLs (`//user:password@`) are
53
- * removed; a text over 16 KB is cut and marked.
25
+ * Set by `dokebi start` on the app (D-0073): a request with a challenge in this header gets
26
+ * HMAC-SHA256(token, challenge) back in it, so `dokebi stop` and `status` can prove a recorded pid
27
+ * is this app where `ps` is unavailable. The token itself never goes on the wire.
54
28
  */
55
- function errorText(error) {
56
- const parts = [];
57
- let current = error;
58
- for (let depth = 0; current !== undefined && depth < 5; depth++) {
59
- let text;
60
- if (current instanceof Error)
61
- text = current.stack ?? `${current.name}: ${current.message}`;
62
- else if (typeof current === 'string')
63
- text = current;
64
- else {
65
- try {
66
- text = `NonError: ${JSON.stringify(current)}`;
67
- }
68
- catch {
69
- text = `NonError: ${String(current)}`; // not serialisable (cycle, BigInt): its string form
70
- }
71
- }
72
- parts.push(depth ? `Caused by: ${text}` : text);
73
- current = current instanceof Error ? current.cause : undefined;
74
- }
75
- const text = parts.join('\n').replace(/\/\/[^\s/@]*@/g, '//***@');
76
- return text.length > 16_384
77
- ? `${text.slice(0, 16_384)}… [truncated ${text.length - 16_384} characters]`
78
- : text;
79
- }
80
- /** How often a repeating error of the same kind is logged; repeats in between are counted. */
81
- const REPEAT_INTERVAL_MS = 10_000;
82
- /**
83
- * Counts repeats of the same error key so a hot path logs it once per interval (D-0047). The
84
- * first occurrence is logged; later ones inside the interval are only counted and reported with
85
- * the next logged occurrence of that key.
86
- */
87
- class Repeats {
88
- #keys = new Map();
89
- /** The repeats to report with this occurrence, or undefined when it is only counted. */
90
- take(key, now = Date.now()) {
91
- const entry = this.#keys.get(key);
92
- if (entry && now < entry.until) {
93
- entry.repeated++;
94
- return undefined;
95
- }
96
- if (!entry && this.#keys.size >= 256)
97
- this.#keys.clear();
98
- this.#keys.set(key, { until: now + REPEAT_INTERVAL_MS, repeated: 0 });
99
- return entry?.repeated ?? 0;
100
- }
29
+ const INSTANCE_TOKEN_ENV = 'DOKEBI_INSTANCE_TOKEN';
30
+ const INSTANCE_HEADER = 'x-dokebi-instance';
31
+ const INSTANCE_TOKEN = /^[A-Za-z0-9_-]{16,128}$/;
32
+ const INSTANCE_CHALLENGE = /^[A-Za-z0-9_-]{16,128}$/;
33
+ const { describeError, Repeats } = diagnostics;
34
+ const EXTENSION_FILE = 'src/infra/web/extension.ts';
35
+ /** IPv4-mapped IPv6 (`::ffff:127.0.0.1`) compares as plain IPv4. */
36
+ const plainAddress = (address) => address.replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/, '');
37
+ function settings(parsed) {
38
+ return Object.freeze({
39
+ ...parsed,
40
+ trustProxy: Object.freeze([...new Set(parsed.trustProxy.map(plainAddress))]),
41
+ sealExclude: sealExclude(parsed.sealExclude),
42
+ });
101
43
  }
44
+ /** Fastify creation options that belong to the drain contract (D-0023, D-0036). */
45
+ const PINNED = Object.freeze({ return503OnClosing: true, forceCloseConnections: 'idle' });
46
+ const FORM_TYPE = 'application/x-www-form-urlencoded';
102
47
  /**
103
48
  * How long a draining node:cluster worker stays up after it stops listening: enough for any
104
49
  * connection the primary was already handing it to be answered "not accepted" and passed on.
105
50
  */
106
51
  const CLOSE_GRACE_MS = 100;
107
- function healthRoutes(input) {
108
- if (input === undefined)
109
- return DEFAULT_HEALTH_ROUTES;
110
- if (input === false)
111
- return false;
112
- const value = dataRecord(input, ['live', 'ready']);
113
- if (!value)
114
- throw new WebError('INVALID_OPTIONS');
115
- const live = value.live === undefined ? DEFAULT_HEALTH_ROUTES.live : value.live;
116
- const ready = value.ready === undefined ? DEFAULT_HEALTH_ROUTES.ready : value.ready;
117
- if (typeof live !== 'string' ||
118
- typeof ready !== 'string' ||
119
- !ROUTE_PATH.test(live) ||
120
- !ROUTE_PATH.test(ready) ||
121
- live === ready)
122
- throw new WebError('INVALID_OPTIONS');
123
- return Object.freeze({ live, ready });
124
- }
125
- function normalize(input) {
126
- const value = dataRecord(input, [
127
- 'host',
128
- 'port',
129
- 'bodyLimit',
130
- 'requestTimeout',
131
- 'healthRoutes',
132
- 'trustProxy',
133
- 'sealDriftMs',
134
- 'sealExclude',
135
- ]);
136
- if (!value)
137
- throw new WebError('INVALID_OPTIONS');
138
- const host = value.host === undefined ? '127.0.0.1' : value.host, port = value.port === undefined ? 0 : value.port, bodyLimit = value.bodyLimit === undefined ? 1048576 : value.bodyLimit, requestTimeout = value.requestTimeout === undefined ? 30000 : value.requestTimeout, sealDriftMs = value.sealDriftMs === undefined ? 60000 : value.sealDriftMs, exclude = sealExclude(value.sealExclude);
139
- if (typeof host !== 'string' ||
140
- !host ||
141
- host.length > 253 ||
142
- typeof port !== 'number' ||
143
- !Number.isInteger(port) ||
144
- port < 0 ||
145
- port > 65535 ||
146
- typeof bodyLimit !== 'number' ||
147
- !Number.isSafeInteger(bodyLimit) ||
148
- bodyLimit < 1 ||
149
- bodyLimit > 67108864 ||
150
- typeof requestTimeout !== 'number' ||
151
- !Number.isSafeInteger(requestTimeout) ||
152
- requestTimeout < 1 ||
153
- requestTimeout > 2147483647 ||
154
- typeof sealDriftMs !== 'number' ||
155
- !Number.isSafeInteger(sealDriftMs) ||
156
- sealDriftMs < 1000 ||
157
- sealDriftMs > 600000 ||
158
- !exclude)
159
- throw new WebError('INVALID_OPTIONS');
160
- return {
161
- host,
162
- port,
163
- bodyLimit,
164
- requestTimeout,
165
- healthRoutes: healthRoutes(value.healthRoutes),
166
- trustProxy: trustProxy(value.trustProxy),
167
- sealDriftMs,
168
- sealExclude: exclude,
169
- };
170
- }
52
+ const injectPoint = definePoint('dokebi-testing:inject');
171
53
  const hooks = new Map([
172
54
  ['onRequest', 2],
173
55
  ['preParsing', 3],
@@ -180,80 +62,232 @@ const hooks = new Map([
180
62
  ['onTimeout', 2],
181
63
  ['onRequestAbort', 1],
182
64
  ]);
65
+ /**
66
+ * Hooks that may run after the response is finished or the client is gone, so the request's own
67
+ * hold no longer covers them: only these are wrapped for drain tracking (D-0068). Request-phase
68
+ * hooks (onRequest … onSend) always run while the request is held.
69
+ */
70
+ const RESPONSE_HOOKS = new Set(['onResponse', 'onError', 'onTimeout', 'onRequestAbort']);
71
+ /** Per-response marks on the raw ServerResponse (no per-request object, D-0068). */
72
+ const REPLY = Symbol('dokebi.web.reply');
73
+ const HANDLER = Symbol('dokebi.web.handler');
74
+ const SENDING = Symbol('dokebi.web.sending');
75
+ const ABORTED = Symbol('dokebi.web.aborted');
76
+ function thenable(value) {
77
+ return (value !== null &&
78
+ (typeof value === 'object' || typeof value === 'function') &&
79
+ typeof value.then === 'function');
80
+ }
81
+ /**
82
+ * A request whose client went away before its response was written (rare). The request stays
83
+ * held until Fastify's chain for it ends: it writes the response head (an error or a late
84
+ * reply), pipes a stream into it, or the handler settled and nothing is being sent. Until then
85
+ * hooks and the handler of that request may still be running (D-0023: a disconnect alone never
86
+ * ends work).
87
+ */
88
+ class AbortedResponse {
89
+ response;
90
+ release;
91
+ #released = false;
92
+ constructor(response, release) {
93
+ this.response = response;
94
+ this.release = release;
95
+ const watch = this;
96
+ const writeHead = response.writeHead;
97
+ const end = response.end;
98
+ // Instance properties of this one response only; the prototype is untouched.
99
+ response.writeHead = function (...args) {
100
+ watch.done('write');
101
+ return writeHead.apply(this, args);
102
+ };
103
+ response.end = function (...args) {
104
+ watch.done('end');
105
+ return end.apply(this, args);
106
+ };
107
+ response.once('pipe', () => watch.done('pipe'));
108
+ const handler = response[HANDLER];
109
+ if (handler !== undefined)
110
+ this.handler(handler);
111
+ }
112
+ /** The route handler was reached (now or before the client left). */
113
+ handler(result) {
114
+ const settled = () => {
115
+ // Fastify sends a resolved value in the same turn; nothing started sending by the next
116
+ // macrotask means it never will (an undefined result after the client left).
117
+ setImmediate(() => {
118
+ if (!this.response[SENDING])
119
+ this.done('handler');
120
+ });
121
+ };
122
+ if (thenable(result))
123
+ result.then(settled, settled);
124
+ else
125
+ settled();
126
+ }
127
+ done(reason) {
128
+ if (this.#released)
129
+ return;
130
+ this.#released = true;
131
+ this.release(reason);
132
+ }
133
+ }
134
+ /** The message of the built-in 503 page per refusal reason. */
135
+ const UNAVAILABLE = {
136
+ STARTING: 'The application is starting. Try again in a moment.',
137
+ NOT_READY: 'The application is not ready. Try again in a moment.',
138
+ DRAINING: 'The application is restarting. Try again in a moment.',
139
+ };
140
+ /** A usable `unavailable` result: a 4xx/5xx status, string headers, synchronous. */
141
+ function validRefusal(value) {
142
+ if (value === null || typeof value !== 'object' || 'then' in value)
143
+ return false;
144
+ const { status, headers } = value;
145
+ return (typeof status === 'number' &&
146
+ Number.isInteger(status) &&
147
+ status >= 400 &&
148
+ status <= 599 &&
149
+ (headers === undefined ||
150
+ (headers !== null &&
151
+ typeof headers === 'object' &&
152
+ Object.values(headers).every((item) => typeof item === 'string'))));
153
+ }
183
154
  class WebOwner {
184
155
  context;
185
156
  options;
186
157
  server;
187
- #pending = new Set();
158
+ /** Requests, handlers, response-phase hooks and track() work still running. */
159
+ #inflight = 0;
160
+ /** Resolved when #inflight reaches 0; only created while draining waits. */
161
+ #idle;
162
+ #release = () => {
163
+ if (--this.#inflight === 0 && this.#idle) {
164
+ const { resolve } = this.#idle;
165
+ this.#idle = undefined;
166
+ resolve();
167
+ }
168
+ };
188
169
  #wrapped = new WeakSet();
189
170
  #closed = false;
190
171
  #frozen = false;
191
172
  #draining = false;
192
173
  #address;
193
174
  #sealing;
175
+ /** Error responders, the last added first (D-0074). */
176
+ #responders = [];
194
177
  api;
195
- constructor(context, options, health) {
178
+ /** A node:cluster worker (D-0063 `context.runtime`): it listens from `ready` and drains first. */
179
+ #worker;
180
+ /** Error bodies without `fix`, `details` and 5xx messages (D-0063 §1). */
181
+ #production;
182
+ #hooks;
183
+ #overridden;
184
+ #https;
185
+ constructor(context, options, extension, health) {
196
186
  this.context = context;
197
187
  this.options = options;
198
- this.server = Fastify({
188
+ const logger = context.logger;
189
+ const runtime = context.runtime ?? context.app.runtime;
190
+ this.#worker = runtime.role === 'worker';
191
+ this.#production = process.env.NODE_ENV === 'production' || !options.developmentErrors;
192
+ this.#hooks = extension.hooks;
193
+ this.#overridden = extension.overridden;
194
+ // Fastify's schema compilers are loaded when a route first needs one (compilers.ts).
195
+ const schemaController = lazyCompilers();
196
+ const defaults = {
199
197
  logger: false,
200
- bodyLimit: options.bodyLimit,
201
- requestTimeout: options.requestTimeout,
202
- return503OnClosing: true,
203
- forceCloseConnections: 'idle',
198
+ bodyLimit: options.maxBodyBytes,
199
+ requestTimeout: options.requestTimeoutMs,
200
+ schemaController,
201
+ ...PINNED,
204
202
  ...(options.trustProxy.length ? { trustProxy: [...options.trustProxy] } : {}),
205
- });
203
+ };
204
+ const created = this.#fastifyOptions(defaults);
205
+ this.#https = Boolean(created.https);
206
+ // HTTPS and HTTP/2 change only the raw server type; the API is typed for the default one.
207
+ this.server = Fastify(created);
208
+ const lazySchemas = restoreDefaultCompilers(this.server, created.schemaController, schemaController);
206
209
  const owner = this;
207
- context.logger.log('debug', 'Web server configured', {
210
+ logger.log('debug', 'Web server configured', {
208
211
  host: options.host,
209
212
  port: options.port,
210
- bodyLimit: options.bodyLimit,
211
- requestTimeout: options.requestTimeout,
213
+ bodyLimit: options.maxBodyBytes,
214
+ requestTimeout: options.requestTimeoutMs,
212
215
  healthRoutes: options.healthRoutes ? { ...options.healthRoutes } : false,
213
216
  trustProxy: options.trustProxy.length,
214
217
  sealDriftMs: options.sealDriftMs,
215
218
  sealExclude: options.sealExclude.length,
219
+ formBody: options.formBody,
220
+ formMaxFields: options.formMaxFields,
221
+ errorBodies: this.#production ? 'production' : 'development',
216
222
  health: health !== undefined,
217
- cluster: cluster.isWorker ? 'worker' : 'none',
223
+ // `lazy`: Fastify's default compilers, loaded on the first schema route (D-0070 §5).
224
+ schemaCompilers: lazySchemas ? 'lazy' : 'extension',
225
+ role: runtime.role,
226
+ serving: runtime.serving,
227
+ extension: [...this.#overridden],
228
+ ...(created === defaults ? {} : { fastifyOptions: Object.keys(created).sort() }),
218
229
  });
219
230
  const failures = new Repeats();
220
- this.server.setErrorHandler((error, request, reply) => {
221
- const code = error && typeof error === 'object' && 'statusCode' in error ? error.statusCode : undefined;
222
- const status = typeof code === 'number' && code >= 400 && code < 500 ? code : 500;
223
- if (status === 500) {
224
- // The route pattern, not the requested URL: no query values in the log (D-0047).
225
- const route = request.routeOptions.url ?? 'unmatched';
226
- const name = error instanceof Error ? error.name : typeof error;
227
- const repeated = failures.take(`${request.method} ${route} ${name}`);
228
- if (repeated !== undefined)
229
- context.logger.log('error', 'HTTP request failed', {
230
- code: 'WEB_REQUEST_FAILED',
231
- requestId: request.id,
232
- method: request.method,
233
- route,
234
- error: errorText(error),
235
- ...(repeated ? { repeated } : {}),
236
- });
231
+ this.server.setErrorHandler((error, request, reply) => this.#fail(error, request, reply, failures));
232
+ // An unknown route answers like any other error (D-0074): the same body, format and
233
+ // responders (an app's errors/404.ejs), not Fastify's own `{ message, error, statusCode }`.
234
+ this.server.setNotFoundHandler((request, reply) => this.#fail(new WebError('NOT_FOUND', `No route for ${request.method} ${request.url.split('?', 1)[0]?.slice(0, 200)}`), request, reply, failures));
235
+ // D-0062: the seal slot. Its hook steps do nothing until something asks for sealing.
236
+ const sealing = new WebSealing(logger, { driftMs: options.sealDriftMs, exclude: options.sealExclude }, (request) => this.api.requestHost(request));
237
+ this.#sealing = sealing;
238
+ // A request is held from here until its response closes (D-0068): one counter and one shared
239
+ // listener, no Promise or closure per request. Callback style: no Promise per hook either.
240
+ const closed = function () {
241
+ owner.#responseClosed(this);
242
+ };
243
+ const worker = this.#worker;
244
+ // `dokebi verify` (D-0065 §11) starts the app with a random token and accepts only answers
245
+ // that echo it, so another project's server on the same port is not taken for this app.
246
+ // Without the variable (every normal start) no hook exists: nothing per request.
247
+ const verifyToken = process.env[VERIFY_TOKEN_ENV];
248
+ if (verifyToken !== undefined) {
249
+ if (/^[A-Za-z0-9_-]{8,128}$/.test(verifyToken)) {
250
+ logger.log('debug', 'Verify instance header enabled', { header: VERIFY_HEADER });
251
+ this.server.addHook('onRequest', (_request, reply, done) => {
252
+ reply.header(VERIFY_HEADER, verifyToken);
253
+ done();
254
+ });
237
255
  }
238
- else if (context.logger.isEnabled('debug'))
239
- context.logger.log('debug', 'HTTP request rejected', {
240
- status,
241
- method: request.method,
242
- route: request.routeOptions.url ?? 'unmatched',
243
- error: errorText(error),
244
- errorCode: error?.code,
256
+ else
257
+ logger.log('warn', 'Verify token ignored: unexpected format', {
258
+ code: 'VERIFY_TOKEN_INVALID',
259
+ variable: VERIFY_TOKEN_ENV,
245
260
  });
246
- reply
247
- .code(status)
248
- .send({ error: status === 500 ? 'INTERNAL_SERVER_ERROR' : 'INVALID_REQUEST' });
249
- });
250
- this.server.addHook('onRequest', async (request, reply) => {
261
+ }
262
+ // `dokebi start` (D-0073): answer the instance challenge before anything else runs (no route,
263
+ // no app code). Without the variable (dev, tests, other process managers) no hook exists.
264
+ const instanceToken = process.env[INSTANCE_TOKEN_ENV];
265
+ if (instanceToken !== undefined) {
266
+ if (INSTANCE_TOKEN.test(instanceToken)) {
267
+ logger.log('debug', 'Instance challenge enabled', { header: INSTANCE_HEADER });
268
+ this.server.addHook('onRequest', (request, reply, done) => {
269
+ const challenge = request.headers[INSTANCE_HEADER];
270
+ if (typeof challenge !== 'string' || !INSTANCE_CHALLENGE.test(challenge))
271
+ return done();
272
+ reply
273
+ .header(INSTANCE_HEADER, createHmac('sha256', instanceToken).update(challenge).digest('base64url'))
274
+ .code(204)
275
+ .send();
276
+ });
277
+ }
278
+ else
279
+ logger.log('warn', 'Instance token ignored: unexpected format', {
280
+ code: 'INSTANCE_TOKEN_INVALID',
281
+ variable: INSTANCE_TOKEN_ENV,
282
+ });
283
+ }
284
+ this.server.addHook('onRequest', (request, reply, done) => {
251
285
  if (request.routeOptions.config.dokebiHealth === true)
252
- return;
286
+ return done();
253
287
  // A draining node:cluster worker no longer listens; a request still arriving on one of its
254
288
  // open keep-alive connections is served and that connection then closes, so the client's
255
289
  // next request goes to another worker instead of seeing 503 (D-0036).
256
- const servesWhileDraining = this.#draining && cluster.isWorker;
290
+ const servesWhileDraining = this.#draining && worker;
257
291
  if (servesWhileDraining)
258
292
  reply.header('connection', 'close');
259
293
  const reason = this.#draining
@@ -266,53 +300,25 @@ class WebOwner {
266
300
  ? 'NOT_READY'
267
301
  : undefined;
268
302
  if (reason) {
269
- // Why a request was turned away: drain, start not finished, or health not ready.
270
- if (context.logger.isEnabled('debug'))
271
- context.logger.log('debug', 'HTTP request refused', {
272
- reason,
273
- method: request.method,
274
- url: request.url.split('?', 1)[0]?.slice(0, 200),
275
- });
276
- return reply
277
- .code(503)
278
- .header('connection', 'close')
279
- .send({ error: 'SERVICE_UNAVAILABLE', reason });
303
+ this.#refuse(request, reply, reason);
304
+ return;
280
305
  }
281
- let release;
282
- const done = new Promise((resolve) => {
283
- release = resolve;
284
- });
285
- const finish = () => {
286
- reply.raw.off('finish', finish);
287
- reply.raw.off('close', finish);
288
- release();
289
- if (this.#draining && cluster.isWorker)
290
- this.server.server.closeIdleConnections();
291
- };
292
- reply.raw.once('finish', finish);
293
- reply.raw.once('close', finish);
294
- this.#watch(done);
306
+ const raw = reply.raw;
307
+ this.#inflight++;
308
+ raw[REPLY] = reply;
309
+ raw.on('close', closed);
310
+ // A sealed request with a plain body is answered 415 here, before any parser (D-0062).
311
+ done(sealing.provider ? sealing.refusePlain(request) : undefined);
295
312
  });
296
- // Responses already under way when a cluster worker starts draining close their connection
297
- // too, instead of leaving it idle for the client to reuse (D-0036).
298
- this.server.addHook('onSend', async (_request, reply, payload) => {
299
- if (this.#draining && cluster.isWorker)
313
+ this.server.addHook('onSend', (request, reply, payload, done) => {
314
+ reply.raw[SENDING] = true;
315
+ // Responses already under way when a cluster worker starts draining close their
316
+ // connection too, instead of leaving it idle for the client to reuse (D-0036).
317
+ if (this.#draining && worker)
300
318
  reply.header('connection', 'close');
301
- return payload;
302
- });
303
- // D-0062: the seal slot. Both hooks do nothing until something asks for sealing.
304
- const sealing = new WebSealing(context.logger, { driftMs: options.sealDriftMs, exclude: options.sealExclude }, (request) => this.api.requestHost(request), errorText);
305
- this.#sealing = sealing;
306
- this.server.addHook('onRequest', async (request, reply) => {
307
- if (!sealing.provider)
308
- return;
309
- return sealing.onRequest(request, reply);
310
- });
311
- this.server.addHook('onSend', async (request, reply, payload) => {
312
- if (!sealing.provider)
313
- return payload;
314
- return sealing.onSend(request, reply, payload);
319
+ done(null, sealing.provider ? sealing.onSend(request, reply, payload) : payload);
315
320
  });
321
+ this.#formBody(options);
316
322
  this.server.addHook('onRoute', (route) => {
317
323
  // `seal` on a route given to Fastify directly (a register() scope, @dokebi/router mount)
318
324
  // becomes `config.dokebiSeal` too, so every way of adding a route can opt out (D-0062).
@@ -329,8 +335,19 @@ class WebOwner {
329
335
  if (config?.dokebiHealth === true)
330
336
  return;
331
337
  const original = route.handler;
338
+ // The handler is held until its Promise settles, also after an early reply.send() and
339
+ // after the client left (D-0023). The request itself is already held by onRequest, so
340
+ // this is the only tracking a handler gets: one reaction on the Promise it returns.
332
341
  route.handler = function (request, reply) {
333
- return owner.track(() => original.call(this, request, reply));
342
+ const result = original.call(this, request, reply);
343
+ const raw = reply.raw;
344
+ raw[HANDLER] = result;
345
+ if (thenable(result)) {
346
+ owner.#inflight++;
347
+ result.then(owner.#release, owner.#release);
348
+ }
349
+ raw[ABORTED]?.handler(result);
350
+ return result;
334
351
  };
335
352
  const fields = route;
336
353
  for (const name of hooks.keys()) {
@@ -398,7 +415,7 @@ class WebOwner {
398
415
  this.#assertMutable();
399
416
  sealing.setProvider(provider);
400
417
  // Registered on the root before any plugin scope exists, so every route inherits it.
401
- this.server.addContentTypeParser(provider.contentType, { parseAs: 'string', bodyLimit: options.bodyLimit }, (request, body) => sealing.parse(request, String(body)));
418
+ this.server.addContentTypeParser(provider.contentType, { parseAs: 'string', bodyLimit: options.maxBodyBytes }, (request, body) => sealing.parse(request, String(body)));
402
419
  },
403
420
  sealRequests: (predicate) => {
404
421
  this.#assertMutable();
@@ -408,22 +425,75 @@ class WebOwner {
408
425
  get sealing() {
409
426
  return sealing.provider !== undefined;
410
427
  },
428
+ errorResponder: (responder) => {
429
+ this.#assertMutable();
430
+ if (typeof responder !== 'function')
431
+ throw new WebError('INVALID_ARGUMENT', 'An error responder must be a function', {
432
+ fix: 'Pass a function: web.errorResponder((response) => boolean | Promise<boolean>).',
433
+ });
434
+ this.#responders.unshift(responder);
435
+ logger.log('debug', 'Web error responder registered', {
436
+ responders: this.#responders.length,
437
+ });
438
+ },
411
439
  });
412
440
  }
413
441
  #assertMutable() {
414
442
  if (this.#frozen || this.#closed)
415
443
  throw new WebError('FROZEN');
416
444
  }
417
- #watch(promise) {
418
- this.#pending.add(promise);
419
- // Bookkeeping only: the caller holds the same promise and sees its rejection (D-0047).
420
- void promise.then(() => this.#pending.delete(promise), () => this.#pending.delete(promise));
421
- return promise;
445
+ /** The shared 'close' listener of every held response (`this` is the response). */
446
+ #responseClosed(response) {
447
+ // 'close' fires once per response, so the listener is not removed (one call saved).
448
+ if (this.#draining && this.#worker)
449
+ this.server.server.closeIdleConnections();
450
+ const reply = response[REPLY];
451
+ // Written (finished, or at least its head: the rest needs no user code) or hijacked: done.
452
+ if (response.writableFinished || response.headersSent || reply === undefined || reply.sent) {
453
+ this.#release();
454
+ return;
455
+ }
456
+ // The client left before the response was written. Hooks or the handler of this request may
457
+ // still run; hold it until Fastify's chain for it ends (D-0023).
458
+ const logger = this.context.logger;
459
+ if (logger.isEnabled('debug'))
460
+ logger.log('debug', 'HTTP client left before the response', {
461
+ method: reply.request.method,
462
+ route: reply.request.routeOptions.url ?? 'unmatched',
463
+ handler: response[HANDLER] !== undefined,
464
+ sending: response[SENDING] === true,
465
+ });
466
+ response[ABORTED] = new AbortedResponse(response, (reason) => {
467
+ if (logger.isEnabled('debug'))
468
+ logger.log('debug', 'HTTP request without client finished', {
469
+ method: reply.request.method,
470
+ route: reply.request.routeOptions.url ?? 'unmatched',
471
+ reason,
472
+ });
473
+ this.#release();
474
+ });
422
475
  }
423
476
  track(work) {
424
477
  if (this.#closed)
425
478
  return Promise.reject(new WebError('CLOSED'));
426
- return this.#watch(Promise.resolve().then(work));
479
+ this.#inflight++;
480
+ const promise = Promise.resolve().then(work);
481
+ // Bookkeeping only: the caller holds the same promise and sees its rejection (D-0047).
482
+ void promise.then(this.#release, this.#release);
483
+ return promise;
484
+ }
485
+ /** Resolves once nothing is held (immediately when nothing is). */
486
+ #whenIdle() {
487
+ if (this.#inflight === 0)
488
+ return Promise.resolve();
489
+ if (!this.#idle) {
490
+ let resolve;
491
+ const promise = new Promise((done) => {
492
+ resolve = done;
493
+ });
494
+ this.#idle = { promise, resolve };
495
+ }
496
+ return this.#idle.promise;
427
497
  }
428
498
  #hook(name, fn) {
429
499
  const count = hooks.get(name);
@@ -433,6 +503,9 @@ class WebOwner {
433
503
  (fn.length === count + 1 || (name === 'onRequestAbort' && fn.length !== 1))) {
434
504
  throw new TypeError('Async Fastify hooks must not accept a done callback');
435
505
  }
506
+ // Request-phase hooks run while their request is held: no wrapper, no cost (D-0068).
507
+ if (!RESPONSE_HOOKS.has(name))
508
+ return fn;
436
509
  const owner = this;
437
510
  function invoke(instance, args) {
438
511
  return owner.track(() => new Promise((resolve, reject) => {
@@ -485,6 +558,30 @@ class WebOwner {
485
558
  this.#wrapped.add(wrapped);
486
559
  return wrapped;
487
560
  }
561
+ /** The urlencoded body parser, or its refusal when `formBody` is off (D-0068). */
562
+ #formBody(options) {
563
+ if (!options.formBody) {
564
+ // Refused before the body is read: nothing is buffered for a request that gets 415.
565
+ this.server.addContentTypeParser(FORM_TYPE, (_request, _payload, done) => {
566
+ done(new WebError('FORM_BODY_DISABLED', 'Form bodies are not enabled'), undefined);
567
+ });
568
+ return;
569
+ }
570
+ const max = options.formMaxFields;
571
+ this.server.addContentTypeParser(FORM_TYPE, { parseAs: 'string', bodyLimit: options.maxBodyBytes }, (_request, body, done) => {
572
+ const text = body;
573
+ // Counted before parsing: refused, never cut (querystring's maxKeys drops the rest).
574
+ let fields = text.length ? 1 : 0;
575
+ for (let at = text.indexOf('&'); at !== -1; at = text.indexOf('&', at + 1))
576
+ if (++fields > max) {
577
+ done(new WebError('FORM_BODY_TOO_MANY_FIELDS', `A form body may carry at most ${max} fields`, { data: { maxFields: max } }), undefined);
578
+ return;
579
+ }
580
+ // node:querystring: decodes + and %XX, repeats become arrays, and the result has a null
581
+ // prototype (`__proto__` is an ordinary key, nothing is polluted).
582
+ done(null, parseQuery(text, '&', '=', { maxKeys: 0 }));
583
+ });
584
+ }
488
585
  async start() {
489
586
  this.#frozen = true;
490
587
  const started = performance.now();
@@ -498,16 +595,35 @@ class WebOwner {
498
595
  // node:cluster shares the port: the primary hands connections to a worker as soon as it
499
596
  // listens, so a worker listens only once the whole application is ready (`ready`, D-0034).
500
597
  // A single process listens here and answers 503 until then (health checks see it start).
501
- if (!cluster.isWorker)
598
+ if (!this.#worker)
502
599
  await this.listen();
503
600
  }
601
+ /** Listens unless this process does not serve (`runtime.serving` false, D-0063 §4). */
504
602
  async listen() {
505
603
  if (this.#address !== undefined)
506
604
  return;
605
+ const runtime = this.context.runtime ?? this.context.app.runtime;
606
+ if (!runtime.serving) {
607
+ this.context.logger.log('debug', 'Web server not listening', {
608
+ role: runtime.role,
609
+ serving: false,
610
+ });
611
+ return;
612
+ }
507
613
  const started = performance.now();
508
614
  this.#address = await this.server.listen({ host: this.options.host, port: this.options.port });
509
- this.context.logger.log('debug', 'Web server listening', {
615
+ // info, with every bound address: `dokebi start` reads it to show where the app answers.
616
+ // `localhost` binds both 127.0.0.1 and ::1, so there can be more than one.
617
+ const scheme = this.#https ? 'https' : 'http';
618
+ const urls = this.server
619
+ .addresses()
620
+ .map((bound) => bound.family === 'IPv6' || bound.family === 6
621
+ ? `${scheme}://[${bound.address}]:${bound.port}`
622
+ : `${scheme}://${bound.address}:${bound.port}`);
623
+ this.context.logger.log('info', 'Web server listening', {
510
624
  address: this.#address,
625
+ urls: urls.length ? urls : [this.#address],
626
+ host: this.options.host,
511
627
  ms: Math.round(performance.now() - started),
512
628
  });
513
629
  }
@@ -517,8 +633,8 @@ class WebOwner {
517
633
  const started = performance.now();
518
634
  const logger = this.context.logger;
519
635
  logger.log('debug', 'Web drain started', {
520
- pending: this.#pending.size,
521
- clusterWorker: cluster.isWorker,
636
+ pending: this.#inflight,
637
+ clusterWorker: this.#worker,
522
638
  });
523
639
  // The node:cluster primary keeps handing new connections to a worker while it listens, so a
524
640
  // draining worker stops listening first; new connections go to the other workers. A single
@@ -532,7 +648,7 @@ class WebOwner {
532
648
  // keep-alive connections at once, racing clients that are just reusing them. Those
533
649
  // connections stay; their next request is served with `Connection: close`.
534
650
  let grace;
535
- if (cluster.isWorker && this.server.server.listening) {
651
+ if (this.#worker && this.server.server.listening) {
536
652
  Server.prototype.close.call(this.server.server);
537
653
  grace = delay(CLOSE_GRACE_MS);
538
654
  logger.log('debug', 'Web worker stopped listening', { graceMs: CLOSE_GRACE_MS });
@@ -545,18 +661,19 @@ class WebOwner {
545
661
  signal.addEventListener('abort', () => resolve(), { once: true, signal: listening.signal });
546
662
  });
547
663
  try {
548
- while (this.#pending.size) {
549
- await Promise.race([Promise.allSettled([...this.#pending]), aborted]);
664
+ while (this.#inflight > 0) {
665
+ await Promise.race([this.#whenIdle(), aborted]);
550
666
  if (signal.aborted) {
551
667
  // Deadline or forced stop: cut the remaining connections; core records the timeout.
552
668
  logger.log('debug', 'Web drain cut connections', {
553
- pending: this.#pending.size,
669
+ pending: this.#inflight,
554
670
  ms: Math.round(performance.now() - started),
555
671
  });
556
672
  this.server.server.closeAllConnections();
557
673
  return;
558
674
  }
559
- // Fastify can schedule serialization/response hooks after a handler promise resolves.
675
+ // Fastify starts the next step of a request (the next hook, onResponse after 'finish')
676
+ // right after the previous one settles; look again once those have had their turn.
560
677
  await immediate();
561
678
  }
562
679
  if (grace)
@@ -567,6 +684,255 @@ class WebOwner {
567
684
  listening.abort();
568
685
  }
569
686
  }
687
+ get worker() {
688
+ return this.#worker;
689
+ }
690
+ /** Fastify creation options: the extension's `fastifyOptions`, checked (D-0064 §9). */
691
+ #fastifyOptions(defaults) {
692
+ if (!this.#hooks || !this.#overridden.has('fastifyOptions'))
693
+ return defaults;
694
+ const result = this.#hooks.fastifyOptions(Object.freeze({ ...defaults }));
695
+ const plain = result !== null &&
696
+ typeof result === 'object' &&
697
+ !types.isProxy(result) &&
698
+ [Object.prototype, null].includes(Object.getPrototypeOf(result)) &&
699
+ !('then' in result);
700
+ const fields = (plain ? result : {});
701
+ const changed = Object.keys(PINNED).filter((key) => Object.hasOwn(fields, key) && fields[key] !== PINNED[key]);
702
+ if (!plain ||
703
+ changed.length ||
704
+ (fields.serverFactory !== undefined && typeof fields.serverFactory !== 'function'))
705
+ throw new WebError('INVALID_EXTENSION_RESULT', 'fastifyOptions() must return a plain object of Fastify options', {
706
+ fix: `Return { ...defaults, … } from fastifyOptions() in ${EXTENSION_FILE}, synchronously; return503OnClosing and forceCloseConnections belong to the drain contract.`,
707
+ data: { hook: 'fastifyOptions', ...(changed.length ? { pinned: changed } : {}) },
708
+ });
709
+ return { ...fields, ...PINNED };
710
+ }
711
+ /**
712
+ * The error handler: D-0063 §1 mapping, the `errorBody` hook, logging, then the error responders
713
+ * or the built-in JSON or HTML answer (D-0074). Synchronous while no responder is registered.
714
+ */
715
+ #fail(error, request, reply, failures) {
716
+ const logger = this.context.logger;
717
+ const production = this.#production;
718
+ let answer = errorAnswer(error, production, (details) => this.#details(details));
719
+ // The route pattern, not the requested URL: no query values in the log (D-0047).
720
+ const route = request.routeOptions.url ?? 'unmatched';
721
+ const own = error?.code;
722
+ const code = typeof own === 'string' ? own : answer.body.error;
723
+ if (answer.status >= 500) {
724
+ const name = error instanceof Error ? error.name : typeof error;
725
+ const repeated = failures.take(`${request.method} ${route} ${name} ${code}`);
726
+ if (repeated !== undefined)
727
+ logger.log('error', 'HTTP request failed', {
728
+ code: 'WEB_REQUEST_FAILED',
729
+ requestId: request.id,
730
+ method: request.method,
731
+ route,
732
+ status: answer.status,
733
+ errorCode: code,
734
+ error: describeError(error),
735
+ ...(repeated ? { repeated } : {}),
736
+ });
737
+ }
738
+ else if (error instanceof WebError && error.code === 'FORM_BODY_DISABLED') {
739
+ // A disabled form body is a setup mistake worth seeing once per interval.
740
+ const repeated = failures.take(`${error.code} ${request.method} ${route}`);
741
+ if (repeated !== undefined)
742
+ logger.log('warn', 'HTTP form body refused', {
743
+ code: error.code,
744
+ method: request.method,
745
+ route,
746
+ fix: error.fix,
747
+ ...(repeated ? { repeated } : {}),
748
+ });
749
+ }
750
+ else if (logger.isEnabled('debug'))
751
+ logger.log('debug', 'HTTP request rejected', {
752
+ status: answer.status,
753
+ method: request.method,
754
+ route,
755
+ error: describeError(error),
756
+ errorCode: code,
757
+ });
758
+ if (this.#hooks && this.#overridden.has('errorBody')) {
759
+ try {
760
+ const changed = this.#hooks.errorBody(error, { request, answer, production });
761
+ if (!validAnswer(changed))
762
+ throw new WebError('INVALID_EXTENSION_RESULT', 'errorBody() returned no answer', {
763
+ data: { hook: 'errorBody' },
764
+ });
765
+ answer = changed;
766
+ }
767
+ catch (failure) {
768
+ const repeated = failures.take(`errorBody ${route}`);
769
+ if (repeated !== undefined)
770
+ logger.log('error', 'Web errorBody hook failed', {
771
+ code: 'WEB_EXTENSION_FAILED',
772
+ method: request.method,
773
+ route,
774
+ fix: `Return { status, body: { error, … } } from errorBody() in ${EXTENSION_FILE}.`,
775
+ error: describeError(failure),
776
+ ...(repeated ? { repeated } : {}),
777
+ });
778
+ }
779
+ }
780
+ const body = production ? productionBody(answer.body) : answer.body;
781
+ // D-0074 §1: JSON for scripts (Inertia, fetch, XHR, APIs, sealed requests), a small page for
782
+ // a browser navigation or an HTML form post.
783
+ const sealed = this.#sealing.sealOf(request) !== undefined;
784
+ const format = errorFormat(request.headers, sealed);
785
+ reply.code(answer.status);
786
+ if (!this.#responders.length) {
787
+ this.#send(reply, answer.status, body, format);
788
+ return undefined;
789
+ }
790
+ return this.#respond({ request, reply, error, status: answer.status, body, format, production, sealed }, route, failures);
791
+ }
792
+ /** The built-in answer: the body as JSON, or its small HTML page. */
793
+ #send(reply, status, body, format) {
794
+ reply.code(status);
795
+ if (format === 'html')
796
+ reply.type('text/html; charset=utf-8').send(errorPage(status, body));
797
+ else
798
+ reply.type('application/json; charset=utf-8').send(body);
799
+ }
800
+ /** Asks the error responders (D-0074); the built-in answer when none wrote one or one failed. */
801
+ async #respond(response, route, failures) {
802
+ const { request, reply } = response;
803
+ const logger = this.context.logger;
804
+ // `reply.sent` stays false until the response has ended (async onSend hooks such as the
805
+ // session's run first), so whether a responder sent is seen on this reply's own `send`
806
+ // (redirect() and view helpers call it too). Error answers only: no cost on other requests.
807
+ let sent = false;
808
+ const send = reply.send;
809
+ reply.send = function (...args) {
810
+ sent = true;
811
+ return send.apply(this, args);
812
+ };
813
+ for (const [index, responder] of this.#responders.entries()) {
814
+ try {
815
+ if ((await responder(response)) === true) {
816
+ if (sent || reply.sent)
817
+ return reply;
818
+ throw new WebError('INVALID_EXTENSION_RESULT', 'An error responder returned true without sending an answer');
819
+ }
820
+ if (sent || reply.sent)
821
+ return reply;
822
+ }
823
+ catch (failure) {
824
+ const repeated = failures.take(`responder ${index} ${route}`);
825
+ if (repeated !== undefined)
826
+ logger.log('error', 'Web error responder failed', {
827
+ code: 'WEB_ERROR_RESPONDER_FAILED',
828
+ method: request.method,
829
+ route,
830
+ status: response.status,
831
+ errorCode: response.body.error,
832
+ fix: 'The built-in error answer was sent instead; fix the error view or page (see error).',
833
+ error: describeError(failure),
834
+ ...(repeated ? { repeated } : {}),
835
+ });
836
+ if (sent || reply.sent)
837
+ return reply;
838
+ break;
839
+ }
840
+ }
841
+ // Headers a failed responder may have set (a view's type) are replaced by the built-in answer.
842
+ this.#send(reply, response.status, response.body, response.format);
843
+ return reply;
844
+ }
845
+ /** `details` for a development body; one that is not JSON (a cycle, a BigInt) is left out. */
846
+ #details(details) {
847
+ try {
848
+ return sendableDetails(details);
849
+ }
850
+ catch (error) {
851
+ if (this.context.logger.isEnabled('debug'))
852
+ this.context.logger.log('debug', 'Web error details not sent', {
853
+ reason: 'not-json',
854
+ error: describeError(error),
855
+ });
856
+ return undefined;
857
+ }
858
+ }
859
+ /** The 503 of a request refused before start, while not ready or while draining. */
860
+ #refuse(request, reply, reason) {
861
+ const logger = this.context.logger;
862
+ // Why a request was turned away: drain, start not finished, or health not ready.
863
+ if (logger.isEnabled('debug'))
864
+ logger.log('debug', 'HTTP request refused', {
865
+ reason,
866
+ method: request.method,
867
+ url: request.url.split('?', 1)[0]?.slice(0, 200),
868
+ });
869
+ // D-0074 §1: a browser navigation gets a small page, every script JSON; sealed requests stay
870
+ // JSON (the route is known in onRequest, so the seal decision is too).
871
+ const html = errorFormat(request.headers, this.#sealing.sealOf(request) !== undefined) === 'html';
872
+ if (!this.#hooks || !this.#overridden.has('unavailable')) {
873
+ reply.code(503).header('connection', 'close');
874
+ if (html)
875
+ reply
876
+ .type('text/html; charset=utf-8')
877
+ .send(errorPage(503, { error: 'SERVICE_UNAVAILABLE', message: UNAVAILABLE[reason] }));
878
+ else
879
+ reply.send({ error: 'SERVICE_UNAVAILABLE', reason });
880
+ return;
881
+ }
882
+ const answer = {
883
+ status: 503,
884
+ body: { error: 'SERVICE_UNAVAILABLE', reason },
885
+ };
886
+ let chosen = answer;
887
+ try {
888
+ const result = this.#hooks.unavailable({ request, reason, answer });
889
+ if (!validRefusal(result))
890
+ throw new WebError('INVALID_EXTENSION_RESULT', 'unavailable() returned no answer', {
891
+ data: { hook: 'unavailable' },
892
+ });
893
+ chosen = result;
894
+ }
895
+ catch (failure) {
896
+ logger.log('error', 'Web unavailable hook failed', {
897
+ code: 'WEB_EXTENSION_FAILED',
898
+ reason,
899
+ fix: `Return { status, headers?, body } synchronously from unavailable() in ${EXTENSION_FILE}.`,
900
+ error: describeError(failure),
901
+ });
902
+ }
903
+ reply.code(chosen.status);
904
+ for (const [name, value] of Object.entries(chosen.headers ?? {}))
905
+ reply.header(name, value);
906
+ // The request is refused either way: the connection closes, as without the hook.
907
+ reply.header('connection', 'close');
908
+ const body = chosen.body;
909
+ // A page only for a body of the error shape; anything else the hook chose stays JSON.
910
+ if (html && body !== null && typeof body === 'object' && typeof body.error === 'string')
911
+ reply
912
+ .type('text/html; charset=utf-8')
913
+ .send(errorPage(chosen.status, this.#production
914
+ ? productionBody(body)
915
+ : body));
916
+ else
917
+ reply.send(chosen.body);
918
+ }
919
+ /** `@dokebi/core/testing` inject (D-0063 §7): a request through Fastify, without a socket. */
920
+ async inject(request) {
921
+ const response = await this.server.inject({
922
+ method: (request.method ?? 'GET'),
923
+ url: request.url,
924
+ ...(request.headers ? { headers: { ...request.headers } } : {}),
925
+ ...(request.payload === undefined
926
+ ? {}
927
+ : { payload: request.payload }),
928
+ });
929
+ return Object.freeze({
930
+ statusCode: response.statusCode,
931
+ headers: Object.freeze({ ...response.headers }),
932
+ body: response.body,
933
+ json: () => JSON.parse(response.body),
934
+ });
935
+ }
570
936
  async close() {
571
937
  this.#closed = true;
572
938
  const started = performance.now();
@@ -576,66 +942,122 @@ class WebOwner {
576
942
  });
577
943
  }
578
944
  }
945
+ const NO_EXTENSION = Object.freeze({
946
+ hooks: undefined,
947
+ overridden: new Set(),
948
+ });
579
949
  const HEALTH = 'dokebi-health';
580
- const health = optionalDependency({ name: HEALTH, version: '^0.1.0' });
950
+ const health = optionalDependency({ name: HEALTH, version: '^0.4.0' });
951
+ function invalidEntry(message, fix) {
952
+ return new WebError('INVALID_ENTRY', message, fix === undefined ? {} : { fix });
953
+ }
581
954
  function requirement(value) {
582
955
  if (value === null || typeof value !== 'object')
583
- throw new TypeError('Invalid web requirement');
956
+ throw invalidEntry('Invalid web requirement');
584
957
  if (typeof value.setup === 'function')
585
958
  return dependencyOf(value);
586
959
  if (typeof value.name !== 'string')
587
- throw new TypeError('Invalid web requirement');
960
+ throw invalidEntry('Invalid web requirement');
588
961
  return value;
589
962
  }
590
- /** Accepts a plain object or the namespace of the user entry module (src/web/index.ts). */
591
- function parseEntry(input) {
592
- if (input === undefined)
593
- return { requires: [] };
594
- if (input === null ||
595
- typeof input !== 'object' ||
596
- Array.isArray(input) ||
597
- types.isProxy(input) ||
598
- ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
599
- throw new TypeError('Invalid web entry');
600
- let list;
601
- for (const key of Reflect.ownKeys(input)) {
602
- // Module namespaces carry Symbol.toStringTag; only string exports are entry fields.
603
- if (typeof key !== 'string')
604
- continue;
605
- const descriptor = Object.getOwnPropertyDescriptor(input, key);
606
- if (key !== 'requires' || !descriptor || !('value' in descriptor))
607
- throw new TypeError('Invalid web entry');
608
- list = descriptor.value;
963
+ function brandedForWeb(value) {
964
+ if (typeof value !== 'function')
965
+ return false;
966
+ const declaration = value[EXTENSION_BRAND];
967
+ return declaration?.plugin === 'dokebi-web';
968
+ }
969
+ /**
970
+ * The entry as given: `requires` is checked at once, the extension class is created lazily,
971
+ * once, when the factory derives dependencies (so INVALID_EXTENSION leaves the factory call).
972
+ */
973
+ class WebEntryInput {
974
+ requires;
975
+ #extension;
976
+ #resolved;
977
+ constructor(input) {
978
+ if (input === undefined || typeof input === 'function') {
979
+ this.requires = [];
980
+ this.#extension = input;
981
+ return;
982
+ }
983
+ if (input === null ||
984
+ typeof input !== 'object' ||
985
+ Array.isArray(input) ||
986
+ types.isProxy(input) ||
987
+ ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
988
+ throw invalidEntry('Invalid web entry');
989
+ let list;
990
+ let extension;
991
+ for (const key of Reflect.ownKeys(input)) {
992
+ // Module namespaces carry Symbol.toStringTag; only string exports are entry fields.
993
+ if (typeof key !== 'string')
994
+ continue;
995
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
996
+ if (!descriptor || !('value' in descriptor))
997
+ throw invalidEntry('Invalid web entry');
998
+ if (key === 'requires')
999
+ list = descriptor.value;
1000
+ else if (key === 'default')
1001
+ extension = descriptor.value;
1002
+ else if (brandedForWeb(descriptor.value))
1003
+ throw invalidEntry('The web extension class must be the default export', `Write export default class … extends WebExtension in ${EXTENSION_FILE} (found the named export ${key}).`);
1004
+ else
1005
+ throw invalidEntry('Invalid web entry');
1006
+ }
1007
+ this.#extension = extension;
1008
+ if (list === undefined) {
1009
+ this.requires = [];
1010
+ return;
1011
+ }
1012
+ if (!Array.isArray(list) || list.length > 256)
1013
+ throw invalidEntry('Invalid web requires');
1014
+ const requires = list.map(requirement);
1015
+ const names = new Set(requires.map((dependency) => dependency.name));
1016
+ if (names.size !== requires.length || names.has('dokebi-web'))
1017
+ throw invalidEntry('Duplicate web requirement');
1018
+ this.requires = Object.freeze(requires);
1019
+ }
1020
+ extension() {
1021
+ this.#resolved ??= this.#resolve();
1022
+ return this.#resolved;
1023
+ }
1024
+ #resolve() {
1025
+ if (this.#extension === undefined)
1026
+ return NO_EXTENSION;
1027
+ const created = createExtension(this.#extension, WebExtension);
1028
+ if (!created.overridden.length)
1029
+ return NO_EXTENSION;
1030
+ return Object.freeze({
1031
+ hooks: webHooks(created.instance),
1032
+ overridden: new Set(created.overridden),
1033
+ });
609
1034
  }
610
- if (list === undefined)
611
- return { requires: [] };
612
- if (!Array.isArray(list) || list.length > 256)
613
- throw new TypeError('Invalid web requires');
614
- const requires = list.map(requirement);
615
- const names = new Set(requires.map((dependency) => dependency.name));
616
- if (names.size !== requires.length || names.has('dokebi-web'))
617
- throw new TypeError('Duplicate web requirement');
618
- return { requires };
619
1035
  }
620
1036
  class WebRuntime {
621
1037
  options;
1038
+ extension;
622
1039
  health;
623
1040
  #owner;
624
- constructor(options, health) {
1041
+ constructor(options, extension, health) {
625
1042
  this.options = options;
1043
+ this.extension = extension;
626
1044
  this.health = health;
627
1045
  }
628
1046
  setup(context) {
629
- const owner = new WebOwner(context, this.options, context.getOptionalDependency(this.health));
1047
+ const owner = new WebOwner(context, this.options, this.extension, context.getOptionalDependency(this.health));
630
1048
  this.#owner = owner;
631
1049
  context.defer(() => owner.close());
1050
+ // D-0063 §7: `inject` of @dokebi/core/testing goes through this server, without a socket.
1051
+ context.contribute(injectPoint, Object.freeze({
1052
+ inject: (request) => owner.inject(request),
1053
+ }));
632
1054
  return owner.api;
633
1055
  }
634
1056
  start() {
635
1057
  return this.#owner?.start();
636
1058
  }
637
1059
  ready() {
638
- return cluster.isWorker ? this.#owner?.listen() : undefined;
1060
+ return this.#owner?.worker ? this.#owner.listen() : undefined;
639
1061
  }
640
1062
  drain(context) {
641
1063
  return this.#owner?.drain(context.drainSignal);
@@ -643,24 +1065,22 @@ class WebRuntime {
643
1065
  }
644
1066
  export const createPlugin = definePlugin({
645
1067
  name: 'dokebi-web',
646
- version: '0.2.0',
647
- core: '^0.2.0',
648
- options: normalize,
649
- entry: parseEntry,
1068
+ version: '0.4.1',
1069
+ core: '^0.4.0',
1070
+ options: declaration,
1071
+ entry: (input) => new WebEntryInput(input),
1072
+ contributes: [injectPoint],
650
1073
  // A required dokebi-health in entry.requires replaces the optional link.
651
1074
  dependencies: ({ entry }) => {
1075
+ // The extension is created here, once: a broken subclass fails the factory call.
1076
+ entry?.extension();
652
1077
  const requires = entry?.requires ?? [];
653
1078
  return requires.some((dependency) => dependency.name === HEALTH)
654
1079
  ? requires
655
1080
  : [...requires, health];
656
1081
  },
657
- instance: ({ options, dependencies }) => new WebRuntime(options, (dependencies.find((dependency) => dependency.name === HEALTH) ??
1082
+ instance: ({ options, entry, dependencies }) => new WebRuntime(settings(options), entry?.extension() ?? NO_EXTENSION, (dependencies.find((dependency) => dependency.name === HEALTH) ??
658
1083
  health)),
659
1084
  });
660
- /** Declares dokebi-web as a required provider; it is created from this package when absent. */
661
- export const dependency = providerDependency({
662
- name: 'dokebi-web',
663
- packageName: '@dokebi/web',
664
- version: '^0.2.0',
665
- load: () => import('./index.js'),
666
- });
1085
+ /** Declares dokebi-web as a required provider (also `@dokebi/web/dependency`, D-0063 §6). */
1086
+ export { dependency } from './dependency.js';