@dokebi/web 0.4.2 → 0.4.3
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 +248 -39
- package/README.md +31 -10
- package/dist/app-routes.d.ts +20 -0
- package/dist/app-routes.js +137 -0
- package/dist/before-hijack.d.ts +24 -0
- package/dist/before-hijack.js +73 -0
- package/dist/body.d.ts +14 -0
- package/dist/body.js +30 -0
- package/dist/cluster-ready.d.ts +67 -0
- package/dist/cluster-ready.js +123 -0
- package/dist/compilers.d.ts +16 -0
- package/dist/compilers.js +25 -0
- package/dist/compression.d.ts +40 -0
- package/dist/compression.js +435 -0
- package/dist/connections.d.ts +44 -0
- package/dist/connections.js +282 -0
- package/dist/define-errors.d.ts +76 -0
- package/dist/define-errors.js +161 -0
- package/dist/describe.d.ts +37 -0
- package/dist/describe.js +96 -0
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +24 -3
- package/dist/forms.d.ts +23 -7
- package/dist/forms.js +53 -13
- package/dist/index.d.ts +134 -4
- package/dist/index.js +1518 -91
- package/dist/options.d.ts +56 -0
- package/dist/options.js +320 -1
- package/dist/points.d.ts +159 -0
- package/dist/points.js +162 -1
- package/dist/responses.d.ts +31 -6
- package/dist/responses.js +68 -6
- package/dist/route-config.d.ts +38 -0
- package/dist/route-config.js +222 -0
- package/dist/route-hooks.d.ts +75 -0
- package/dist/route-hooks.js +118 -0
- package/dist/route-table.d.ts +55 -0
- package/dist/route-table.js +142 -0
- package/dist/seal.d.ts +49 -1
- package/dist/seal.js +259 -24
- package/dist/security-headers.d.ts +121 -0
- package/dist/security-headers.js +298 -0
- package/dist/transient-log.d.ts +42 -0
- package/dist/transient-log.js +95 -0
- package/options.schema.json +488 -1
- package/package.json +22 -9
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The connections of the web server (D-0023 follow-up of 2026-10-22), kept with public events
|
|
3
|
+
* only: 'connection', 'secureConnection', 'session', 'request' and 'upgrade' of the Node server,
|
|
4
|
+
* 'close' of sockets and responses. Per connection: one Set entry and one shared 'close'
|
|
5
|
+
* listener (plus one Map entry behind TLS or HTTP/2, to pair the accepted socket with its TLS
|
|
6
|
+
* socket or session by remote address). Per HTTP/1 request: one property write (the newest
|
|
7
|
+
* response of the connection; it is answering while that response has not finished, since
|
|
8
|
+
* Node answers a connection's requests in order). Per HTTP/2 request: a counter on the session
|
|
9
|
+
* and one shared 'close' listener on the response (streams of a session run side by side).
|
|
10
|
+
*
|
|
11
|
+
* Node's own sweep (closeIdleConnections) leaves a connection on which no request ever arrived
|
|
12
|
+
* (a browser's preconnect, the spare connection a client opens after it aborted a request) and
|
|
13
|
+
* one whose next request is still arriving, and HTTP/2 servers leave a TLS or h2c connection
|
|
14
|
+
* whose client never sent its preface: server.close() waited for them until headersTimeout or
|
|
15
|
+
* forever, past the cleanup deadline (CLEANUP_TIMEOUT).
|
|
16
|
+
*/
|
|
17
|
+
/** Streams being answered on an HTTP/2 session. */
|
|
18
|
+
const ANSWERING = Symbol('dokebi.web.answering');
|
|
19
|
+
/** On an HTTP/1 socket: the response of its newest request. */
|
|
20
|
+
const LAST = Symbol('dokebi.web.last');
|
|
21
|
+
/** An HTTP/1 socket handed to an 'upgrade' owner (a WebSocket plugin closes it itself). */
|
|
22
|
+
const UPGRADED = Symbol('dokebi.web.upgraded');
|
|
23
|
+
/** On the accepted socket: the TLS socket HTTP runs on. */
|
|
24
|
+
const SECURE = Symbol('dokebi.web.secure');
|
|
25
|
+
/** On the accepted socket: its HTTP/2 session. */
|
|
26
|
+
const SESSION = Symbol('dokebi.web.session');
|
|
27
|
+
/** On the accepted socket: its remote address key (the pairing Map entry). */
|
|
28
|
+
const REMOTE = Symbol('dokebi.web.remote');
|
|
29
|
+
/** On an HTTP/2 response: its session (a stream forgets its session once destroyed). */
|
|
30
|
+
const HOLDER = Symbol('dokebi.web.holder');
|
|
31
|
+
/** A response that has not finished (its last bytes not yet handed to the socket). */
|
|
32
|
+
const answering = (response) => !response.writableFinished && !response.destroyed;
|
|
33
|
+
const remoteOf = (socket) => `${socket.remoteAddress ?? '?'}|${socket.remotePort ?? '?'}`;
|
|
34
|
+
export class WebConnections {
|
|
35
|
+
#accepted = new Set();
|
|
36
|
+
/** Who waits for the next connection to end (a draining worker's idle wait). */
|
|
37
|
+
#waiting = [];
|
|
38
|
+
#secure;
|
|
39
|
+
#logger;
|
|
40
|
+
#closing = false;
|
|
41
|
+
constructor(server, settings) {
|
|
42
|
+
this.#secure = settings.secure;
|
|
43
|
+
this.#logger = settings.logger;
|
|
44
|
+
const pair = settings.secure || settings.http2;
|
|
45
|
+
const byRemote = pair ? new Map() : undefined;
|
|
46
|
+
// h2c: Node emits 'session' in its own 'connection' listener, before this one runs.
|
|
47
|
+
const early = settings.http2 ? new Map() : undefined;
|
|
48
|
+
const accepted = this.#accepted;
|
|
49
|
+
const self = this;
|
|
50
|
+
function forget() {
|
|
51
|
+
accepted.delete(this);
|
|
52
|
+
if (self.#waiting.length) {
|
|
53
|
+
const waiting = self.#waiting;
|
|
54
|
+
self.#waiting = [];
|
|
55
|
+
for (const resolve of waiting)
|
|
56
|
+
resolve();
|
|
57
|
+
}
|
|
58
|
+
const key = this[REMOTE];
|
|
59
|
+
if (key !== undefined && byRemote?.get(key) === this)
|
|
60
|
+
byRemote.delete(key);
|
|
61
|
+
}
|
|
62
|
+
server.on('connection', (socket) => {
|
|
63
|
+
if (self.#closing) {
|
|
64
|
+
socket.destroy();
|
|
65
|
+
if (self.#logger.isEnabled('debug'))
|
|
66
|
+
self.#logger.log('debug', 'Web connection ended: the server is closing', {
|
|
67
|
+
remote: `${socket.remoteAddress ?? '?'}:${socket.remotePort ?? '?'}`,
|
|
68
|
+
});
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
accepted.add(socket);
|
|
72
|
+
socket.once('close', forget);
|
|
73
|
+
if (byRemote === undefined)
|
|
74
|
+
return;
|
|
75
|
+
const key = remoteOf(socket);
|
|
76
|
+
socket[REMOTE] = key;
|
|
77
|
+
byRemote.set(key, socket);
|
|
78
|
+
const session = early?.get(key);
|
|
79
|
+
if (session !== undefined) {
|
|
80
|
+
early?.delete(key);
|
|
81
|
+
socket[SESSION] = session;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
if (settings.secure)
|
|
85
|
+
server.on('secureConnection', (secure) => {
|
|
86
|
+
const socket = byRemote?.get(remoteOf(secure));
|
|
87
|
+
if (socket !== undefined)
|
|
88
|
+
socket[SECURE] = secure;
|
|
89
|
+
});
|
|
90
|
+
if (settings.http2)
|
|
91
|
+
server.on('session', (session) => {
|
|
92
|
+
// session.socket is Node's proxy of the session's socket: reading its address is allowed.
|
|
93
|
+
const key = remoteOf(session.socket);
|
|
94
|
+
const socket = byRemote?.get(key);
|
|
95
|
+
if (socket !== undefined)
|
|
96
|
+
socket[SESSION] = session;
|
|
97
|
+
else {
|
|
98
|
+
early?.set(key, session);
|
|
99
|
+
// Paired in this turn by 'connection'; a socket that never came leaves no entry behind.
|
|
100
|
+
queueMicrotask(() => {
|
|
101
|
+
if (early?.get(key) === session)
|
|
102
|
+
early.delete(key);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
function answered() {
|
|
107
|
+
const session = this[HOLDER];
|
|
108
|
+
if (session === undefined)
|
|
109
|
+
return;
|
|
110
|
+
const left = (session[ANSWERING] ?? 1) - 1;
|
|
111
|
+
session[ANSWERING] = left;
|
|
112
|
+
// Node's session.close() ends the session after its last stream: said again, it is a no-op.
|
|
113
|
+
if (left === 0 && self.#closing)
|
|
114
|
+
session.close();
|
|
115
|
+
}
|
|
116
|
+
// First, so the mark is there before Fastify's handler can answer.
|
|
117
|
+
server.prependListener('request', (request, response) => {
|
|
118
|
+
if (request.httpVersionMajor !== 2) {
|
|
119
|
+
request.socket[LAST] = response;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const session = request.stream.session;
|
|
123
|
+
response[HOLDER] = session;
|
|
124
|
+
session[ANSWERING] = (session[ANSWERING] ?? 0) + 1;
|
|
125
|
+
response.on('close', answered);
|
|
126
|
+
});
|
|
127
|
+
// An upgraded socket gets no 'request'. Node hands an upgrade to 'upgrade' listeners only
|
|
128
|
+
// while there is one (otherwise it answers it as a request), so the mark listens only while
|
|
129
|
+
// another owner (a WebSocket plugin) does.
|
|
130
|
+
const mark = Object.assign((_request, socket) => {
|
|
131
|
+
socket[UPGRADED] = true;
|
|
132
|
+
},
|
|
133
|
+
// Lets another plugin's upgrade listener (template-inertia's Vite HMR) tell this one, which
|
|
134
|
+
// only marks sockets, from listeners that own upgrades (a WebSocket plugin).
|
|
135
|
+
{ [Symbol.for('dokebi.web.upgrade-mark')]: true });
|
|
136
|
+
let owners = 0;
|
|
137
|
+
server.on('newListener', (event, listener) => {
|
|
138
|
+
if (event !== 'upgrade' || listener === mark)
|
|
139
|
+
return;
|
|
140
|
+
if (owners++ === 0)
|
|
141
|
+
server.prependListener('upgrade', mark);
|
|
142
|
+
});
|
|
143
|
+
server.on('removeListener', (event, listener) => {
|
|
144
|
+
if (event !== 'upgrade' || listener === mark)
|
|
145
|
+
return;
|
|
146
|
+
if (--owners === 0)
|
|
147
|
+
server.removeListener('upgrade', mark);
|
|
148
|
+
});
|
|
149
|
+
// An owner a serverFactory added before.
|
|
150
|
+
const before = server.listenerCount('upgrade');
|
|
151
|
+
if (before > 0) {
|
|
152
|
+
owners = before;
|
|
153
|
+
server.prependListener('upgrade', mark);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** Open connections (tests, logs and a draining worker's idle wait). */
|
|
157
|
+
get size() {
|
|
158
|
+
return this.#accepted.size;
|
|
159
|
+
}
|
|
160
|
+
/** Resolves when the next connection ends. */
|
|
161
|
+
changed() {
|
|
162
|
+
return new Promise((resolve) => {
|
|
163
|
+
this.#waiting.push(resolve);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/** The HTTP/1 socket of an accepted one (behind TLS, once its handshake is done). */
|
|
167
|
+
#http(socket) {
|
|
168
|
+
return this.#secure ? socket[SECURE] : socket;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Close (after the drain): ends every connection that answers no request and was not
|
|
172
|
+
* upgraded, tells an HTTP/2 session with streams under way to go away (GOAWAY: it ends once
|
|
173
|
+
* they end), and from now on ends a connection once its last response ends and every
|
|
174
|
+
* connection accepted at once. A response under way is left to finish.
|
|
175
|
+
*/
|
|
176
|
+
close() {
|
|
177
|
+
this.#closing = true;
|
|
178
|
+
let ended = 0;
|
|
179
|
+
let kept = 0;
|
|
180
|
+
for (const socket of this.#accepted) {
|
|
181
|
+
if (socket.destroyed)
|
|
182
|
+
continue;
|
|
183
|
+
const session = socket[SESSION];
|
|
184
|
+
if (session?.[ANSWERING]) {
|
|
185
|
+
session.close();
|
|
186
|
+
kept++;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const http = session === undefined ? this.#http(socket) : undefined;
|
|
190
|
+
if (http?.[UPGRADED]) {
|
|
191
|
+
kept++;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const last = http?.[LAST];
|
|
195
|
+
if (http !== undefined && last !== undefined && answering(last)) {
|
|
196
|
+
this.#endAfter(http, last);
|
|
197
|
+
kept++;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
// The bytes of an answered response still on their way leave before the end.
|
|
201
|
+
if (http !== undefined && http.writableLength > 0)
|
|
202
|
+
http.end(() => http.destroy());
|
|
203
|
+
// Also an HTTP/2 session without streams: its socket, since a session whose client never
|
|
204
|
+
// sent its preface stays open after session.close() and session.destroy().
|
|
205
|
+
else
|
|
206
|
+
socket.destroy();
|
|
207
|
+
ended++;
|
|
208
|
+
}
|
|
209
|
+
if (ended || kept)
|
|
210
|
+
this.#logger.log('debug', 'Web close ended connections without a request', { ended, kept });
|
|
211
|
+
return { ended, kept };
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* An HTTP/1 connection answering while closing: once its newest response closes (and no newer
|
|
215
|
+
* request came meanwhile), the connection is ended after its bytes are out. Node leaves such a
|
|
216
|
+
* keep-alive connection open after server.close() until keepAliveTimeout.
|
|
217
|
+
*/
|
|
218
|
+
#endAfter(socket, response) {
|
|
219
|
+
response.once('close', () => {
|
|
220
|
+
const last = socket[LAST];
|
|
221
|
+
if (last !== undefined && last !== response && answering(last)) {
|
|
222
|
+
this.#endAfter(socket, last);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (socket.destroyed || socket.writableEnded)
|
|
226
|
+
return;
|
|
227
|
+
socket.end(() => socket.destroy());
|
|
228
|
+
if (this.#logger.isEnabled('debug'))
|
|
229
|
+
this.#logger.log('debug', 'Web close ended a connection after its response', {
|
|
230
|
+
remote: `${socket.remoteAddress ?? '?'}:${socket.remotePort ?? '?'}`,
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* A draining node:cluster worker (D-0036, D-0107 §1), once per drain: every HTTP/2 session is
|
|
236
|
+
* told to go away (its streams under way finish); the caller sweeps idle HTTP/1 connections.
|
|
237
|
+
*/
|
|
238
|
+
goAway() {
|
|
239
|
+
let sessions = 0;
|
|
240
|
+
for (const socket of this.#accepted) {
|
|
241
|
+
const session = socket[SESSION];
|
|
242
|
+
if (session === undefined || session.closed || session.destroyed)
|
|
243
|
+
continue;
|
|
244
|
+
session.close();
|
|
245
|
+
sessions++;
|
|
246
|
+
}
|
|
247
|
+
return sessions;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* A draining worker's response ended: its HTTP/1 connection is ended when it answers no
|
|
251
|
+
* other request (a socket Node is already ending, or that is gone, is left alone). An HTTP/2
|
|
252
|
+
* response's session went away in goAway(). Returns the ended socket.
|
|
253
|
+
*/
|
|
254
|
+
endIfIdle(response) {
|
|
255
|
+
if (response[HOLDER] !== undefined)
|
|
256
|
+
return undefined;
|
|
257
|
+
// ServerResponse detaches its socket before 'close'; the request keeps it.
|
|
258
|
+
const socket = response.req.socket;
|
|
259
|
+
if (socket === null || socket.destroyed || socket.writableEnded)
|
|
260
|
+
return undefined;
|
|
261
|
+
// A newer request of the connection is being answered.
|
|
262
|
+
const last = socket[LAST];
|
|
263
|
+
if (last !== undefined && last !== response && answering(last))
|
|
264
|
+
return undefined;
|
|
265
|
+
socket.destroy();
|
|
266
|
+
return socket;
|
|
267
|
+
}
|
|
268
|
+
/** The drain deadline or a forced stop: every connection but upgraded ones is cut. */
|
|
269
|
+
cut() {
|
|
270
|
+
let cut = 0;
|
|
271
|
+
for (const socket of this.#accepted) {
|
|
272
|
+
if (socket.destroyed)
|
|
273
|
+
continue;
|
|
274
|
+
const http = socket[SESSION] === undefined ? this.#http(socket) : undefined;
|
|
275
|
+
if (http?.[UPGRADED])
|
|
276
|
+
continue;
|
|
277
|
+
socket.destroy();
|
|
278
|
+
cut++;
|
|
279
|
+
}
|
|
280
|
+
return cut;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { DokebiError } from '@dokebi/core';
|
|
2
|
+
/** The key of the frozen code list on a `defineErrors` result (D-0077 D). */
|
|
3
|
+
export declare const ERROR_CATALOG: unique symbol;
|
|
4
|
+
/**
|
|
5
|
+
* Set to true on an error of a code declared `intended` (a refusal the app makes on purpose): the
|
|
6
|
+
* web plugin logs it at warn instead of error. A symbol, so a second installed copy reads it too.
|
|
7
|
+
*/
|
|
8
|
+
export declare const INTENDED_REFUSAL: unique symbol;
|
|
9
|
+
/** One app error code: the HTTP status, the client message and an optional hint. */
|
|
10
|
+
export interface ErrorDefinition {
|
|
11
|
+
/** HTTP status dokebi-web answers with: 400 to 599. */
|
|
12
|
+
readonly status: number;
|
|
13
|
+
/** Fixed English, one line: what went wrong (`The post does not exist`). */
|
|
14
|
+
readonly message: string;
|
|
15
|
+
/** Optional, one line: what the person who got the error can do next. */
|
|
16
|
+
readonly hint?: string;
|
|
17
|
+
/**
|
|
18
|
+
* A refusal the app makes on purpose (a report budget, a quota it enforces): status 503 only,
|
|
19
|
+
* thrown with `data.retryAfterMs`. Logged at warn and counted per window instead of at error,
|
|
20
|
+
* because it is the app working as designed, not a failure. Default false.
|
|
21
|
+
*/
|
|
22
|
+
readonly intended?: boolean;
|
|
23
|
+
}
|
|
24
|
+
/** One entry of the code list (`errorCatalog`). */
|
|
25
|
+
export interface ErrorCatalogEntry {
|
|
26
|
+
readonly code: string;
|
|
27
|
+
readonly status: number;
|
|
28
|
+
readonly message: string;
|
|
29
|
+
readonly hint?: string;
|
|
30
|
+
readonly intended?: true;
|
|
31
|
+
}
|
|
32
|
+
/** What one `errors.CODE(…)` call may add or change. */
|
|
33
|
+
export interface DefinedErrorOptions {
|
|
34
|
+
/** Values safe to send with the error (`body.data`): ids, limits. Never secrets. */
|
|
35
|
+
readonly data?: Readonly<Record<string, unknown>>;
|
|
36
|
+
/** Diagnostics for developers and logs only (hidden in production, like `fix`). */
|
|
37
|
+
readonly details?: unknown;
|
|
38
|
+
/** The error that caused this one (kept in logs). */
|
|
39
|
+
readonly cause?: unknown;
|
|
40
|
+
/** Replaces the defined message for this one error (still one line of fixed English). */
|
|
41
|
+
readonly message?: string;
|
|
42
|
+
}
|
|
43
|
+
/** A factory of one code: `errors.POST_NOT_FOUND({ data: { id } })`. */
|
|
44
|
+
export interface DefinedError<TCode extends string> {
|
|
45
|
+
(options?: DefinedErrorOptions): DokebiError<TCode>;
|
|
46
|
+
/** The code, for comparisons: `error.code === errors.POST_NOT_FOUND.code`. */
|
|
47
|
+
readonly code: TCode;
|
|
48
|
+
readonly status: number;
|
|
49
|
+
}
|
|
50
|
+
/** The result of `defineErrors`: one factory per code, and the frozen code list. */
|
|
51
|
+
export type DefinedErrors<T extends Readonly<Record<string, ErrorDefinition>>> = {
|
|
52
|
+
readonly [K in keyof T & string]: DefinedError<K>;
|
|
53
|
+
} & {
|
|
54
|
+
readonly [ERROR_CATALOG]: readonly ErrorCatalogEntry[];
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The app's error codes (D-0077 D), in `src/shared/errors.ts`:
|
|
58
|
+
*
|
|
59
|
+
* export const errors = defineErrors({
|
|
60
|
+
* POST_NOT_FOUND: { status: 404, message: 'The post does not exist' },
|
|
61
|
+
* });
|
|
62
|
+
* throw errors.POST_NOT_FOUND({ data: { id } });
|
|
63
|
+
*
|
|
64
|
+
* Each call makes a `DokebiError` with the code, status, message and hint (`plugin: 'app'`);
|
|
65
|
+
* dokebi-web answers it like any coded error. A wrong code, a status outside 400..599, an empty
|
|
66
|
+
* or multi-line message, an unknown field or `VALIDATION_FAILED` (use `validationError`) throws
|
|
67
|
+
* INVALID_ARGUMENT when the module loads.
|
|
68
|
+
*/
|
|
69
|
+
export declare function defineErrors<const T extends Readonly<Record<string, ErrorDefinition>>>(definitions: T): DefinedErrors<T>;
|
|
70
|
+
/**
|
|
71
|
+
* The code list of a `defineErrors` result, or of a module namespace that exports one
|
|
72
|
+
* (`await import('./src/shared/errors.ts')`): `[{ code, status, message, hint? }]`, frozen.
|
|
73
|
+
* Several exported results are joined in export order (one result exported twice counts once,
|
|
74
|
+
* a code already listed is not repeated). undefined when there is none.
|
|
75
|
+
*/
|
|
76
|
+
export declare function errorCatalog(value: unknown): readonly ErrorCatalogEntry[] | undefined;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// The app's error codes in one place (D-0077 D): `src/shared/errors.ts` declares them with
|
|
2
|
+
// `defineErrors`, app code throws `errors.CODE()`, and dokebi-web answers each in the D-0074 shape
|
|
3
|
+
// (`{ error, message, hint?, data? }` with its status). The result carries its frozen list under
|
|
4
|
+
// `Symbol.for('dokebi.errors.v1')`, so a tool (`dokebi describe`) can read the list from the module
|
|
5
|
+
// without knowing the export name, and a second installed copy of @dokebi/web reads it too.
|
|
6
|
+
import { DokebiError } from '@dokebi/core';
|
|
7
|
+
import { WebError } from './errors.js';
|
|
8
|
+
/** The key of the frozen code list on a `defineErrors` result (D-0077 D). */
|
|
9
|
+
export const ERROR_CATALOG = Symbol.for('dokebi.errors.v1');
|
|
10
|
+
/**
|
|
11
|
+
* Set to true on an error of a code declared `intended` (a refusal the app makes on purpose): the
|
|
12
|
+
* web plugin logs it at warn instead of error. A symbol, so a second installed copy reads it too.
|
|
13
|
+
*/
|
|
14
|
+
export const INTENDED_REFUSAL = Symbol.for('dokebi.errors.intended.v1');
|
|
15
|
+
/** A stable code (D-0063): upper case letters, digits and `_`, starting with a letter. */
|
|
16
|
+
const CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
17
|
+
const MAX_CODES = 1000;
|
|
18
|
+
const MAX_TEXT = 500;
|
|
19
|
+
const FIELDS = new Set(['status', 'message', 'hint', 'intended']);
|
|
20
|
+
/** CR, LF and the Unicode line and paragraph separators. */
|
|
21
|
+
const LINE_BREAK = /[\r\n\u2028\u2029]/;
|
|
22
|
+
const EXAMPLE = "defineErrors({ POST_NOT_FOUND: { status: 404, message: 'The post does not exist', hint: 'Check the address.' } })";
|
|
23
|
+
function invalid(message, fix = `Declare the codes as ${EXAMPLE}.`) {
|
|
24
|
+
return new WebError('INVALID_ARGUMENT', message, { fix });
|
|
25
|
+
}
|
|
26
|
+
/** One line of text: non-empty after trimming, no line break, at most MAX_TEXT characters. */
|
|
27
|
+
function oneLine(value) {
|
|
28
|
+
return (typeof value === 'string' &&
|
|
29
|
+
value.trim() !== '' &&
|
|
30
|
+
value.length <= MAX_TEXT &&
|
|
31
|
+
!LINE_BREAK.test(value));
|
|
32
|
+
}
|
|
33
|
+
function plainObject(value) {
|
|
34
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
35
|
+
return false;
|
|
36
|
+
const prototype = Object.getPrototypeOf(value);
|
|
37
|
+
return prototype === Object.prototype || prototype === null;
|
|
38
|
+
}
|
|
39
|
+
function checkDefinition(code, value) {
|
|
40
|
+
if (!CODE.test(code))
|
|
41
|
+
throw invalid(`Error code ${JSON.stringify(code)} is not a code: use upper case letters, digits and _, starting with a letter (at most 64)`);
|
|
42
|
+
if (code === 'VALIDATION_FAILED')
|
|
43
|
+
throw invalid('VALIDATION_FAILED belongs to dokebi-web: it carries the refused fields', "Refuse fields with throw validationError({ field: 'message' }) (import { validationError } from '@dokebi/web'); give other app errors their own code.");
|
|
44
|
+
if (!plainObject(value))
|
|
45
|
+
throw invalid(`Error code ${code} needs { status, message, hint?, intended? }`);
|
|
46
|
+
const unknown = Object.keys(value).filter((key) => !FIELDS.has(key));
|
|
47
|
+
if (unknown.length)
|
|
48
|
+
throw invalid(`Error code ${code} has unknown field ${unknown.join(', ')}: only status, message, hint and intended`);
|
|
49
|
+
const { status, message, hint, intended } = value;
|
|
50
|
+
if (typeof status !== 'number' || !Number.isInteger(status) || status < 400 || status > 599)
|
|
51
|
+
throw invalid(`Error code ${code} needs a status from 400 to 599`);
|
|
52
|
+
if (!oneLine(message))
|
|
53
|
+
throw invalid(`Error code ${code} needs a message: one line of text (at most ${MAX_TEXT} characters)`);
|
|
54
|
+
if (hint !== undefined && !oneLine(hint))
|
|
55
|
+
throw invalid(`The hint of error code ${code} must be one line of text when set`);
|
|
56
|
+
if (intended !== undefined && typeof intended !== 'boolean')
|
|
57
|
+
throw invalid(`intended of error code ${code} must be true or false when set`);
|
|
58
|
+
if (intended === true && status !== 503)
|
|
59
|
+
throw invalid(`Error code ${code} is intended but answers ${status}: only a 503 refusal can be intended`, 'Declare an intended refusal as { status: 503, message, intended: true } and throw it with data: { retryAfterMs }; a 4xx answer is not logged as an error anyway.');
|
|
60
|
+
return Object.freeze({
|
|
61
|
+
code,
|
|
62
|
+
status,
|
|
63
|
+
message: message.trim(),
|
|
64
|
+
...(hint === undefined ? {} : { hint: hint.trim() }),
|
|
65
|
+
...(intended === true ? { intended: true } : {}),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function factory(entry) {
|
|
69
|
+
const { code, status, hint, intended } = entry;
|
|
70
|
+
const create = (options = {}) => {
|
|
71
|
+
if (!plainObject(options))
|
|
72
|
+
throw invalid(`errors.${code}() takes { data?, details?, cause?, message? }`, `Call errors.${code}() or errors.${code}({ data: { id } }).`);
|
|
73
|
+
const { data, details, cause, message } = options;
|
|
74
|
+
if (message !== undefined && !oneLine(message))
|
|
75
|
+
throw invalid(`The message of errors.${code}() must be one line of text (at most ${MAX_TEXT} characters)`, `Leave message out to use the defined one, or pass one line of fixed English.`);
|
|
76
|
+
if (data !== undefined && !plainObject(data))
|
|
77
|
+
throw invalid(`The data of errors.${code}() must be a plain object`, `Pass data as { name: value } with values that are safe to send.`);
|
|
78
|
+
const error = new DokebiError(code, message?.trim() ?? entry.message, {
|
|
79
|
+
plugin: 'app',
|
|
80
|
+
status,
|
|
81
|
+
...(hint === undefined ? {} : { hint }),
|
|
82
|
+
...(data === undefined ? {} : { data }),
|
|
83
|
+
...(details === undefined ? {} : { details }),
|
|
84
|
+
...(cause === undefined ? {} : { cause }),
|
|
85
|
+
});
|
|
86
|
+
if (intended)
|
|
87
|
+
Object.defineProperty(error, INTENDED_REFUSAL, { value: true });
|
|
88
|
+
return error;
|
|
89
|
+
};
|
|
90
|
+
return Object.freeze(Object.assign(create, { code, status }));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The app's error codes (D-0077 D), in `src/shared/errors.ts`:
|
|
94
|
+
*
|
|
95
|
+
* export const errors = defineErrors({
|
|
96
|
+
* POST_NOT_FOUND: { status: 404, message: 'The post does not exist' },
|
|
97
|
+
* });
|
|
98
|
+
* throw errors.POST_NOT_FOUND({ data: { id } });
|
|
99
|
+
*
|
|
100
|
+
* Each call makes a `DokebiError` with the code, status, message and hint (`plugin: 'app'`);
|
|
101
|
+
* dokebi-web answers it like any coded error. A wrong code, a status outside 400..599, an empty
|
|
102
|
+
* or multi-line message, an unknown field or `VALIDATION_FAILED` (use `validationError`) throws
|
|
103
|
+
* INVALID_ARGUMENT when the module loads.
|
|
104
|
+
*/
|
|
105
|
+
export function defineErrors(definitions) {
|
|
106
|
+
if (!plainObject(definitions))
|
|
107
|
+
throw invalid('defineErrors() takes an object of codes');
|
|
108
|
+
const codes = Object.keys(definitions);
|
|
109
|
+
if (codes.length === 0 || codes.length > MAX_CODES)
|
|
110
|
+
throw invalid(`defineErrors() takes 1 to ${MAX_CODES} codes, not ${codes.length}`);
|
|
111
|
+
const catalog = codes.map((code) => checkDefinition(code, definitions[code]));
|
|
112
|
+
const result = Object.create(null);
|
|
113
|
+
for (const entry of catalog)
|
|
114
|
+
result[entry.code] = factory(entry);
|
|
115
|
+
result[ERROR_CATALOG] = Object.freeze(catalog);
|
|
116
|
+
return Object.freeze(result);
|
|
117
|
+
}
|
|
118
|
+
/** A code list read from another copy: a frozen array of entries of the documented shape. */
|
|
119
|
+
function catalogOf(value) {
|
|
120
|
+
if (value === null || (typeof value !== 'object' && typeof value !== 'function'))
|
|
121
|
+
return undefined;
|
|
122
|
+
const list = value[ERROR_CATALOG];
|
|
123
|
+
if (!Array.isArray(list))
|
|
124
|
+
return undefined;
|
|
125
|
+
const valid = list.every((item) => item !== null &&
|
|
126
|
+
typeof item === 'object' &&
|
|
127
|
+
typeof item.code === 'string' &&
|
|
128
|
+
typeof item.status === 'number' &&
|
|
129
|
+
typeof item.message === 'string');
|
|
130
|
+
return valid ? list : undefined;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The code list of a `defineErrors` result, or of a module namespace that exports one
|
|
134
|
+
* (`await import('./src/shared/errors.ts')`): `[{ code, status, message, hint? }]`, frozen.
|
|
135
|
+
* Several exported results are joined in export order (one result exported twice counts once,
|
|
136
|
+
* a code already listed is not repeated). undefined when there is none.
|
|
137
|
+
*/
|
|
138
|
+
export function errorCatalog(value) {
|
|
139
|
+
const own = catalogOf(value);
|
|
140
|
+
if (own)
|
|
141
|
+
return own;
|
|
142
|
+
if (value === null || typeof value !== 'object')
|
|
143
|
+
return undefined;
|
|
144
|
+
const lists = [];
|
|
145
|
+
for (const key of Object.keys(value)) {
|
|
146
|
+
const list = catalogOf(value[key]);
|
|
147
|
+
if (list && !lists.includes(list))
|
|
148
|
+
lists.push(list);
|
|
149
|
+
}
|
|
150
|
+
if (lists.length <= 1)
|
|
151
|
+
return lists[0];
|
|
152
|
+
const seen = new Set();
|
|
153
|
+
const joined = [];
|
|
154
|
+
for (const list of lists)
|
|
155
|
+
for (const entry of list)
|
|
156
|
+
if (!seen.has(entry.code)) {
|
|
157
|
+
seen.add(entry.code);
|
|
158
|
+
joined.push(entry);
|
|
159
|
+
}
|
|
160
|
+
return Object.freeze(joined);
|
|
161
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type Describer } from '@dokebi/core';
|
|
2
|
+
import type { RouteTable } from './route-table.js';
|
|
3
|
+
/**
|
|
4
|
+
* The `core:describe` point of @dokebi/core 0.4.2, declared here by name (its identity) so this
|
|
5
|
+
* package keeps working with older cores, which never describe.
|
|
6
|
+
*/
|
|
7
|
+
export declare const describePoint: import("@dokebi/core").ContributionPoint<Describer>;
|
|
8
|
+
/** One described route (`dokebi describe` `routes[]`). */
|
|
9
|
+
export interface DescribedRoute {
|
|
10
|
+
/** `GET`, `POST`, … (several joined with commas). */
|
|
11
|
+
readonly method: string;
|
|
12
|
+
readonly url: string;
|
|
13
|
+
/** `config.id` (D-0077 A) when the route has one. */
|
|
14
|
+
readonly id?: string;
|
|
15
|
+
/** Fastify route constraints as text: `host`, the app of dokebi-app (`dokebiApp`), … */
|
|
16
|
+
readonly constraints?: Record<string, string>;
|
|
17
|
+
/** JSON Schemas of the route, as given (body, querystring, params, headers, response). */
|
|
18
|
+
readonly schema?: Record<string, unknown>;
|
|
19
|
+
/** Route `config` keys other plugins read (`auth`, `can`, `roles`, `csrf`, …). */
|
|
20
|
+
readonly config?: Record<string, unknown>;
|
|
21
|
+
/** `seal: false|true` of the route (D-0062); `"function"` when a function decides. */
|
|
22
|
+
readonly seal?: boolean | 'function';
|
|
23
|
+
/** True for the health routes of dokebi-web. */
|
|
24
|
+
readonly health?: true;
|
|
25
|
+
/** The plugin that added the route itself (D-0142), for example `dokebi-mcp`. */
|
|
26
|
+
readonly plugin?: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Route data as JSON: functions become `"[function]"`, regular expressions their source, symbol
|
|
30
|
+
* keys are left out, repeated objects `"[circular]"`.
|
|
31
|
+
*/
|
|
32
|
+
export declare function jsonValue(value: unknown, depth?: number, seen?: Set<object>): unknown;
|
|
33
|
+
/**
|
|
34
|
+
* Every route of `web.routes()` (D-0077 A) with what describe mode kept about it: its schema and
|
|
35
|
+
* the values of the config keys other plugins read. Called after `server.ready()`.
|
|
36
|
+
*/
|
|
37
|
+
export declare function describeRoutes(table: RouteTable): DescribedRoute[];
|
package/dist/describe.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Describe mode (D-0077 B): the routes of the app as data, for `dokebi describe --json`. The list
|
|
2
|
+
// is `web.routes()` (D-0077 A); the schema and config values of each route are kept by the route
|
|
3
|
+
// table only when `context.runtime.describing` is true (a normal start keeps nothing more), and
|
|
4
|
+
// read after `server.ready()`, so routes added inside plugin scopes are there too.
|
|
5
|
+
import { definePoint } from '@dokebi/core';
|
|
6
|
+
/**
|
|
7
|
+
* The `core:describe` point of @dokebi/core 0.4.2, declared here by name (its identity) so this
|
|
8
|
+
* package keeps working with older cores, which never describe.
|
|
9
|
+
*/
|
|
10
|
+
export const describePoint = definePoint('core:describe');
|
|
11
|
+
/** Fastify's own keys and dokebi-web's internal ones; `id`, `seal` and `health` are given apart. */
|
|
12
|
+
const HIDDEN = new Set(['url', 'method', 'dokebiHealth', 'dokebiSeal', 'id']);
|
|
13
|
+
const SCHEMA_PARTS = ['body', 'querystring', 'params', 'headers', 'response'];
|
|
14
|
+
const MAX_DEPTH = 24;
|
|
15
|
+
/**
|
|
16
|
+
* Route data as JSON: functions become `"[function]"`, regular expressions their source, symbol
|
|
17
|
+
* keys are left out, repeated objects `"[circular]"`.
|
|
18
|
+
*/
|
|
19
|
+
export function jsonValue(value, depth = 0, seen = new Set()) {
|
|
20
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
21
|
+
return value;
|
|
22
|
+
if (typeof value === 'number')
|
|
23
|
+
return Number.isFinite(value) ? value : String(value);
|
|
24
|
+
if (typeof value === 'bigint')
|
|
25
|
+
return value.toString();
|
|
26
|
+
if (typeof value === 'function')
|
|
27
|
+
return '[function]';
|
|
28
|
+
if (typeof value !== 'object')
|
|
29
|
+
return undefined;
|
|
30
|
+
if (value instanceof RegExp)
|
|
31
|
+
return value.toString();
|
|
32
|
+
if (value instanceof Date)
|
|
33
|
+
return value.toISOString();
|
|
34
|
+
if (depth >= MAX_DEPTH)
|
|
35
|
+
return '[deep]';
|
|
36
|
+
if (seen.has(value))
|
|
37
|
+
return '[circular]';
|
|
38
|
+
seen.add(value);
|
|
39
|
+
try {
|
|
40
|
+
if (Array.isArray(value))
|
|
41
|
+
return value.map((item) => jsonValue(item, depth + 1, seen) ?? null);
|
|
42
|
+
const result = {};
|
|
43
|
+
for (const [key, item] of Object.entries(value)) {
|
|
44
|
+
const copied = jsonValue(item, depth + 1, seen);
|
|
45
|
+
if (copied !== undefined)
|
|
46
|
+
result[key] = copied;
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
seen.delete(value);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Every route of `web.routes()` (D-0077 A) with what describe mode kept about it: its schema and
|
|
56
|
+
* the values of the config keys other plugins read. Called after `server.ready()`.
|
|
57
|
+
*/
|
|
58
|
+
export function describeRoutes(table) {
|
|
59
|
+
const details = table.details() ?? [];
|
|
60
|
+
return table.routes().map((entry, index) => describeRoute(entry, details[index]));
|
|
61
|
+
}
|
|
62
|
+
function describeRoute(entry, details) {
|
|
63
|
+
const config = details?.config ?? {};
|
|
64
|
+
const schema = {};
|
|
65
|
+
const given = details?.schema;
|
|
66
|
+
if (given !== null && typeof given === 'object')
|
|
67
|
+
for (const part of SCHEMA_PARTS) {
|
|
68
|
+
const value = given[part];
|
|
69
|
+
if (value !== undefined)
|
|
70
|
+
schema[part] = jsonValue(value);
|
|
71
|
+
}
|
|
72
|
+
const keys = {};
|
|
73
|
+
for (const name of entry.configKeys) {
|
|
74
|
+
if (HIDDEN.has(name))
|
|
75
|
+
continue;
|
|
76
|
+
const copied = jsonValue(config[name]);
|
|
77
|
+
if (copied !== undefined)
|
|
78
|
+
keys[name] = copied;
|
|
79
|
+
}
|
|
80
|
+
const seal = config.dokebiSeal;
|
|
81
|
+
return {
|
|
82
|
+
method: entry.method,
|
|
83
|
+
url: entry.url,
|
|
84
|
+
...(entry.id === undefined ? {} : { id: entry.id }),
|
|
85
|
+
...(Object.keys(entry.constraints).length ? { constraints: { ...entry.constraints } } : {}),
|
|
86
|
+
...(Object.keys(schema).length ? { schema } : {}),
|
|
87
|
+
...(Object.keys(keys).length ? { config: keys } : {}),
|
|
88
|
+
...(typeof seal === 'boolean'
|
|
89
|
+
? { seal }
|
|
90
|
+
: typeof seal === 'function'
|
|
91
|
+
? { seal: 'function' }
|
|
92
|
+
: {}),
|
|
93
|
+
...(config.dokebiHealth === true ? { health: true } : {}),
|
|
94
|
+
...(entry.plugin === undefined ? {} : { plugin: entry.plugin }),
|
|
95
|
+
};
|
|
96
|
+
}
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
|
|
2
2
|
import { type WebFieldError } from './responses.js';
|
|
3
3
|
/** Codes of the errors this plugin throws or answers with (`WebError`, `plugin: 'dokebi-web'`). */
|
|
4
|
-
export type WebErrorCode = 'INVALID_ENTRY' | 'INVALID_ROUTE' | 'INVALID_HOOK' | 'INVALID_ARGUMENT' | 'INVALID_EXTENSION_RESULT' | 'FROZEN' | 'CLOSED' | 'FORM_BODY_DISABLED' | 'FORM_BODY_TOO_MANY_FIELDS' | 'SEAL_PROVIDER_MISSING' | 'SEAL_PROVIDER_INVALID' | 'SEAL_REQUIRED' | 'SEAL_BODY_REFUSED' | 'SEAL_BUSY' | 'SEAL_BODY_NOT_JSON' | 'SEAL_STREAM_UNSUPPORTED' | 'VALIDATION_FAILED' | 'NOT_FOUND';
|
|
4
|
+
export type WebErrorCode = 'INVALID_ENTRY' | 'INVALID_ROUTE' | 'INVALID_HOOK' | 'INVALID_ARGUMENT' | 'INVALID_ROUTE_CONFIG' | 'DUPLICATE_ROUTE_ID' | 'INVALID_EXTENSION_RESULT' | 'INVALID_ERROR_TRANSLATOR' | 'FROZEN' | 'CLOSED' | 'FORM_BODY_DISABLED' | 'FORM_BODY_TOO_MANY_FIELDS' | 'FORM_BODY_INVALID' | 'SEAL_PROVIDER_MISSING' | 'SEAL_PROVIDER_INVALID' | 'SEAL_REQUIRED' | 'SEAL_BODY_REFUSED' | 'SEAL_BUSY' | 'SEAL_NONCE_STORE_UNAVAILABLE' | 'SEAL_NONCES_LOST' | 'SEAL_BODY_NOT_JSON' | 'SEAL_STREAM_UNSUPPORTED' | 'VALIDATION_FAILED' | 'NOT_FOUND' | 'ROUTE_APP_UNAVAILABLE' | 'ROUTE_APP_UNKNOWN' | 'ROUTE_APP_CONFLICT' | 'OVERLOADED' | 'REQUEST_TIMEOUT';
|
|
5
5
|
/**
|
|
6
6
|
* Errors of @dokebi/web; compare `code`, not the class (another installed copy may throw).
|
|
7
7
|
* Request errors carry the HTTP `status` dokebi-web answers with, and a `hint` for the client.
|