@plinthjs/http 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +157 -2
- package/dist/index.cjs +3082 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1626 -0
- package/dist/index.d.ts +1626 -0
- package/dist/index.js +3052 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,1626 @@
|
|
|
1
|
+
import { ServerResponse, IncomingMessage, Server } from 'node:http';
|
|
2
|
+
import { Collection } from '@plinthjs/support';
|
|
3
|
+
import { Newable, Container } from '@plinthjs/core';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `Controller` — the optional convention base for `[Controller, method]` route actions. Controllers are plain classes resolved through the `@plinthjs/core`
|
|
7
|
+
* container, so extending this is not required; it gives a shared, stable base for app-wide
|
|
8
|
+
* controller helpers and a clear type. Route/group middleware is declared on the route, not here.
|
|
9
|
+
*/
|
|
10
|
+
declare abstract class Controller {
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A registered response macro: an arbitrary builder invoked through {@link Response.callMacro}. */
|
|
14
|
+
type ResponseMacro = (...args: never[]) => Response;
|
|
15
|
+
/**
|
|
16
|
+
* A bag of flash data queued onto a {@link Response} by {@link Response.with}. The session layer
|
|
17
|
+
* reads {@link Response.flashes} after the response is built and flashes each key for the next
|
|
18
|
+
* request; this keeps `@plinthjs/http` free of any session dependency.
|
|
19
|
+
*/
|
|
20
|
+
type FlashBag = Record<string, unknown>;
|
|
21
|
+
/** A chunk a streaming response may yield: text or raw bytes. */
|
|
22
|
+
type StreamChunk = string | Uint8Array;
|
|
23
|
+
/**
|
|
24
|
+
* The body source accepted by {@link Response.stream}: an iterable / async iterable of chunks, or a
|
|
25
|
+
* factory (e.g. a generator function) returning one. A factory is invoked lazily, once, when the
|
|
26
|
+
* response is flushed.
|
|
27
|
+
*/
|
|
28
|
+
type StreamSource = Iterable<StreamChunk> | AsyncIterable<StreamChunk> | (() => Iterable<StreamChunk> | AsyncIterable<StreamChunk>);
|
|
29
|
+
/** A JSON streaming source: rows to stream as one array, or an object whose values may be iterables. */
|
|
30
|
+
type JsonStreamData = Iterable<unknown> | AsyncIterable<unknown> | Record<string, unknown>;
|
|
31
|
+
/** Options for {@link Response.cookie} — the common `Set-Cookie` attributes. */
|
|
32
|
+
interface CookieOptions {
|
|
33
|
+
/** `Max-Age` in seconds. */
|
|
34
|
+
maxAge?: number;
|
|
35
|
+
/** `Expires` date. */
|
|
36
|
+
expires?: Date;
|
|
37
|
+
/** `Path` attribute. Defaults to `/`. */
|
|
38
|
+
path?: string;
|
|
39
|
+
/** `Domain` attribute. */
|
|
40
|
+
domain?: string;
|
|
41
|
+
/** `Secure` flag. */
|
|
42
|
+
secure?: boolean;
|
|
43
|
+
/** `HttpOnly` flag. */
|
|
44
|
+
httpOnly?: boolean;
|
|
45
|
+
/** `SameSite` policy. */
|
|
46
|
+
sameSite?: 'Strict' | 'Lax' | 'None';
|
|
47
|
+
}
|
|
48
|
+
declare class Response {
|
|
49
|
+
/** The HTTP status code. */
|
|
50
|
+
status: number;
|
|
51
|
+
/** The response headers (canonical-ish casing as set). */
|
|
52
|
+
headers: Record<string, string>;
|
|
53
|
+
/** The response body, already serialized to a string (or `null` for no body). */
|
|
54
|
+
body: string | null;
|
|
55
|
+
/** Any `Set-Cookie` header values, kept separate so multiple cookies survive serialization. */
|
|
56
|
+
private setCookies;
|
|
57
|
+
/**
|
|
58
|
+
* The encoding used to flush {@link Response.body}. Text bodies are UTF-8; binary file bodies are
|
|
59
|
+
* read and written as `'binary'` (latin1) so every byte survives the string round-trip intact and
|
|
60
|
+
* matches the `Content-Length` set by {@link Response.file}/{@link Response.download}.
|
|
61
|
+
*/
|
|
62
|
+
private bodyEncoding;
|
|
63
|
+
/** Flash intent queued by {@link Response.with}; drained by the session layer. */
|
|
64
|
+
private flashData;
|
|
65
|
+
/** The streaming body source, when this is a streamed response (see {@link Response.stream}). */
|
|
66
|
+
private streamSource;
|
|
67
|
+
/** The registered response macros, shared across all instances (the `Response::macro` registry). */
|
|
68
|
+
private static readonly macros;
|
|
69
|
+
private constructor();
|
|
70
|
+
/** Begin building a response with an optional body and status. The `response()` helper equivalent. */
|
|
71
|
+
static make(body?: string | null, status?: number): Response;
|
|
72
|
+
/** Build a JSON response, serializing `data` and setting `Content-Type`. The `response()->json()` equivalent. */
|
|
73
|
+
static json(data: unknown, status?: number): Response;
|
|
74
|
+
/** Build a plain-text response. */
|
|
75
|
+
static text(body: string, status?: number): Response;
|
|
76
|
+
/** Build an HTML response. */
|
|
77
|
+
static html(body: string, status?: number): Response;
|
|
78
|
+
/** Build an empty `204 No Content` response. The `response()->noContent()` equivalent. */
|
|
79
|
+
static noContent(status?: number): Response;
|
|
80
|
+
/** Build a redirect to `url`. The `redirect()` helper equivalent. */
|
|
81
|
+
static redirect(url: string, status?: number): Response;
|
|
82
|
+
/** Build a redirect to `url`. The `redirect()->to()` / `Redirect::to()` equivalent. */
|
|
83
|
+
static redirectTo(url: string, status?: number): Response;
|
|
84
|
+
/**
|
|
85
|
+
* Build a redirect back to the previous URL, falling back to `fallback` (default `/`) when no
|
|
86
|
+
* referer is known. The `back()` / `redirect()->back()` equivalent.
|
|
87
|
+
*
|
|
88
|
+
* As a static this has no request in scope, so it relies on `fallback`; middleware that knows the
|
|
89
|
+
* incoming `Referer` should pass it explicitly.
|
|
90
|
+
*/
|
|
91
|
+
static back(fallback?: string, status?: number): Response;
|
|
92
|
+
/**
|
|
93
|
+
* Build a response that serves the file at `path` inline (no download prompt), inferring
|
|
94
|
+
* `Content-Type` from the extension and setting `Content-Length`. The `response()->file()`
|
|
95
|
+
* equivalent. The file is read synchronously into the body.
|
|
96
|
+
*/
|
|
97
|
+
static file(filePath: string, headers?: Record<string, string>): Response;
|
|
98
|
+
/**
|
|
99
|
+
* Build a download response (`Content-Disposition: attachment`) for the file at `path`, using
|
|
100
|
+
* `name` as the download filename (defaulting to the path's basename). The `response()->download()`
|
|
101
|
+
* equivalent. The file is read synchronously into the body.
|
|
102
|
+
*/
|
|
103
|
+
static download(filePath: string, name?: string, headers?: Record<string, string>): Response;
|
|
104
|
+
/**
|
|
105
|
+
* Build a streamed response: `source` (an iterable, async iterable, or a generator/factory
|
|
106
|
+
* returning one) is consumed chunk by chunk as the response is flushed, each chunk written to the
|
|
107
|
+
* client as it yields — the `response()->stream()` equivalent. No `Content-Length` is set, so
|
|
108
|
+
* Node serves it with chunked transfer encoding. The kernel/server adapter flushes streamed
|
|
109
|
+
* responses via {@link Response.writeStreamTo}.
|
|
110
|
+
*/
|
|
111
|
+
static stream(source: StreamSource, status?: number, headers?: Record<string, string>): Response;
|
|
112
|
+
/**
|
|
113
|
+
* Build a streamed download: like {@link Response.stream} but with
|
|
114
|
+
* `Content-Disposition: attachment` for `filename` and a default `application/octet-stream`
|
|
115
|
+
* content type (override via `headers`). The `response()->streamDownload()` equivalent.
|
|
116
|
+
*/
|
|
117
|
+
static streamDownload(source: StreamSource, filename: string, headers?: Record<string, string>): Response;
|
|
118
|
+
/**
|
|
119
|
+
* Build a streamed JSON response — the `response()->streamJson()` equivalent. An iterable (or
|
|
120
|
+
* async iterable) of rows is streamed as one JSON array, each row serialized as it yields; an
|
|
121
|
+
* object is emitted key by key with iterable values streamed as arrays and plain values encoded
|
|
122
|
+
* in place. Useful for serializing large result sets without buffering them.
|
|
123
|
+
*/
|
|
124
|
+
static streamJson(data: JsonStreamData, status?: number): Response;
|
|
125
|
+
/** Whether this is a streamed response (flush it with {@link Response.writeStreamTo}). */
|
|
126
|
+
isStream(): boolean;
|
|
127
|
+
/**
|
|
128
|
+
* Register a reusable response builder under `name`. The `Response::macro()` equivalent —
|
|
129
|
+
* application code installs a named factory once and invokes it via {@link Response.callMacro}
|
|
130
|
+
* (`Response.callMacro('caps', text)`). Re-registering a name overwrites the previous macro.
|
|
131
|
+
*/
|
|
132
|
+
static macro(name: string, fn: ResponseMacro): void;
|
|
133
|
+
/** Whether a macro named `name` has been registered. The `Response::hasMacro()` equivalent. */
|
|
134
|
+
static hasMacro(name: string): boolean;
|
|
135
|
+
/** Install many macros at once from a plain object of builders. The `Macroable::mixin()` analog. */
|
|
136
|
+
static mixin(macros: Record<string, ResponseMacro>): void;
|
|
137
|
+
/**
|
|
138
|
+
* Invoke a previously {@link Response.macro registered} macro by name, forwarding `args` and
|
|
139
|
+
* returning the {@link Response} it builds. Throws when no macro is registered under `name`. Typed pragmatically: callers cast
|
|
140
|
+
* `args` to the macro's expected parameters.
|
|
141
|
+
*/
|
|
142
|
+
static callMacro(name: string, ...args: never[]): Response;
|
|
143
|
+
/** Set the status code. */
|
|
144
|
+
setStatus(code: number): this;
|
|
145
|
+
/** Set a single header. The `->header()` equivalent. */
|
|
146
|
+
header(name: string, value: string): this;
|
|
147
|
+
/** Merge a header map onto the response. The `->withHeaders()` equivalent. */
|
|
148
|
+
withHeaders(headers: Record<string, string>): this;
|
|
149
|
+
/** Serialize `data` to JSON, set the body and `Content-Type`, and (optionally) the status. */
|
|
150
|
+
json(data: unknown, status?: number): this;
|
|
151
|
+
/** Set a plain-text body and `Content-Type`. */
|
|
152
|
+
text(body: string): this;
|
|
153
|
+
/** Set an HTML body and `Content-Type`. */
|
|
154
|
+
html(body: string): this;
|
|
155
|
+
/** Clear the body and set a no-content status. */
|
|
156
|
+
noContent(status?: number): this;
|
|
157
|
+
/** Turn this into a redirect to `url` with a `Location` header. */
|
|
158
|
+
redirect(url: string, status?: number): this;
|
|
159
|
+
/** Alias of {@link Response.redirect} reading as `redirect()->to()`. */
|
|
160
|
+
redirectTo(url: string, status?: number): this;
|
|
161
|
+
/** Retarget this redirect at `fallback` (the previous-URL fallback when no referer is known). */
|
|
162
|
+
back(fallback?: string, status?: number): this;
|
|
163
|
+
/**
|
|
164
|
+
* Queue a flash value (or a whole bag) to survive to the next request. The conventional
|
|
165
|
+
* `redirect()->with('status', 'Saved!')` equivalent: a single `key`/`value` flashes that pair,
|
|
166
|
+
* while passing an object as the sole argument merges every entry. Returns `this` to chain.
|
|
167
|
+
*
|
|
168
|
+
* `@plinthjs/http` has no session, so the data is held as response state ({@link Response.flashes});
|
|
169
|
+
* the session middleware reads and flashes it after the response is built.
|
|
170
|
+
*/
|
|
171
|
+
with(key: string, value: unknown): this;
|
|
172
|
+
with(data: FlashBag): this;
|
|
173
|
+
/**
|
|
174
|
+
* Flash an `input` bag for repopulating a form after a redirect. The `redirect()->withInput()`
|
|
175
|
+
* equivalent: the bag is stored under the `input` flash key.
|
|
176
|
+
*/
|
|
177
|
+
withInput(input: Record<string, unknown>): this;
|
|
178
|
+
/**
|
|
179
|
+
* Flash a validation `errors` bag. The `redirect()->withErrors()` equivalent: the bag is stored
|
|
180
|
+
* under the `errors` flash key for the next request's view.
|
|
181
|
+
*/
|
|
182
|
+
withErrors(errors: Record<string, unknown>): this;
|
|
183
|
+
/** The queued flash intent (a copy) for the session layer to consume. */
|
|
184
|
+
flashes(): FlashBag;
|
|
185
|
+
/** Read a single queued flash value by key, or `undefined` when absent. */
|
|
186
|
+
getFlash<T = unknown>(key: string): T | undefined;
|
|
187
|
+
/** Queue a `Set-Cookie` header. Multiple calls accumulate distinct cookies. */
|
|
188
|
+
cookie(name: string, value: string, options?: CookieOptions): this;
|
|
189
|
+
/** The queued `Set-Cookie` header values (a copy). */
|
|
190
|
+
cookies(): string[];
|
|
191
|
+
/** Write the status, headers, and cookies (everything before the body) to `res`. */
|
|
192
|
+
private writeHead;
|
|
193
|
+
/**
|
|
194
|
+
* Flush this response to a Node {@link ServerResponse}: status, headers, cookies, then body.
|
|
195
|
+
* Streamed responses ({@link Response.stream}) must be flushed with the async
|
|
196
|
+
* {@link Response.writeStreamTo} instead — calling `writeTo` on one throws so a stream is never
|
|
197
|
+
* silently dropped.
|
|
198
|
+
*/
|
|
199
|
+
writeTo(res: ServerResponse): void;
|
|
200
|
+
/**
|
|
201
|
+
* Flush a streamed response to a Node {@link ServerResponse}: status, headers, and cookies first,
|
|
202
|
+
* then each chunk the {@link StreamSource} yields is written as it arrives (respecting
|
|
203
|
+
* backpressure via `drain`), and the response is ended when the source completes. Falls back to
|
|
204
|
+
* {@link Response.writeTo} semantics when this response has no stream.
|
|
205
|
+
*/
|
|
206
|
+
writeStreamTo(res: ServerResponse): Promise<void>;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The constructor inputs for an {@link UploadedFile}; mirrors a parsed multipart file part. */
|
|
210
|
+
interface UploadedFileInit {
|
|
211
|
+
/** The client-supplied original filename (`filename="…"`). */
|
|
212
|
+
clientOriginalName: string;
|
|
213
|
+
/** The declared `Content-Type` of the part. */
|
|
214
|
+
mimeType: string;
|
|
215
|
+
/** The raw uploaded bytes. */
|
|
216
|
+
content: Buffer;
|
|
217
|
+
}
|
|
218
|
+
declare class UploadedFile {
|
|
219
|
+
/** The original filename the client supplied. The `getClientOriginalName()` value. */
|
|
220
|
+
readonly clientOriginalName: string;
|
|
221
|
+
/** The declared MIME type of the upload. */
|
|
222
|
+
readonly mimeType: string;
|
|
223
|
+
/** The size of the uploaded content in bytes. */
|
|
224
|
+
readonly size: number;
|
|
225
|
+
/** The uploaded bytes, held in memory. */
|
|
226
|
+
private readonly content;
|
|
227
|
+
constructor(init: UploadedFileInit);
|
|
228
|
+
/** The raw uploaded bytes. The `get()` content accessor. */
|
|
229
|
+
get(): Buffer;
|
|
230
|
+
/** The raw uploaded bytes — an alias for {@link UploadedFile.get} reading more naturally as bytes. */
|
|
231
|
+
buffer(): Buffer;
|
|
232
|
+
/** The client-supplied original filename. The `$file->getClientOriginalName()` equivalent. */
|
|
233
|
+
getClientOriginalName(): string;
|
|
234
|
+
/**
|
|
235
|
+
* The file extension derived from the client original name (lower-cased, no leading dot), or `''`
|
|
236
|
+
* when the name has none. The `$file->getClientOriginalExtension()` equivalent.
|
|
237
|
+
*/
|
|
238
|
+
getClientOriginalExtension(): string;
|
|
239
|
+
/** The declared MIME type of the upload. The `$file->getMimeType()` equivalent. */
|
|
240
|
+
getMimeType(): string;
|
|
241
|
+
/** The size of the uploaded content in bytes. The `$file->getSize()` equivalent. */
|
|
242
|
+
getSize(): number;
|
|
243
|
+
/**
|
|
244
|
+
* Whether the upload is valid — here, simply that it carries a non-empty filename. Mirrors the
|
|
245
|
+
* `$file->isValid()` predicate at this layer (no PHP upload-error codes exist in Node).
|
|
246
|
+
*/
|
|
247
|
+
isValid(): boolean;
|
|
248
|
+
/**
|
|
249
|
+
* Write the upload to `directory` under a generated unique name, creating the directory as needed,
|
|
250
|
+
* and return the full path written. The `$file->store('dir')` equivalent (sans disk abstraction).
|
|
251
|
+
*/
|
|
252
|
+
store(directory: string): string;
|
|
253
|
+
/**
|
|
254
|
+
* Write the upload to `directory` under `name`, creating the directory as needed, and return the
|
|
255
|
+
* full path written. The `$file->storeAs('dir', 'name')` equivalent.
|
|
256
|
+
*/
|
|
257
|
+
storeAs(directory: string, name: string): string;
|
|
258
|
+
/**
|
|
259
|
+
* Write the upload to the exact file path `destination`, creating its parent directory as needed,
|
|
260
|
+
* and return `destination`. The `$file->move()` equivalent — the documented filesystem seam.
|
|
261
|
+
*/
|
|
262
|
+
move(destination: string): string;
|
|
263
|
+
/**
|
|
264
|
+
* A unique storage filename preserving the original extension — a timestamp/random base, the way
|
|
265
|
+
* the conventional `hashName()` produces a collision-resistant name. Used by {@link UploadedFile.store}.
|
|
266
|
+
*/
|
|
267
|
+
hashName(): string;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* `Request` — an immutable wrapper around an inbound HTTP request, the conventional
|
|
272
|
+
*. It normalizes the method, URL, headers, cookies, and a
|
|
273
|
+
* parsed body, and exposes the familiar accessor surface (`input`, `only`, `query`, `bearerToken`,
|
|
274
|
+
* `wantsJson`, …). Instances are immutable: {@link Request.withParams} returns a fresh copy with
|
|
275
|
+
* route parameters attached rather than mutating in place.
|
|
276
|
+
*/
|
|
277
|
+
|
|
278
|
+
/** A JSON-ish value the body parser may produce. */
|
|
279
|
+
type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
280
|
+
[key: string]: JsonValue;
|
|
281
|
+
};
|
|
282
|
+
/** The shape used to construct a {@link Request} synthetically (tests build these directly). */
|
|
283
|
+
interface RequestInit {
|
|
284
|
+
/** HTTP verb; normalized to upper-case. Defaults to `GET`. */
|
|
285
|
+
method?: string;
|
|
286
|
+
/** The full request target, e.g. `/users?page=2`. Defaults to `/`. */
|
|
287
|
+
url?: string;
|
|
288
|
+
/** Header map; names are lower-cased on the way in. */
|
|
289
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
290
|
+
/** The raw request body (already-read string), if any. */
|
|
291
|
+
body?: string;
|
|
292
|
+
/**
|
|
293
|
+
* The raw request body as bytes, used for binary-safe `multipart/form-data` parsing. When omitted
|
|
294
|
+
* it is derived from {@link RequestInit.body} as utf8, so a string-only construction still yields a
|
|
295
|
+
* usable buffer. The Node adapter supplies the original {@link Buffer} here so file bytes survive.
|
|
296
|
+
*/
|
|
297
|
+
bodyBuffer?: Buffer;
|
|
298
|
+
/**
|
|
299
|
+
* The request host (e.g. `acme.myapp.com`), used by host/subdomain routing. When omitted it is
|
|
300
|
+
* derived from the `Host` header. An explicit value here takes precedence over the header.
|
|
301
|
+
*/
|
|
302
|
+
host?: string;
|
|
303
|
+
}
|
|
304
|
+
/** Options for {@link Request.fromNode}. */
|
|
305
|
+
interface FromNodeOptions {
|
|
306
|
+
/**
|
|
307
|
+
* The largest request body, in bytes, {@link Request.fromNode} will buffer before rejecting with
|
|
308
|
+
* a {@link PayloadTooLargeHttpException}. Defaults to 1 MiB. An oversized `Content-Length` is
|
|
309
|
+
* refused before a single byte is read; a chunked body is aborted as soon as the accumulated
|
|
310
|
+
* size crosses the cap, so an attacker can never make the process hold more than the limit.
|
|
311
|
+
*/
|
|
312
|
+
maxBodyBytes?: number;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* A `413 Payload Too Large`, thrown by {@link Request.fromNode} when an inbound body exceeds the
|
|
316
|
+
* configured cap — either declared up front by `Content-Length` or discovered while accumulating
|
|
317
|
+
* chunks. The server adapter answers it with a `413` and closes the connection (the unread
|
|
318
|
+
* remainder of the body would poison keep-alive reuse).
|
|
319
|
+
*/
|
|
320
|
+
declare class PayloadTooLargeHttpException extends HttpException {
|
|
321
|
+
constructor(message?: string);
|
|
322
|
+
}
|
|
323
|
+
declare class Request {
|
|
324
|
+
private _method;
|
|
325
|
+
/** The raw request target as received (`/users?page=2`); URL work happens lazily off it. */
|
|
326
|
+
private _target;
|
|
327
|
+
/** Memoized WHATWG parse of {@link Request._target}; built only when normalization is needed. */
|
|
328
|
+
private _url;
|
|
329
|
+
/** Memoized pathname; a {@link isPlainPath plain} target resolves by slicing, sparing `new URL`. */
|
|
330
|
+
private _pathname;
|
|
331
|
+
private _host;
|
|
332
|
+
/** The host as received (port included, if any) — backs {@link Request.httpHost}. */
|
|
333
|
+
private _httpHost;
|
|
334
|
+
/** The matched route's name, attached by the kernel after a successful match (for `routeIs`). */
|
|
335
|
+
private _routeName;
|
|
336
|
+
private _headers;
|
|
337
|
+
/** Lazily-decoded utf8 view of {@link Request._rawBuffer} (eager when constructed from a string). */
|
|
338
|
+
private _rawBody;
|
|
339
|
+
private _rawBuffer;
|
|
340
|
+
/** Memoized parsed body; `undefined` until the first input access forces the parse. */
|
|
341
|
+
private _parsedBody;
|
|
342
|
+
/** Memoized result of parsing a `multipart/form-data` body; `undefined` until first accessed. */
|
|
343
|
+
private _multipart;
|
|
344
|
+
private _routeParams;
|
|
345
|
+
private _attributes;
|
|
346
|
+
private _boundModels;
|
|
347
|
+
private _mergedInput;
|
|
348
|
+
/**
|
|
349
|
+
* Construct from already-resolved primitives. Prefer {@link Request.fromNode} for a live
|
|
350
|
+
* {@link IncomingMessage}; this constructor is what synthetic tests use directly.
|
|
351
|
+
*/
|
|
352
|
+
constructor(init?: RequestInit);
|
|
353
|
+
/**
|
|
354
|
+
* Build a {@link Request} from a live Node {@link IncomingMessage}, draining and parsing the body.
|
|
355
|
+
* The body is buffered
|
|
356
|
+
* up to {@link FromNodeOptions.maxBodyBytes} (default 1 MiB); anything larger rejects with a
|
|
357
|
+
* {@link PayloadTooLargeHttpException} without buffering past the cap.
|
|
358
|
+
*/
|
|
359
|
+
static fromNode(req: IncomingMessage, options?: FromNodeOptions): Promise<Request>;
|
|
360
|
+
/** The memoized WHATWG parse of the request target, for the paths that need normalization. */
|
|
361
|
+
private urlObject;
|
|
362
|
+
/** The URL-normalized pathname (untrimmed), via the plain-target fast path when possible. */
|
|
363
|
+
private pathname;
|
|
364
|
+
/** The URL-normalized search component (`?…` or the empty string). */
|
|
365
|
+
private searchString;
|
|
366
|
+
/** The raw body as utf8 text, decoded from the byte buffer on first use and memoized. */
|
|
367
|
+
private rawBody;
|
|
368
|
+
/** Parse the body on first access and memoize; clones share the memo (the body is immutable). */
|
|
369
|
+
private parsedBody;
|
|
370
|
+
/** Parse the raw body according to the `Content-Type`, falling back to an empty object. */
|
|
371
|
+
private parseBody;
|
|
372
|
+
/** Whether the `Content-Type` declares a `multipart/form-data` body. */
|
|
373
|
+
private isMultipart;
|
|
374
|
+
/**
|
|
375
|
+
* Parse the `multipart/form-data` body once and memoize it. Returns an empty result for any
|
|
376
|
+
* non-multipart request (so json/urlencoded handling is never disturbed) and is best-effort on a
|
|
377
|
+
* malformed body. The parse reads the binary-safe {@link Request._rawBuffer}, not the utf8 string.
|
|
378
|
+
*/
|
|
379
|
+
private multipart;
|
|
380
|
+
/** The HTTP verb (upper-case). The `$request->method()` equivalent. */
|
|
381
|
+
method(): string;
|
|
382
|
+
/** Whether the request uses the given verb (case-insensitive). The `$request->isMethod()` equivalent. */
|
|
383
|
+
isMethod(method: string): boolean;
|
|
384
|
+
/** The path with no query string, e.g. `/users`. The `$request->path()` equivalent. */
|
|
385
|
+
path(): string;
|
|
386
|
+
/** The full request target including any query string. The `$request->fullUrl()` equivalent. */
|
|
387
|
+
url(): string;
|
|
388
|
+
/**
|
|
389
|
+
* The request host without any port (e.g. `acme.myapp.com`), from the constructor `host` or the
|
|
390
|
+
* `Host` header, or `undefined` when neither is present. The `$request->host()` equivalent, used
|
|
391
|
+
* by the {@link import('./router').Router}'s subdomain/domain routing.
|
|
392
|
+
*/
|
|
393
|
+
host(): string | undefined;
|
|
394
|
+
/**
|
|
395
|
+
* The request host **including** any port (e.g. `acme.myapp.com:8080`), as received from the
|
|
396
|
+
* constructor `host` or the `Host` header. The `$request->httpHost()` equivalent; `undefined`
|
|
397
|
+
* when no host is known (a synthetic request without a `Host` header).
|
|
398
|
+
*/
|
|
399
|
+
httpHost(): string | undefined;
|
|
400
|
+
/**
|
|
401
|
+
* The scheme plus host (e.g. `https://acme.myapp.com:8080`) — the `$request->schemeAndHttpHost()`
|
|
402
|
+
* equivalent. The scheme is read from the first `X-Forwarded-Proto` hop, defaulting to `http`
|
|
403
|
+
* (Plinth's adapter sits on plain `node:http`; a TLS-terminating proxy sets the header).
|
|
404
|
+
* `undefined` when no host is known.
|
|
405
|
+
*/
|
|
406
|
+
schemeAndHttpHost(): string | undefined;
|
|
407
|
+
/** The request scheme: the first `X-Forwarded-Proto` hop, defaulting to `http`. */
|
|
408
|
+
private scheme;
|
|
409
|
+
/**
|
|
410
|
+
* Whether the request arrived over HTTPS — the `$request->isSecure()` equivalent. Reads the first
|
|
411
|
+
* `X-Forwarded-Proto` hop (Plinth sits on plain `node:http` behind a TLS-terminating proxy), so it
|
|
412
|
+
* is the trust-proxy signal a `secure` cookie or HSTS header should gate on.
|
|
413
|
+
*/
|
|
414
|
+
isSecure(): boolean;
|
|
415
|
+
/**
|
|
416
|
+
* The full URL including the query string — `scheme://host/path?query` when the host is known,
|
|
417
|
+
* otherwise just `/path?query` (matching {@link Request.url} for host-less synthetic requests).
|
|
418
|
+
* The `$request->fullUrl()` equivalent.
|
|
419
|
+
*/
|
|
420
|
+
fullUrl(): string;
|
|
421
|
+
/**
|
|
422
|
+
* The {@link Request.fullUrl} with `query` merged into the current query string (existing keys
|
|
423
|
+
* are overridden). The `$request->fullUrlWithQuery()` equivalent.
|
|
424
|
+
*/
|
|
425
|
+
fullUrlWithQuery(query: Record<string, string | number>): string;
|
|
426
|
+
/**
|
|
427
|
+
* The {@link Request.fullUrl} with the given query `keys` removed. The
|
|
428
|
+
* `$request->fullUrlWithoutQuery()` equivalent.
|
|
429
|
+
*/
|
|
430
|
+
fullUrlWithoutQuery(keys: string[]): string;
|
|
431
|
+
/** Reassemble the full URL from the current scheme/host/path plus an edited query bag. */
|
|
432
|
+
private rebuildFullUrl;
|
|
433
|
+
/**
|
|
434
|
+
* Whether the request path matches any of the wildcard `patterns` — `*` matches any run of
|
|
435
|
+
* characters. Patterns are matched against the path **without** its leading slash (so
|
|
436
|
+
* `req.is('admin/*')` matches `/admin/users`), mirroring `$request->is()`.
|
|
437
|
+
*/
|
|
438
|
+
is(...patterns: string[]): boolean;
|
|
439
|
+
/**
|
|
440
|
+
* Whether the matched route's name matches any of the wildcard `patterns` (e.g.
|
|
441
|
+
* `req.routeIs('users.*')`). The kernel attaches the name after a successful match via
|
|
442
|
+
* {@link Request.withRouteName}; `false` for an unnamed or unmatched route. The
|
|
443
|
+
* `$request->routeIs()` equivalent.
|
|
444
|
+
*/
|
|
445
|
+
routeIs(...patterns: string[]): boolean;
|
|
446
|
+
/**
|
|
447
|
+
* Whether {@link Request.fullUrl} matches any of the wildcard `patterns`. The
|
|
448
|
+
* `$request->fullUrlIs()` equivalent.
|
|
449
|
+
*/
|
|
450
|
+
fullUrlIs(...patterns: string[]): boolean;
|
|
451
|
+
/**
|
|
452
|
+
* Read a query parameter, or every parameter when `key` is omitted. The `$request->query()`
|
|
453
|
+
* equivalent.
|
|
454
|
+
*/
|
|
455
|
+
query(): Record<string, string>;
|
|
456
|
+
query(key: string, def?: string): string | undefined;
|
|
457
|
+
/** Every query parameter as a plain object. The `$request->query()` (no-arg) equivalent. */
|
|
458
|
+
queryAll(): Record<string, string>;
|
|
459
|
+
/** Read a single header (case-insensitive), or `def` when absent. The `$request->header()` equivalent. */
|
|
460
|
+
header(name: string, def?: string): string | undefined;
|
|
461
|
+
/** Every header as a plain object (lower-cased names). The `$request->headers->all()` equivalent. */
|
|
462
|
+
headers(): Record<string, string>;
|
|
463
|
+
/**
|
|
464
|
+
* The merged input bag: query parameters overlaid with the parsed body (body wins), then with any
|
|
465
|
+
* values supplied via {@link Request.merge}/{@link Request.mergeIfMissing} (merged values win).
|
|
466
|
+
*/
|
|
467
|
+
all(): Record<string, unknown>;
|
|
468
|
+
/** Read a merged input value by key, or `def` when absent. The `$request->input()` equivalent. */
|
|
469
|
+
input<T = unknown>(key: string, def?: T): T | undefined;
|
|
470
|
+
/** Only the named keys from the merged input. The `$request->only()` equivalent. */
|
|
471
|
+
only(keys: string[]): Record<string, unknown>;
|
|
472
|
+
/** Every merged input value except the named keys. The `$request->except()` equivalent. */
|
|
473
|
+
except(keys: string[]): Record<string, unknown>;
|
|
474
|
+
/** Whether the merged input contains the key. The `$request->has()` equivalent. */
|
|
475
|
+
has(key: string): boolean;
|
|
476
|
+
/** Every merged-input key. The `$request->keys()` equivalent. */
|
|
477
|
+
keys(): string[];
|
|
478
|
+
/**
|
|
479
|
+
* Read an input value coerced to a boolean — `true`/`1`/`'1'`/`'true'`/`'on'`/`'yes'` (strings
|
|
480
|
+
* case-insensitive) are `true`, anything else `false`. When the key is absent, `def` (default
|
|
481
|
+
* `false`) is returned. The `$request->boolean()` equivalent.
|
|
482
|
+
*/
|
|
483
|
+
boolean(key: string, def?: boolean): boolean;
|
|
484
|
+
/**
|
|
485
|
+
* Read an input value coerced to an integer (a finite number, truncated toward zero). When the key
|
|
486
|
+
* is absent or its value has no numeric reading, `def` (default `0`) is returned. The
|
|
487
|
+
* `$request->integer()` equivalent.
|
|
488
|
+
*/
|
|
489
|
+
integer(key: string, def?: number): number;
|
|
490
|
+
/**
|
|
491
|
+
* Read an input value coerced to a floating-point number. When the key is absent or its value has
|
|
492
|
+
* no numeric reading, `def` (default `0`) is returned. The `$request->float()` equivalent.
|
|
493
|
+
*/
|
|
494
|
+
float(key: string, def?: number): number;
|
|
495
|
+
/**
|
|
496
|
+
* Read an input value coerced to a primitive string. When the key is absent, `def` (default `''`)
|
|
497
|
+
* is returned. The `$request->string()` equivalent — note this returns a primitive
|
|
498
|
+
* `string` rather than a `Stringable`; wrap it with `@plinthjs/support`'s `Str.of()` for fluent
|
|
499
|
+
* helpers if needed.
|
|
500
|
+
*/
|
|
501
|
+
string(key: string, def?: string): string;
|
|
502
|
+
/**
|
|
503
|
+
* Read an input value if (and only if) it is one of `values`, else `undefined`. Generic over the
|
|
504
|
+
* union of allowed values. The `$request->enum()` equivalent (returning the value, not a
|
|
505
|
+
* native enum case). Comparison is by strict equality against the supplied members.
|
|
506
|
+
*/
|
|
507
|
+
enum<T>(key: string, values: readonly T[]): T | undefined;
|
|
508
|
+
/**
|
|
509
|
+
* Wrap the input in a `@plinthjs/support` {@link Collection}: the value at `key` when given (an array
|
|
510
|
+
* value is collected as-is; any other single value is wrapped as a one-element collection), or all
|
|
511
|
+
* input values when omitted. The `$request->collect()` equivalent.
|
|
512
|
+
*/
|
|
513
|
+
collect(key?: string): Collection<unknown>;
|
|
514
|
+
/**
|
|
515
|
+
* Whether the key is present AND its value is not "blank" (empty string/array/object, or nullish).
|
|
516
|
+
* The `$request->filled()` equivalent.
|
|
517
|
+
*/
|
|
518
|
+
filled(key: string): boolean;
|
|
519
|
+
/** Whether the key is absent OR its value is blank. The inverse of {@link Request.filled}. */
|
|
520
|
+
isNotFilled(key: string): boolean;
|
|
521
|
+
/** Whether the key is absent from the merged input. The `$request->missing()` equivalent. */
|
|
522
|
+
missing(key: string): boolean;
|
|
523
|
+
/** Whether any of the given keys is present in the merged input. The `$request->hasAny()` equivalent. */
|
|
524
|
+
hasAny(keys: string[]): boolean;
|
|
525
|
+
/**
|
|
526
|
+
* Whether any of the given keys is present AND not blank. The `$request->anyFilled()` equivalent.
|
|
527
|
+
*/
|
|
528
|
+
anyFilled(keys: string[]): boolean;
|
|
529
|
+
/**
|
|
530
|
+
* Run `cb` when `key` is **absent** from the merged input, returning its result; otherwise return
|
|
531
|
+
* `def`. The `$request->whenMissing()` equivalent.
|
|
532
|
+
*/
|
|
533
|
+
whenMissing<R>(key: string, cb: () => R, def?: R): R | undefined;
|
|
534
|
+
/**
|
|
535
|
+
* Run `cb` with the input value when `key` is present, returning its result; otherwise return
|
|
536
|
+
* `def`. The `$request->whenHas()` equivalent.
|
|
537
|
+
*/
|
|
538
|
+
whenHas<R>(key: string, cb: (value: unknown) => R, def?: R): R | undefined;
|
|
539
|
+
/**
|
|
540
|
+
* Run `cb` with the input value when `key` is present AND not blank, returning its result;
|
|
541
|
+
* otherwise return `def`. The `$request->whenFilled()` equivalent.
|
|
542
|
+
*/
|
|
543
|
+
whenFilled<R>(key: string, cb: (value: unknown) => R, def?: R): R | undefined;
|
|
544
|
+
/**
|
|
545
|
+
* Return a copy of this request with `input` merged into its input bag, overriding any existing
|
|
546
|
+
* keys. Immutable: the original is unchanged. The `$request->merge()` equivalent.
|
|
547
|
+
*/
|
|
548
|
+
merge(input: Record<string, unknown>): Request;
|
|
549
|
+
/**
|
|
550
|
+
* Return a copy of this request with only the keys of `input` that are not already present in the
|
|
551
|
+
* merged input added. Immutable: the original is unchanged. The `$request->mergeIfMissing()`
|
|
552
|
+
* equivalent.
|
|
553
|
+
*/
|
|
554
|
+
mergeIfMissing(input: Record<string, unknown>): Request;
|
|
555
|
+
/** The raw, unparsed request body. */
|
|
556
|
+
body(): string;
|
|
557
|
+
/**
|
|
558
|
+
* Parse and return the JSON body, or `def` when the body is absent/invalid. Unlike {@link all},
|
|
559
|
+
* this returns the decoded value verbatim (arrays and scalars included). The `$request->json()`
|
|
560
|
+
* equivalent.
|
|
561
|
+
*/
|
|
562
|
+
json<T = JsonValue>(def?: T): T | undefined;
|
|
563
|
+
/** Whether the `Content-Type` declares a JSON body. The `$request->isJson()` equivalent. */
|
|
564
|
+
isJson(): boolean;
|
|
565
|
+
/** Whether the client prefers a JSON response (Accept / XHR). The `$request->wantsJson()` equivalent. */
|
|
566
|
+
wantsJson(): boolean;
|
|
567
|
+
/** The bearer token from `Authorization: Bearer …`, or `undefined`. The `$request->bearerToken()` equivalent. */
|
|
568
|
+
bearerToken(): string | undefined;
|
|
569
|
+
/** Read a cookie by name from the `Cookie` header, or `undefined`. The `$request->cookie()` equivalent. */
|
|
570
|
+
cookie(name: string): string | undefined;
|
|
571
|
+
/** Every cookie parsed from the `Cookie` header. */
|
|
572
|
+
cookies(): Record<string, string>;
|
|
573
|
+
/** The client IP, read from `X-Forwarded-For` (first hop) then `X-Real-IP`. The `$request->ip()` equivalent. */
|
|
574
|
+
ip(): string | undefined;
|
|
575
|
+
/**
|
|
576
|
+
* The uploaded file(s) for `key`: a single {@link UploadedFile} when one part used the name, an
|
|
577
|
+
* array when several did, or `undefined` when none did. The `$request->file('avatar')` equivalent.
|
|
578
|
+
*/
|
|
579
|
+
file(key: string): UploadedFile | UploadedFile[] | undefined;
|
|
580
|
+
/** Every uploaded file submitted under `key`, as an array (empty when none). */
|
|
581
|
+
files(key: string): UploadedFile[];
|
|
582
|
+
/** Whether a file was uploaded under `key`. The `$request->hasFile('avatar')` equivalent. */
|
|
583
|
+
hasFile(key: string): boolean;
|
|
584
|
+
/**
|
|
585
|
+
* Every uploaded file keyed by its form field name. A field with multiple files yields an array; a
|
|
586
|
+
* single-file field yields one {@link UploadedFile}. The `$request->allFiles()` equivalent.
|
|
587
|
+
*/
|
|
588
|
+
allFiles(): Record<string, UploadedFile | UploadedFile[]>;
|
|
589
|
+
/**
|
|
590
|
+
* A structural copy carrying route parameters and attributes forward (kept immutable). Every
|
|
591
|
+
* parsed artifact — headers, URL memos, body buffer, parsed/multipart memos — is immutable once
|
|
592
|
+
* built, so clones share it by reference; only the per-clone bags (route params, attributes,
|
|
593
|
+
* bound models, merged input) are copied.
|
|
594
|
+
*/
|
|
595
|
+
private cloneRequest;
|
|
596
|
+
/**
|
|
597
|
+
* Return a copy of this request with the matched route's name attached (read by
|
|
598
|
+
* {@link Request.routeIs}). Immutable: the original is unchanged. The kernel calls this after a
|
|
599
|
+
* successful match on a named route.
|
|
600
|
+
*/
|
|
601
|
+
withRouteName(name: string): Request;
|
|
602
|
+
/**
|
|
603
|
+
* Return a copy of this request with route parameters attached. Immutable: the original is
|
|
604
|
+
* unchanged. The router calls this after a successful match.
|
|
605
|
+
*/
|
|
606
|
+
withParams(params: Record<string, string>): Request;
|
|
607
|
+
/**
|
|
608
|
+
* Return a copy of this request with an arbitrary attribute attached — the `$request->attributes`
|
|
609
|
+
* bag equivalent. Middleware use this to hand request-scoped values (the session, the
|
|
610
|
+
* authenticated user, …) to downstream handlers without mutating the original.
|
|
611
|
+
*/
|
|
612
|
+
withAttribute(key: string, value: unknown): Request;
|
|
613
|
+
/** Read a middleware-attached attribute, or `undefined` when absent. */
|
|
614
|
+
attribute<T = unknown>(key: string): T | undefined;
|
|
615
|
+
/**
|
|
616
|
+
* Return a copy of this request with `name` set to `value` (case-insensitive) — e.g. a `forceJson`
|
|
617
|
+
* middleware setting `Accept: application/json`. The header map is copied (clones normally share it
|
|
618
|
+
* by reference), so the original request is untouched.
|
|
619
|
+
*/
|
|
620
|
+
withHeader(name: string, value: string): Request;
|
|
621
|
+
/**
|
|
622
|
+
* Return a copy with resolved route-model bindings attached. The {@link HttpKernel} calls this
|
|
623
|
+
* after resolving the {@link import('./router').Router}'s bindings for a matched route; handlers
|
|
624
|
+
* read the resolved model with {@link route}.
|
|
625
|
+
*/
|
|
626
|
+
withBoundModels(models: Record<string, unknown>): Request;
|
|
627
|
+
/**
|
|
628
|
+
* The route value for `key`: the resolved bound model when route-model binding applied, otherwise
|
|
629
|
+
* the raw route parameter. `undefined` when neither exists.
|
|
630
|
+
*/
|
|
631
|
+
route<T = unknown>(key: string): T | undefined;
|
|
632
|
+
/** Read a single route parameter, or `def` when absent. The `$request->route('id')` equivalent. */
|
|
633
|
+
param(name: string, def?: string): string | undefined;
|
|
634
|
+
/** Every route parameter as a plain object. */
|
|
635
|
+
params(): Record<string, string>;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* HTTP exceptions and the exception handler — the conventional
|
|
640
|
+
* `Symfony\Component\HttpKernel\Exception\HttpException` family plus
|
|
641
|
+
* `App\Exceptions\Handler`. {@link HttpException} carries a status code; {@link ExceptionHandler}
|
|
642
|
+
* renders any thrown error into a {@link Response}, negotiating JSON vs. HTML from the request.
|
|
643
|
+
*/
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Container token for the application's {@link ExceptionHandler}. Bind a custom handler under this
|
|
647
|
+
* token and {@link HttpKernel} resolves and
|
|
648
|
+
* uses it — `app.singleton(EXCEPTION_HANDLER, () => new MyHandler())`. A symbol token (rather than
|
|
649
|
+
* the {@link ExceptionHandler} class itself) keeps the binding key decoupled, so an app may bind any
|
|
650
|
+
* handler shape without the class participating as a key.
|
|
651
|
+
*/
|
|
652
|
+
declare const EXCEPTION_HANDLER: symbol;
|
|
653
|
+
/**
|
|
654
|
+
* A reportable callback registered via {@link ExceptionHandler.reportable}. Returning `false` halts
|
|
655
|
+
* further reporting of that error (no later reportable callbacks and no default sink run) — the
|
|
656
|
+
* `reportable(fn)->stop()` / `return false` convention. Any other return (including
|
|
657
|
+
* returning nothing) lets reporting continue; the return is `unknown` so void callbacks fit too.
|
|
658
|
+
*/
|
|
659
|
+
type ReportableCallback = (error: unknown) => unknown;
|
|
660
|
+
/**
|
|
661
|
+
* A renderable callback registered via {@link ExceptionHandler.renderable}. Returning a
|
|
662
|
+
* {@link Response} makes {@link ExceptionHandler.render} use it; returning `undefined` falls through
|
|
663
|
+
* to the next renderable, then the default rendering.
|
|
664
|
+
*/
|
|
665
|
+
type RenderableCallback = (error: unknown, request?: Request) => Response | undefined;
|
|
666
|
+
/** The terminal report destination — where un-stopped errors are sent. The settable log seam. */
|
|
667
|
+
type ReportSink = (error: unknown, context: Record<string, unknown>) => void;
|
|
668
|
+
/** The log severities an exception may be reported at — the PSR-3 / `level()` levels. */
|
|
669
|
+
type LogLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';
|
|
670
|
+
/** A base HTTP error carrying a status code. The `HttpException` equivalent. */
|
|
671
|
+
declare class HttpException extends Error {
|
|
672
|
+
/** The HTTP status code this exception renders as. */
|
|
673
|
+
readonly status: number;
|
|
674
|
+
/** Extra headers to attach to the rendered response. */
|
|
675
|
+
readonly headers: Record<string, string>;
|
|
676
|
+
constructor(
|
|
677
|
+
/** The HTTP status code this exception renders as. */
|
|
678
|
+
status: number, message?: string, headers?: Record<string, string>);
|
|
679
|
+
}
|
|
680
|
+
/** A `404 Not Found`. The `NotFoundHttpException` equivalent. */
|
|
681
|
+
declare class NotFoundHttpException extends HttpException {
|
|
682
|
+
constructor(message?: string);
|
|
683
|
+
}
|
|
684
|
+
/** A `405 Method Not Allowed`, advertising the `Allow` header. The `MethodNotAllowedHttpException` equivalent. */
|
|
685
|
+
declare class MethodNotAllowedHttpException extends HttpException {
|
|
686
|
+
constructor(allowed?: string[], message?: string);
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* `ExceptionHandler` — renders a thrown error to a {@link Response}, the `App\Exceptions\Handler`
|
|
690
|
+
* equivalent. JSON when the request {@link Request.wantsJson wants JSON}, otherwise an HTML page.
|
|
691
|
+
* The handler is deterministic: it derives status and message from the error, never the clock.
|
|
692
|
+
*/
|
|
693
|
+
declare class ExceptionHandler {
|
|
694
|
+
private readonly debug;
|
|
695
|
+
/** Reportable callbacks, run in registration order by {@link ExceptionHandler.report}. */
|
|
696
|
+
private readonly reportCallbacks;
|
|
697
|
+
/** Renderable callbacks, tried in registration order by {@link ExceptionHandler.render}. */
|
|
698
|
+
private readonly renderCallbacks;
|
|
699
|
+
/**
|
|
700
|
+
* Error constructors whose instances are not reported. Seeded with {@link HttpException} (an
|
|
701
|
+
* `instanceof` check, so every subclass — 404/405/… — is covered too), following the usual small
|
|
702
|
+
* internal don't-report list. Extend with {@link ExceptionHandler.ignore} / shrink with
|
|
703
|
+
* {@link ExceptionHandler.stopIgnoring}.
|
|
704
|
+
*/
|
|
705
|
+
private readonly ignored;
|
|
706
|
+
/** The terminal report sink; a no-op by default. Replace via {@link ExceptionHandler.reportUsing}. */
|
|
707
|
+
private reportSink;
|
|
708
|
+
/** When `true`, an already-reported error instance is skipped on later {@link report} calls. */
|
|
709
|
+
private deduplicate;
|
|
710
|
+
/** Exception mappings, applied (first match wins) before reporting/rendering. See {@link map}. */
|
|
711
|
+
private readonly mappers;
|
|
712
|
+
/** Per-constructor log levels consulted by {@link ExceptionHandler.levelFor}. */
|
|
713
|
+
private readonly levels;
|
|
714
|
+
/**
|
|
715
|
+
* Input keys never flashed back to the session on a validation redirect — the conventional
|
|
716
|
+
* `$dontFlash` list, seeded with its defaults. `@plinthjs/http` itself has no redirect/flash path,
|
|
717
|
+
* so the list is stored here and exposed via {@link ExceptionHandler.getDontFlash} for the
|
|
718
|
+
* session/validation layer to consume when it re-flashes old input.
|
|
719
|
+
*/
|
|
720
|
+
private dontFlashKeys;
|
|
721
|
+
/** Error instances already reported, for {@link ExceptionHandler.withoutDuplicates} de-duplication. */
|
|
722
|
+
private readonly reported;
|
|
723
|
+
/**
|
|
724
|
+
* @param debug When `true`, non-HTTP errors expose their real message (and a stack hint in JSON);
|
|
725
|
+
* otherwise they render a generic `500`. The `APP_DEBUG` equivalent.
|
|
726
|
+
*/
|
|
727
|
+
constructor(debug?: boolean);
|
|
728
|
+
/**
|
|
729
|
+
* The status code an error should render as: an {@link HttpException}'s status, a numeric `status`
|
|
730
|
+
* carried structurally by the error (e.g. a validation `422` or authorization `403`), else `500`.
|
|
731
|
+
*/
|
|
732
|
+
statusFor(error: unknown): number;
|
|
733
|
+
/**
|
|
734
|
+
* Map one exception type to another: whenever an instance of `from` reaches the handler, it is
|
|
735
|
+
* first converted via `to` and the *result* is reported and rendered instead. The conventional
|
|
736
|
+
* `$exceptions->map(From::class, fn ($e) => new To(..., $e))` equivalent. Mappings are checked in
|
|
737
|
+
* registration order; the first `instanceof` match applies (once — the mapped error is not
|
|
738
|
+
* re-mapped). Chains.
|
|
739
|
+
*/
|
|
740
|
+
map<T>(from: Newable<T>, to: (error: T) => unknown): this;
|
|
741
|
+
/** Apply the first matching {@link ExceptionHandler.map} mapping to `error`, if any. */
|
|
742
|
+
mapException(error: unknown): unknown;
|
|
743
|
+
/**
|
|
744
|
+
* Set the log level instances of `ctor` are reported at. The level is surfaced as the
|
|
745
|
+
* `level` key of the context passed to the {@link ReportSink}. Chains.
|
|
746
|
+
*/
|
|
747
|
+
level(ctor: Newable, logLevel: LogLevel): this;
|
|
748
|
+
/** The log level `error` reports at: the first registered `instanceof` match, else `'error'`. */
|
|
749
|
+
levelFor(error: unknown): LogLevel;
|
|
750
|
+
/**
|
|
751
|
+
* Replace the list of input keys that must never be flashed back on a validation redirect — the
|
|
752
|
+
* `$exceptions->dontFlash([...])` equivalent. Defaults to `current_password`, `password`,
|
|
753
|
+
* and `password_confirmation`. There is no redirect/flash path inside `@plinthjs/http`, so the list
|
|
754
|
+
* is exposed via {@link ExceptionHandler.getDontFlash} for the session/validation layer that
|
|
755
|
+
* re-flashes old input. Chains.
|
|
756
|
+
*/
|
|
757
|
+
dontFlash(keys: string[]): this;
|
|
758
|
+
/** The input keys never flashed back on a validation redirect (a copy). */
|
|
759
|
+
getDontFlash(): string[];
|
|
760
|
+
/**
|
|
761
|
+
* Register a reportable callback. Runs in order during {@link ExceptionHandler.report}; returning
|
|
762
|
+
* `false` from a callback stops all further reporting of that error. Chains.
|
|
763
|
+
*/
|
|
764
|
+
reportable(callback: ReportableCallback): this;
|
|
765
|
+
/**
|
|
766
|
+
* Add error constructors to the don't-report list. Matching is by `instanceof`, so a base class also suppresses its subclasses. Chains.
|
|
767
|
+
*/
|
|
768
|
+
ignore(...classes: Newable[]): this;
|
|
769
|
+
/** Alias of {@link ExceptionHandler.ignore} — the `$dontReport` spelling. */
|
|
770
|
+
dontReport(...classes: Newable[]): this;
|
|
771
|
+
/** Remove error constructors from the don't-report list. */
|
|
772
|
+
stopIgnoring(...classes: Newable[]): this;
|
|
773
|
+
/** Whether `error` should be reported: `false` when it (or a superclass) is in the ignore list. */
|
|
774
|
+
shouldReport(error: unknown): boolean;
|
|
775
|
+
/** Replace the terminal report sink (the logger seam). */
|
|
776
|
+
reportUsing(sink: ReportSink): this;
|
|
777
|
+
/** De-duplicate reports: the same error instance is reported at most once. The `withoutDuplicates()` flag. */
|
|
778
|
+
withoutDuplicates(): this;
|
|
779
|
+
/**
|
|
780
|
+
* A hook for additional report context, merged into every report. Override in a subclass to attach
|
|
781
|
+
* request-scoped data (user id, etc.).
|
|
782
|
+
*/
|
|
783
|
+
context(): Record<string, unknown>;
|
|
784
|
+
/**
|
|
785
|
+
* Report `error`: if {@link ExceptionHandler.shouldReport} and not a duplicate (when
|
|
786
|
+
* {@link ExceptionHandler.withoutDuplicates} is on), run the reportable callbacks in order — a
|
|
787
|
+
* `false` return stops the chain (the default sink is skipped) — otherwise fall through to the
|
|
788
|
+
* terminal sink.
|
|
789
|
+
*/
|
|
790
|
+
report(error: unknown): void;
|
|
791
|
+
/** Register a renderable callback, tried first by {@link ExceptionHandler.render}. Chains. */
|
|
792
|
+
renderable(callback: RenderableCallback): this;
|
|
793
|
+
/**
|
|
794
|
+
* Render `error` to a {@link Response}, negotiating JSON vs. HTML from `req`. Any
|
|
795
|
+
* {@link ExceptionHandler.map} mapping is applied first, so renderables and the default rendering
|
|
796
|
+
* see the mapped error.
|
|
797
|
+
*/
|
|
798
|
+
render(req: Request, rawError: unknown): Response;
|
|
799
|
+
/** The user-facing message for an error, hiding internals for non-debug `500`s. */
|
|
800
|
+
private messageFor;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* Middleware — the conventional, API-driven HTTP middleware stack. A
|
|
805
|
+
* {@link Middleware} receives the {@link Request} and a `next` continuation, and either calls
|
|
806
|
+
* `next` (passing control inward) or returns a {@link Response} directly to short-circuit.
|
|
807
|
+
* {@link runMiddleware} composes a stack around a final handler; {@link isTerminable} /
|
|
808
|
+
* {@link TerminableMiddleware} support the `terminate()` hook that runs after the response is built.
|
|
809
|
+
*/
|
|
810
|
+
|
|
811
|
+
/** The continuation handed to a middleware: invoke it to pass control to the next layer. */
|
|
812
|
+
type Next = (req: Request) => Promise<Response>;
|
|
813
|
+
/**
|
|
814
|
+
* An HTTP middleware. Call `next(req)` to continue (optionally with a modified request), or return
|
|
815
|
+
* a {@link Response} without calling `next` to short-circuit the stack.
|
|
816
|
+
*/
|
|
817
|
+
type Middleware = (req: Request, next: Next) => Promise<Response>;
|
|
818
|
+
/** A middleware that also wants a post-response `terminate()` callback (e.g. session save). */
|
|
819
|
+
interface TerminableMiddleware {
|
|
820
|
+
/** The request-handling phase. */
|
|
821
|
+
handle: Middleware;
|
|
822
|
+
/** Runs after the response has been produced. The `terminate($request, $response)` equivalent. */
|
|
823
|
+
terminate(req: Request, res: Response): void | Promise<void>;
|
|
824
|
+
}
|
|
825
|
+
/** A middleware in either supported form: a bare function or a {@link TerminableMiddleware} object. */
|
|
826
|
+
type MiddlewareEntry = Middleware | TerminableMiddleware;
|
|
827
|
+
/**
|
|
828
|
+
* A middleware *reference* accepted on routes and groups: either a concrete {@link MiddlewareEntry}
|
|
829
|
+
* (function/class) or a `string` naming a registered {@link import('./router').Router.aliasMiddleware
|
|
830
|
+
* alias} or {@link import('./router').Router.middlewareGroup group}. Strings are resolved to concrete
|
|
831
|
+
* entries when a matched route's stack is assembled (see {@link import('./router').Router.resolveMiddleware}).
|
|
832
|
+
*/
|
|
833
|
+
type MiddlewareReference = MiddlewareEntry | string;
|
|
834
|
+
/** Type guard: does this entry carry a `terminate()` hook? */
|
|
835
|
+
declare function isTerminable(entry: MiddlewareEntry): entry is TerminableMiddleware;
|
|
836
|
+
/**
|
|
837
|
+
* Compose `stack` around `destination`, running the middleware left-to-right (outermost first) and
|
|
838
|
+
* returning the resulting {@link Response}. Equivalent to passing the request through the conventional
|
|
839
|
+
* `Pipeline`. A middleware that returns without calling `next` short-circuits everything inward.
|
|
840
|
+
*/
|
|
841
|
+
declare function runMiddleware(req: Request, stack: MiddlewareEntry[], destination: Next): Promise<Response>;
|
|
842
|
+
/**
|
|
843
|
+
* Invoke `terminate()` on every terminable entry in `stack`, in order, after the response is sent.
|
|
844
|
+
* Errors in one terminator do not prevent the others from running.
|
|
845
|
+
*/
|
|
846
|
+
declare function terminateMiddleware(req: Request, res: Response, stack: readonly MiddlewareEntry[]): Promise<void>;
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* `Router` — registration and matching of HTTP routes, the conventional API
|
|
850
|
+
* equivalent. Routes carry a method set, a path pattern (`/users/{id}`, optional `{id?}`), an
|
|
851
|
+
* optional name, and per-route middleware. {@link Router.group} applies a shared prefix and
|
|
852
|
+
* middleware to everything registered inside it; {@link Router.match} resolves an inbound
|
|
853
|
+
* method+path to a {@link Route} (with extracted parameters), a 405 (method not allowed), or a 404.
|
|
854
|
+
*
|
|
855
|
+
* It also generates signed URLs ({@link Router.signedUrl}) and validates them
|
|
856
|
+
* ({@link Router.hasValidSignature}, {@link Router.signedMiddleware}), built on an HMAC over a
|
|
857
|
+
* {@link Router.setSigningKey configured} secret.
|
|
858
|
+
*/
|
|
859
|
+
|
|
860
|
+
/** Construction options for {@link Router}. */
|
|
861
|
+
interface RouterOptions {
|
|
862
|
+
/** The secret used to sign and verify URLs (the `app.key` equivalent for {@link Router.signedUrl}). */
|
|
863
|
+
key?: string;
|
|
864
|
+
/**
|
|
865
|
+
* The renderer {@link Router.view} routes defer to. Can also be installed later via
|
|
866
|
+
* {@link Router.renderViewsUsing}; dispatching a view route without one throws.
|
|
867
|
+
*/
|
|
868
|
+
viewRenderer?: ViewRenderer;
|
|
869
|
+
}
|
|
870
|
+
/** What a route handler may return; the kernel coerces non-{@link Response} results. */
|
|
871
|
+
type RouteResult = Response | string | object | null | undefined;
|
|
872
|
+
/** A closure route handler: receives the (parameter-bound) request and returns a result. */
|
|
873
|
+
type RouteHandlerClosure = (req: Request) => RouteResult | Promise<RouteResult>;
|
|
874
|
+
/** A controller action: a class plus the method name to invoke, resolved via the container. */
|
|
875
|
+
type ControllerAction = readonly [controller: Newable, method: string];
|
|
876
|
+
/**
|
|
877
|
+
* A single-action ("invokable") controller reference — a controller class on its own, or a
|
|
878
|
+
* one-element `[Controller]` tuple. The kernel resolves the instance via the container and calls its
|
|
879
|
+
* `__invoke` method.
|
|
880
|
+
*/
|
|
881
|
+
type InvokableAction = Newable | readonly [controller: Newable];
|
|
882
|
+
/**
|
|
883
|
+
* Either supported handler form: a closure, a `[Controller, method]` pair, or an
|
|
884
|
+
* {@link InvokableAction} (a controller class — or `[Controller]` — whose `__invoke` is called).
|
|
885
|
+
*/
|
|
886
|
+
type RouteHandler = RouteHandlerClosure | ControllerAction | InvokableAction;
|
|
887
|
+
/**
|
|
888
|
+
* Resolves a route-bound parameter to a value (typically a model) — the `Route::bind`
|
|
889
|
+
* resolver. May return synchronously or as a `Promise` (both covered by `unknown`); returning
|
|
890
|
+
* `null`/`undefined` makes the route a 404 (implicit-binding "not found").
|
|
891
|
+
*/
|
|
892
|
+
type BindingResolver = (value: string, req: Request) => unknown;
|
|
893
|
+
/** The HTTP verbs a route can be registered for. `HEAD` is served by matching a `GET` route. */
|
|
894
|
+
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
|
|
895
|
+
/**
|
|
896
|
+
* A route-parameter constraint: a regex pattern (string or `RegExp`) the parameter's value must
|
|
897
|
+
* fully match for the route to match.
|
|
898
|
+
*/
|
|
899
|
+
type WherePattern = string | RegExp;
|
|
900
|
+
/**
|
|
901
|
+
* A renderer the {@link Router} defers {@link Router.view} routes to — given the view name, the
|
|
902
|
+
* data bag, and the request, it produces the HTML string. The usual view-factory seam: `@plinthjs/http`
|
|
903
|
+
* has no templating, so the app (or `@plinthjs/view`-style package) installs one via
|
|
904
|
+
* {@link Router.renderViewsUsing} or the `viewRenderer` {@link RouterOptions construction option}.
|
|
905
|
+
*/
|
|
906
|
+
type ViewRenderer = (view: string, data: Record<string, unknown>, req: Request) => string | Promise<string>;
|
|
907
|
+
/** Options for {@link Router.group}: a shared path prefix, shared middleware, and/or a host domain. */
|
|
908
|
+
interface RouteGroupOptions {
|
|
909
|
+
prefix?: string;
|
|
910
|
+
/**
|
|
911
|
+
* Parameter constraints applied to every route registered inside the group — the conventional
|
|
912
|
+
* `Route::group(['where' => [...]])` / group-level `pattern` equivalent. A route's own
|
|
913
|
+
* {@link Route.where} for the same parameter overrides the group's.
|
|
914
|
+
*/
|
|
915
|
+
where?: Record<string, WherePattern>;
|
|
916
|
+
/**
|
|
917
|
+
* Shared middleware for every route in the group. Accepts concrete entries (function/class) and
|
|
918
|
+
* `string` names referencing a registered alias or middleware group; names are resolved when a
|
|
919
|
+
* matched route's stack is assembled.
|
|
920
|
+
*/
|
|
921
|
+
middleware?: MiddlewareReference | MiddlewareReference[];
|
|
922
|
+
/**
|
|
923
|
+
* A host pattern (e.g. `{account}.myapp.com`) constraining every route in the group. When groups
|
|
924
|
+
* nest, the innermost `domain` wins.
|
|
925
|
+
*/
|
|
926
|
+
domain?: string;
|
|
927
|
+
}
|
|
928
|
+
/** The outcome of {@link Router.match}. */
|
|
929
|
+
type RouteMatch = {
|
|
930
|
+
readonly type: 'matched';
|
|
931
|
+
readonly route: Route;
|
|
932
|
+
readonly params: Record<string, string>;
|
|
933
|
+
} | {
|
|
934
|
+
readonly type: 'method-not-allowed';
|
|
935
|
+
readonly allowed: HttpMethod[];
|
|
936
|
+
} | {
|
|
937
|
+
readonly type: 'not-found';
|
|
938
|
+
};
|
|
939
|
+
/**
|
|
940
|
+
* A single route in a {@link RouteCache} snapshot — a plain, JSON-serializable description of a
|
|
941
|
+
* registered route. The handler is recorded as a `[controllerName, method]` pair (closures cannot
|
|
942
|
+
* be serialized; see {@link Router.toCache}), and middleware are recorded by name only.
|
|
943
|
+
*/
|
|
944
|
+
interface CachedRoute {
|
|
945
|
+
readonly methods: readonly HttpMethod[];
|
|
946
|
+
readonly path: string;
|
|
947
|
+
readonly name: string | undefined;
|
|
948
|
+
readonly domain: string | undefined;
|
|
949
|
+
/** Middleware names (function/class names) — recorded for inspection and optional rehydration. */
|
|
950
|
+
readonly middleware: readonly string[];
|
|
951
|
+
/** The controller class name and method invoked for this route. */
|
|
952
|
+
readonly action: readonly [controller: string, method: string];
|
|
953
|
+
}
|
|
954
|
+
/** A JSON-serializable snapshot of a {@link Router}'s routes — the `route:cache` artifact. */
|
|
955
|
+
interface RouteCache {
|
|
956
|
+
readonly routes: readonly CachedRoute[];
|
|
957
|
+
}
|
|
958
|
+
/** Resolves a cached controller class name back to its constructor during rehydration. */
|
|
959
|
+
type ControllerResolver = (name: string) => Newable;
|
|
960
|
+
/** Resolves a cached middleware name back to a {@link MiddlewareEntry} during rehydration. */
|
|
961
|
+
type MiddlewareResolver = (name: string) => MiddlewareEntry;
|
|
962
|
+
/** Options controlling how a {@link RouteCache} is rehydrated back into a {@link Router}. */
|
|
963
|
+
interface LoadCacheOptions {
|
|
964
|
+
/** Maps a controller class name to its constructor. Required to reconstruct route handlers. */
|
|
965
|
+
controller: ControllerResolver;
|
|
966
|
+
/**
|
|
967
|
+
* Maps a middleware name to a {@link MiddlewareEntry}. Optional: when omitted, cached middleware
|
|
968
|
+
* names are not reattached (the controller action still dispatches), mirroring the fact that the
|
|
969
|
+
* cache records middleware by name only.
|
|
970
|
+
*/
|
|
971
|
+
middleware?: MiddlewareResolver;
|
|
972
|
+
}
|
|
973
|
+
/** Why a signature failed to validate, or `'valid'` — surfaced by {@link Router.validateSignature}. */
|
|
974
|
+
type SignatureResult = 'valid' | 'missing' | 'invalid' | 'expired';
|
|
975
|
+
/** A single registered route. Builder methods ({@link Route.name}, {@link Route.middleware}) chain. */
|
|
976
|
+
declare class Route {
|
|
977
|
+
readonly methods: readonly HttpMethod[];
|
|
978
|
+
readonly path: string;
|
|
979
|
+
readonly handler: RouteHandler;
|
|
980
|
+
private readonly compiled;
|
|
981
|
+
private routeName;
|
|
982
|
+
private readonly routeMiddleware;
|
|
983
|
+
private domainPattern;
|
|
984
|
+
private compiledDomain;
|
|
985
|
+
/** Per-parameter constraints; a parameter only matches when its value satisfies the regex. */
|
|
986
|
+
private readonly constraints;
|
|
987
|
+
constructor(methods: readonly HttpMethod[], path: string, handler: RouteHandler, middleware?: readonly MiddlewareReference[], domain?: string);
|
|
988
|
+
/** Name this route so it can be resolved by {@link Router.url}. The `->name()` equivalent. */
|
|
989
|
+
name(name: string): this;
|
|
990
|
+
/** This route's name, or `undefined` if unnamed. */
|
|
991
|
+
getName(): string | undefined;
|
|
992
|
+
/**
|
|
993
|
+
* Constrain this route to a host pattern (e.g. `{account}.myapp.com`). The `->domain()`
|
|
994
|
+
* equivalent: the route only matches when the request host matches, and any `{param}` labels in
|
|
995
|
+
* the domain are extracted into the route's parameters (ahead of path params). Chains like the
|
|
996
|
+
* other builders.
|
|
997
|
+
*/
|
|
998
|
+
domain(domain: string): this;
|
|
999
|
+
/** Compile and store the domain pattern; shared by the constructor and {@link Route.domain}. */
|
|
1000
|
+
private setDomain;
|
|
1001
|
+
/** This route's domain pattern, or `undefined` when it matches any host. */
|
|
1002
|
+
getDomain(): string | undefined;
|
|
1003
|
+
/**
|
|
1004
|
+
* Match a request `host` against this route's domain. Returns the extracted domain params, or `undefined` when the route has a domain that the host does not satisfy (including
|
|
1005
|
+
* when the route requires a domain but no host was supplied).
|
|
1006
|
+
*/
|
|
1007
|
+
matchDomain(host: string | undefined): Record<string, string> | undefined;
|
|
1008
|
+
/**
|
|
1009
|
+
* Constrain route parameter(s) to a regex pattern. Accepts a
|
|
1010
|
+
* single `param`/`pattern` pair or a `{ param: pattern }` record; patterns are strings or
|
|
1011
|
+
* `RegExp`s, anchored so the **whole** parameter value must match. A non-matching value makes this
|
|
1012
|
+
* route not match at all, so the request falls through to later routes (or a 404). Chains.
|
|
1013
|
+
*/
|
|
1014
|
+
where(param: string, pattern: WherePattern): this;
|
|
1015
|
+
where(patterns: Record<string, WherePattern>): this;
|
|
1016
|
+
/** Constrain `param` to digits only. Chains. */
|
|
1017
|
+
whereNumber(param: string): this;
|
|
1018
|
+
/** Constrain `param` to ASCII letters only. Chains. */
|
|
1019
|
+
whereAlpha(param: string): this;
|
|
1020
|
+
/** Constrain `param` to letters and digits. Chains. */
|
|
1021
|
+
whereAlphaNumeric(param: string): this;
|
|
1022
|
+
/** Constrain `param` to a UUID shape. Chains. */
|
|
1023
|
+
whereUuid(param: string): this;
|
|
1024
|
+
/** Constrain `param` to a ULID shape. Chains. */
|
|
1025
|
+
whereUlid(param: string): this;
|
|
1026
|
+
/** Constrain `param` to one of `values` (matched literally). The `->whereIn()` equivalent. Chains. */
|
|
1027
|
+
whereIn(param: string, values: readonly string[]): this;
|
|
1028
|
+
/**
|
|
1029
|
+
* Append middleware that wraps only this route. Accepts concrete entries (function/class) and
|
|
1030
|
+
* `string` names referencing a registered alias or middleware group (resolved at match time). The
|
|
1031
|
+
* `->middleware()` equivalent.
|
|
1032
|
+
*/
|
|
1033
|
+
middleware(...entries: MiddlewareReference[]): this;
|
|
1034
|
+
/**
|
|
1035
|
+
* The middleware stack for this route (a copy), as registered — so `string` alias/group names are
|
|
1036
|
+
* returned verbatim. The {@link Router} resolves these to concrete entries via
|
|
1037
|
+
* {@link Router.resolveMiddleware} when dispatching a matched route.
|
|
1038
|
+
*/
|
|
1039
|
+
getMiddleware(): MiddlewareReference[];
|
|
1040
|
+
/** The ordered names of this route's path parameters. */
|
|
1041
|
+
parameterNames(): string[];
|
|
1042
|
+
/**
|
|
1043
|
+
* Extract route parameters if `path` matches this route's pattern, else `undefined`. Any
|
|
1044
|
+
* {@link Route.where} constraints are enforced here: a parameter value that fails its constraint
|
|
1045
|
+
* makes the whole route a non-match (so an absent optional parameter is never constrained).
|
|
1046
|
+
*/
|
|
1047
|
+
match(path: string): Record<string, string> | undefined;
|
|
1048
|
+
/** Whether this route serves `method` (HEAD falls through to GET). */
|
|
1049
|
+
handlesMethod(method: string): boolean;
|
|
1050
|
+
/** Build a concrete path from this route's pattern, substituting `params`. */
|
|
1051
|
+
url(params?: Record<string, string | number>): string;
|
|
1052
|
+
}
|
|
1053
|
+
/** The seven canonical resource controller methods, in registration order. */
|
|
1054
|
+
type ResourceMethod = 'index' | 'create' | 'store' | 'show' | 'edit' | 'update' | 'destroy';
|
|
1055
|
+
/**
|
|
1056
|
+
* Options for {@link Router.resource} / {@link Router.apiResource}. Every option also has a chained
|
|
1057
|
+
* counterpart on the returned {@link ResourceRegistration}; values passed here are applied first and
|
|
1058
|
+
* may be further narrowed/renamed by chaining.
|
|
1059
|
+
*/
|
|
1060
|
+
interface ResourceOptions {
|
|
1061
|
+
/** Register only these resource methods (others are skipped). */
|
|
1062
|
+
only?: readonly ResourceMethod[];
|
|
1063
|
+
/** Register every resource method except these. */
|
|
1064
|
+
except?: readonly ResourceMethod[];
|
|
1065
|
+
/** Override the generated route name for specific methods. */
|
|
1066
|
+
names?: Partial<Record<ResourceMethod, string>>;
|
|
1067
|
+
/**
|
|
1068
|
+
* Override the URI parameter name(s). A single string renames the resource's one parameter; a map
|
|
1069
|
+
* renames per resource-name key (for nested resources).
|
|
1070
|
+
*/
|
|
1071
|
+
parameters?: string | Record<string, string>;
|
|
1072
|
+
/**
|
|
1073
|
+
* Scope nested-resource child URIs to only the trailing parameter (and prefix it with the resource
|
|
1074
|
+
* name) for `show`/`edit`/`update`/`destroy`.
|
|
1075
|
+
*/
|
|
1076
|
+
shallow?: boolean;
|
|
1077
|
+
}
|
|
1078
|
+
/** The enclosing-group context captured when a resource is registered, applied at build time. */
|
|
1079
|
+
interface ResourceContext {
|
|
1080
|
+
readonly prefix: string;
|
|
1081
|
+
readonly middleware: readonly MiddlewareReference[];
|
|
1082
|
+
readonly domain: string | undefined;
|
|
1083
|
+
readonly where: Record<string, WherePattern>;
|
|
1084
|
+
}
|
|
1085
|
+
/**
|
|
1086
|
+
* A pending resource-route registration — the builder returned by {@link Router.resource} /
|
|
1087
|
+
* {@link Router.apiResource}, the `PendingResourceRegistration` equivalent. Routes are not
|
|
1088
|
+
* created when this is returned; instead the registration is **deferred** and finalized (built into
|
|
1089
|
+
* real {@link Route}s) the first time the owning {@link Router} is matched, enumerated, has a named
|
|
1090
|
+
* URL generated, or is cached. This lets `.only()` / `.except()` / `.names()` / `.parameters()` /
|
|
1091
|
+
* `.shallow()` be chained after the call and still take effect — each just narrows/renames config,
|
|
1092
|
+
* then returns `this`. The group prefix/middleware/domain in force when {@link Router.resource} was
|
|
1093
|
+
* called are captured up-front, so deferred building still honors the enclosing group.
|
|
1094
|
+
*
|
|
1095
|
+
* Resolving (and re-resolving) is idempotent; the registration builds exactly once.
|
|
1096
|
+
*/
|
|
1097
|
+
declare class ResourceRegistration {
|
|
1098
|
+
private readonly resourceName;
|
|
1099
|
+
private readonly controller;
|
|
1100
|
+
private readonly api;
|
|
1101
|
+
private readonly context;
|
|
1102
|
+
private readonly register;
|
|
1103
|
+
private onlyMethods;
|
|
1104
|
+
private exceptMethods;
|
|
1105
|
+
private readonly nameOverrides;
|
|
1106
|
+
private parameterName;
|
|
1107
|
+
private readonly parameterMap;
|
|
1108
|
+
private isShallow;
|
|
1109
|
+
private builtRoutes;
|
|
1110
|
+
constructor(resourceName: string, controller: Newable, api: boolean, context: ResourceContext, register: (route: Route) => void, options?: ResourceOptions);
|
|
1111
|
+
/** Register only these resource methods. Chains. Re-resolving after the first build is a no-op. */
|
|
1112
|
+
only(methods: readonly ResourceMethod[]): this;
|
|
1113
|
+
/** Register every resource method except these. Chains. */
|
|
1114
|
+
except(methods: readonly ResourceMethod[]): this;
|
|
1115
|
+
/** Override generated route names per method (e.g. `{ show: 'users.profile' }`). Chains. */
|
|
1116
|
+
names(overrides: Partial<Record<ResourceMethod, string>>): this;
|
|
1117
|
+
/** Override the URI parameter name (string) or per-resource-name map. Chains. */
|
|
1118
|
+
parameters(value: string | Record<string, string>): this;
|
|
1119
|
+
/** Mark this resource's member routes as shallow (trailing-param-only URIs). Chains. */
|
|
1120
|
+
shallow(value?: boolean): this;
|
|
1121
|
+
/** The methods this registration will produce, after applying `only`/`except` (and `api`). */
|
|
1122
|
+
private selectedMethods;
|
|
1123
|
+
/** The resolved URI parameter name for this resource (override → string map → singular of name). */
|
|
1124
|
+
private resolvedParameter;
|
|
1125
|
+
/** Build (once) and register every selected route, returning them. Idempotent. */
|
|
1126
|
+
resolve(): Route[];
|
|
1127
|
+
/**
|
|
1128
|
+
* Construct a single resource {@link Route} for `spec`, naming it `name.method` and applying the
|
|
1129
|
+
* captured group prefix/middleware/domain (so a resource declared inside a group is grouped).
|
|
1130
|
+
*/
|
|
1131
|
+
private buildRoute;
|
|
1132
|
+
}
|
|
1133
|
+
/** The singleton-resource methods. */
|
|
1134
|
+
type SingletonMethod = 'show' | 'edit' | 'update' | 'destroy';
|
|
1135
|
+
/**
|
|
1136
|
+
* A pending singleton-resource registration — the builder returned by {@link Router.singleton} /
|
|
1137
|
+
* {@link Router.apiSingleton}, the `PendingSingletonResourceRegistration` equivalent. A
|
|
1138
|
+
* singleton resource has exactly one instance per context (a profile, a thumbnail), so no `index`,
|
|
1139
|
+
* `create`/`store`, or `{param}` segment is registered:
|
|
1140
|
+
*
|
|
1141
|
+
* - `GET name` → `show` (`name.show`)
|
|
1142
|
+
* - `GET name/edit` → `edit` (`name.edit`, omitted by {@link Router.apiSingleton})
|
|
1143
|
+
* - `PUT|PATCH name` → `update` (`name.update`)
|
|
1144
|
+
* - `DELETE name` → `destroy` (`name.destroy`, only after chaining {@link SingletonRegistration.destroyable})
|
|
1145
|
+
*
|
|
1146
|
+
* Registration is **deferred** exactly like {@link ResourceRegistration} (built on first
|
|
1147
|
+
* match/enumeration), so `.destroyable()` may be chained after the call. The enclosing group
|
|
1148
|
+
* context is captured up-front. Resolving is idempotent.
|
|
1149
|
+
*/
|
|
1150
|
+
declare class SingletonRegistration {
|
|
1151
|
+
private readonly resourceName;
|
|
1152
|
+
private readonly controller;
|
|
1153
|
+
private readonly api;
|
|
1154
|
+
private readonly context;
|
|
1155
|
+
private readonly register;
|
|
1156
|
+
private isDestroyable;
|
|
1157
|
+
private builtRoutes;
|
|
1158
|
+
constructor(resourceName: string, controller: Newable, api: boolean, context: ResourceContext, register: (route: Route) => void);
|
|
1159
|
+
/** Also register `DELETE name` → `destroy`. Chains. */
|
|
1160
|
+
destroyable(value?: boolean): this;
|
|
1161
|
+
/** Build (once) and register every selected route, returning them. Idempotent. */
|
|
1162
|
+
resolve(): Route[];
|
|
1163
|
+
/** Construct and register a single singleton {@link Route}, named `name.method`. */
|
|
1164
|
+
private buildRoute;
|
|
1165
|
+
}
|
|
1166
|
+
declare class Router {
|
|
1167
|
+
private readonly routes;
|
|
1168
|
+
private readonly groupStack;
|
|
1169
|
+
private fallbackHandler;
|
|
1170
|
+
private readonly bindings;
|
|
1171
|
+
private readonly middlewareGroups;
|
|
1172
|
+
private readonly middlewareAliases;
|
|
1173
|
+
private signingKey;
|
|
1174
|
+
private readonly pendingResources;
|
|
1175
|
+
private viewRenderer;
|
|
1176
|
+
private dispatchIndex;
|
|
1177
|
+
constructor(options?: RouterOptions);
|
|
1178
|
+
/** Register a `GET` route (also answers `HEAD`). */
|
|
1179
|
+
get(path: string, handler: RouteHandler): Route;
|
|
1180
|
+
/** Register a `POST` route. */
|
|
1181
|
+
post(path: string, handler: RouteHandler): Route;
|
|
1182
|
+
/** Register a `PUT` route. */
|
|
1183
|
+
put(path: string, handler: RouteHandler): Route;
|
|
1184
|
+
/** Register a `PATCH` route. */
|
|
1185
|
+
patch(path: string, handler: RouteHandler): Route;
|
|
1186
|
+
/** Register a `DELETE` route. */
|
|
1187
|
+
delete(path: string, handler: RouteHandler): Route;
|
|
1188
|
+
/** Register an `OPTIONS` route. */
|
|
1189
|
+
options(path: string, handler: RouteHandler): Route;
|
|
1190
|
+
/** Register a route answering every standard verb. The `Route::any()` equivalent. */
|
|
1191
|
+
any(path: string, handler: RouteHandler): Route;
|
|
1192
|
+
/** Register a route for an explicit set of verbs. The `Route::match()` equivalent. */
|
|
1193
|
+
on(methods: HttpMethod[], path: string, handler: RouteHandler): Route;
|
|
1194
|
+
/**
|
|
1195
|
+
* Install the renderer {@link Router.view} routes defer to — the seam an app (or a view package)
|
|
1196
|
+
* plugs its template engine into. Chains.
|
|
1197
|
+
*/
|
|
1198
|
+
renderViewsUsing(renderer: ViewRenderer): this;
|
|
1199
|
+
/**
|
|
1200
|
+
* Register a `GET` route that renders `view` with `data`.
|
|
1201
|
+
* `@plinthjs/http` ships no template engine, so rendering is deferred to the {@link ViewRenderer}
|
|
1202
|
+
* configured via {@link Router.renderViewsUsing} (or the `viewRenderer` construction option);
|
|
1203
|
+
* dispatching the route without one throws a clear error. The renderer's string becomes an HTML
|
|
1204
|
+
* {@link Response}.
|
|
1205
|
+
*/
|
|
1206
|
+
view(uri: string, view: string, data?: Record<string, unknown>): Route;
|
|
1207
|
+
/**
|
|
1208
|
+
* Register a route answering every verb with a redirect to `destination` (default `302`). The
|
|
1209
|
+
* `Route::redirect()` equivalent.
|
|
1210
|
+
*/
|
|
1211
|
+
redirect(uri: string, destination: string, status?: number): Route;
|
|
1212
|
+
/** Register a `301` redirect route. */
|
|
1213
|
+
permanentRedirect(uri: string, destination: string): Route;
|
|
1214
|
+
/**
|
|
1215
|
+
* Register the seven canonical RESTful routes for `controller` under `name`, mapping each verb+URI
|
|
1216
|
+
* to a controller method:
|
|
1217
|
+
*
|
|
1218
|
+
* - `GET name` → `index` (`name.index`)
|
|
1219
|
+
* - `GET name/create` → `create` (`name.create`)
|
|
1220
|
+
* - `POST name` → `store` (`name.store`)
|
|
1221
|
+
* - `GET name/{param}` → `show` (`name.show`)
|
|
1222
|
+
* - `GET name/{param}/edit` → `edit` (`name.edit`)
|
|
1223
|
+
* - `PUT|PATCH name/{param}` → `update` (`name.update`)
|
|
1224
|
+
* - `DELETE name/{param}` → `destroy` (`name.destroy`)
|
|
1225
|
+
*
|
|
1226
|
+
* `{param}` defaults to `Str.singular(name)` (override via `options.parameters` or `.parameters()`).
|
|
1227
|
+
* Returns a {@link ResourceRegistration} whose `.only()` / `.except()` / `.names()` /
|
|
1228
|
+
* `.parameters()` / `.shallow()` narrow or rename the set; the same controls are accepted via
|
|
1229
|
+
* `options`. Routes are **deferred**: they materialize (as normal, named, middleware-able,
|
|
1230
|
+
* cacheable {@link Route}s) the first time the router is matched/enumerated/url'd/cached, so
|
|
1231
|
+
* chaining after this call still takes effect. The enclosing {@link Router.group} context is
|
|
1232
|
+
* captured now and applied at build time.
|
|
1233
|
+
*/
|
|
1234
|
+
resource(name: string, controller: Newable, options?: ResourceOptions): ResourceRegistration;
|
|
1235
|
+
/**
|
|
1236
|
+
* Like {@link Router.resource} but for APIs: registers the same routes minus `create` and `edit`
|
|
1237
|
+
* (the HTML form-presenting endpoints).
|
|
1238
|
+
*/
|
|
1239
|
+
apiResource(name: string, controller: Newable, options?: ResourceOptions): ResourceRegistration;
|
|
1240
|
+
/** Shared builder for {@link Router.resource} / {@link Router.apiResource}. */
|
|
1241
|
+
private registerResource;
|
|
1242
|
+
/**
|
|
1243
|
+
* Register a singleton resource — routes for a resource with exactly one instance (a profile, a
|
|
1244
|
+
* settings page), mapping `GET name` → `show`, `GET name/edit` → `edit`, and `PUT|PATCH name` →
|
|
1245
|
+
* `update` (no `{param}` segment, no `index`/`create`/`store`). Chain {@link SingletonRegistration.destroyable} to add `DELETE name` → `destroy`.
|
|
1246
|
+
* Registration is deferred exactly like {@link Router.resource}.
|
|
1247
|
+
*/
|
|
1248
|
+
singleton(name: string, controller: Newable): SingletonRegistration;
|
|
1249
|
+
/**
|
|
1250
|
+
* Like {@link Router.singleton} but for APIs: omits the HTML `edit` route, registering only
|
|
1251
|
+
* `show` and `update` (plus `destroy` after `.destroyable()`).
|
|
1252
|
+
*/
|
|
1253
|
+
apiSingleton(name: string, controller: Newable): SingletonRegistration;
|
|
1254
|
+
/** Shared builder for {@link Router.singleton} / {@link Router.apiSingleton}. */
|
|
1255
|
+
private registerSingleton;
|
|
1256
|
+
/** Snapshot the active group stack into a {@link ResourceContext} for deferred resource building. */
|
|
1257
|
+
private currentResourceContext;
|
|
1258
|
+
/** The merged group-level parameter constraints, innermost group winning on a key clash. */
|
|
1259
|
+
private currentGroupWhere;
|
|
1260
|
+
/**
|
|
1261
|
+
* Materialize any not-yet-built resource registrations into real routes. Idempotent and cheap
|
|
1262
|
+
* after the first call; invoked by {@link Router.match}, {@link Router.getRoutes},
|
|
1263
|
+
* {@link Router.url}, and {@link Router.toCache} so deferred resources are always resolved before
|
|
1264
|
+
* the routes are observed.
|
|
1265
|
+
*/
|
|
1266
|
+
private flushResources;
|
|
1267
|
+
/** Apply a shared prefix and/or middleware to every route registered inside `callback`. */
|
|
1268
|
+
group(options: RouteGroupOptions, callback: (router: this) => void): this;
|
|
1269
|
+
/** Register a fallback handler invoked when no route matches. The `Route::fallback()` equivalent. */
|
|
1270
|
+
fallback(handler: RouteHandler): this;
|
|
1271
|
+
/** Register a route-model binding: a `{key}` param resolves through `resolver` (`Route::bind`). */
|
|
1272
|
+
bind(key: string, resolver: BindingResolver): this;
|
|
1273
|
+
/** The binding resolver registered for `key`, if any. */
|
|
1274
|
+
binding(key: string): BindingResolver | undefined;
|
|
1275
|
+
/**
|
|
1276
|
+
* Register a named middleware *group* — a list of references (concrete entries and/or other
|
|
1277
|
+
* alias/group names) that expand in place wherever the group name is used on a route or group. The
|
|
1278
|
+
* `Route::middlewareGroup('web', [...])` equivalent. Re-registering a name replaces it.
|
|
1279
|
+
* Names are resolved (recursively) at match time by {@link Router.resolveMiddleware}.
|
|
1280
|
+
*/
|
|
1281
|
+
middlewareGroup(name: string, entries: MiddlewareReference[]): this;
|
|
1282
|
+
/**
|
|
1283
|
+
* Register a middleware *alias* — a short `string` name for a single concrete {@link MiddlewareEntry}.
|
|
1284
|
+
*
|
|
1285
|
+
* Re-registering a name replaces it.
|
|
1286
|
+
*/
|
|
1287
|
+
aliasMiddleware(name: string, entry: MiddlewareEntry): this;
|
|
1288
|
+
/**
|
|
1289
|
+
* The references registered for a middleware group, or `undefined` when no group is registered
|
|
1290
|
+
* under `name`. Returns a copy; mutating it does not affect the registration.
|
|
1291
|
+
*/
|
|
1292
|
+
getMiddlewareGroup(name: string): MiddlewareReference[] | undefined;
|
|
1293
|
+
/** The concrete entry registered for a middleware alias, or `undefined` when none is registered. */
|
|
1294
|
+
getMiddlewareAlias(name: string): MiddlewareEntry | undefined;
|
|
1295
|
+
/**
|
|
1296
|
+
* Resolve a middleware reference list to concrete {@link MiddlewareEntry entries}, expanding
|
|
1297
|
+
* `string` names: a name resolves first as an **alias** (→ its single entry), else as a **group**
|
|
1298
|
+
* (→ its references, expanded recursively). An unknown name **throws** —, which
|
|
1299
|
+
* raises when a route references a middleware that is neither an alias nor a group. Cyclic group
|
|
1300
|
+
* references (a group that, directly or transitively, contains itself) also throw rather than
|
|
1301
|
+
* recursing without bound. Function/class entries pass through unchanged and in order.
|
|
1302
|
+
*
|
|
1303
|
+
* The {@link HttpKernel} calls this on a matched route's {@link Route.getMiddleware} stack before
|
|
1304
|
+
* running it.
|
|
1305
|
+
*/
|
|
1306
|
+
resolveMiddleware(references: readonly MiddlewareReference[]): MiddlewareEntry[];
|
|
1307
|
+
/**
|
|
1308
|
+
* Recursive worker for {@link Router.resolveMiddleware}. `groupPath` is the stack of group names
|
|
1309
|
+
* currently being expanded; revisiting a name already on the path is a cycle (a group that
|
|
1310
|
+
* directly or transitively contains itself) and throws. The same group may still appear in
|
|
1311
|
+
* sibling branches — only re-entrancy along a single path is rejected.
|
|
1312
|
+
*/
|
|
1313
|
+
private expandMiddleware;
|
|
1314
|
+
/** Every registered route (a copy). Pending resource registrations are materialized first. */
|
|
1315
|
+
getRoutes(): Route[];
|
|
1316
|
+
/**
|
|
1317
|
+
* Serialize the registered routes to a plain, JSON-serializable {@link RouteCache} snapshot
|
|
1318
|
+
* (methods, path, name, domain, middleware names, and the `[controller, method]` action).
|
|
1319
|
+
*
|
|
1320
|
+
* Closures cannot be serialized. Mirroring the conventional `route:cache` — which aborts with
|
|
1321
|
+
* "Unable to prepare route … for serialization. Uses Closure." — this **throws** when any route
|
|
1322
|
+
* uses a closure handler, rather than silently dropping it, so a cache is always complete or
|
|
1323
|
+
* absent. Rehydrate with {@link Router.loadCache} or {@link Router.fromCache}.
|
|
1324
|
+
*/
|
|
1325
|
+
toCache(): RouteCache;
|
|
1326
|
+
/**
|
|
1327
|
+
* Rehydrate a {@link RouteCache} onto this Router, appending the cached routes. `options.controller`
|
|
1328
|
+
* maps each cached controller name back to its constructor; an optional `options.middleware`
|
|
1329
|
+
* resolver reattaches middleware by name (omitted middleware are skipped). Returns `this`.
|
|
1330
|
+
*/
|
|
1331
|
+
loadCache(snapshot: RouteCache, options: LoadCacheOptions): this;
|
|
1332
|
+
/**
|
|
1333
|
+
* Build a fresh {@link Router} from a {@link RouteCache} snapshot, resolving cached controller
|
|
1334
|
+
* names through `resolver`. The static `route:cache` rehydration entry point; pass
|
|
1335
|
+
* {@link LoadCacheOptions} (or a bare {@link ControllerResolver}) plus optional {@link RouterOptions}.
|
|
1336
|
+
*/
|
|
1337
|
+
static fromCache(snapshot: RouteCache, resolver: ControllerResolver | LoadCacheOptions, options?: RouterOptions): Router;
|
|
1338
|
+
/**
|
|
1339
|
+
* Resolve an inbound `method`+`path` to a route, a 405, or a 404. When `host` is supplied, routes
|
|
1340
|
+
* carrying a {@link Route.domain domain} only match a host that satisfies the pattern, and the
|
|
1341
|
+
* domain's `{param}` labels are merged into the result ahead of the path params; routes without a
|
|
1342
|
+
* domain match regardless of host. When `host` is omitted, domain-carrying routes are skipped
|
|
1343
|
+
* (host-agnostic call sites keep their prior behavior for domain-less routes).
|
|
1344
|
+
*/
|
|
1345
|
+
match(method: string, path: string, host?: string): RouteMatch;
|
|
1346
|
+
/** Build (and memoize) the {@link DispatchIndex} over the current route list. */
|
|
1347
|
+
private buildDispatchIndex;
|
|
1348
|
+
/** Append a registered route and drop the dispatch index so the next match rebuilds it. */
|
|
1349
|
+
private registerRoute;
|
|
1350
|
+
/** Build a URL for a named route, optionally appending a query string. The `route()` helper. */
|
|
1351
|
+
url(name: string, params?: Record<string, string | number>, query?: Record<string, string | number>): string;
|
|
1352
|
+
/** Set (or replace) the secret used to sign and verify URLs. The app-key configuration step. */
|
|
1353
|
+
setSigningKey(key: string): this;
|
|
1354
|
+
/** The configured signing key, asserting one is set (signing without a key is a programmer error). */
|
|
1355
|
+
private requireKey;
|
|
1356
|
+
/**
|
|
1357
|
+
* Build a signed URL for the named route. The `URL::signedRoute()` equivalent: the route
|
|
1358
|
+
* URL is generated as usual, an optional `expires` (a {@link Date} or unix-seconds number) is
|
|
1359
|
+
* appended, and an HMAC `signature` over the canonical URL is added last. Verify it later with
|
|
1360
|
+
* {@link Router.hasValidSignature}.
|
|
1361
|
+
*/
|
|
1362
|
+
signedUrl(name: string, params?: Record<string, string | number>, expiresAt?: Date | number, query?: Record<string, string | number>): string;
|
|
1363
|
+
/**
|
|
1364
|
+
* Build a signed URL that expires after `expiresIn` seconds from now. The conventional
|
|
1365
|
+
* `URL::temporarySignedRoute()` equivalent (with the expiry expressed in seconds rather than a
|
|
1366
|
+
* `DateTime`/minutes).
|
|
1367
|
+
*/
|
|
1368
|
+
temporarySignedUrl(name: string, expiresIn: number, params?: Record<string, string | number>, query?: Record<string, string | number>): string;
|
|
1369
|
+
/**
|
|
1370
|
+
* Validate the signature on a `path?query` string, returning a {@link SignatureResult} describing
|
|
1371
|
+
* the outcome (`valid`, `missing`, `invalid`, or `expired`). The low-level check behind
|
|
1372
|
+
* {@link Router.hasValidSignature}; a `false`-returning caller can use this to distinguish *why*.
|
|
1373
|
+
*/
|
|
1374
|
+
validateSignature(url: string): SignatureResult;
|
|
1375
|
+
/**
|
|
1376
|
+
* Whether `req` carries a valid (and unexpired) signature. The `$request->hasValidSignature()`
|
|
1377
|
+
* equivalent: recomputes the HMAC over the request's path+query (minus `signature`) and compares
|
|
1378
|
+
* in constant time.
|
|
1379
|
+
*/
|
|
1380
|
+
hasValidSignature(req: Request): boolean;
|
|
1381
|
+
/**
|
|
1382
|
+
* A middleware that aborts unsigned/invalid/expired requests with a `403`. On a valid signature it passes control inward.
|
|
1383
|
+
*/
|
|
1384
|
+
signedMiddleware(): Middleware;
|
|
1385
|
+
private addRoute;
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
/**
|
|
1389
|
+
* `HttpKernel` — the request lifecycle.
|
|
1390
|
+
* {@link HttpKernel.handle} runs a request through the global middleware stack, matches it against
|
|
1391
|
+
* the {@link Router}, runs any route middleware, invokes the handler (resolving controller classes
|
|
1392
|
+
* through the `@plinthjs/core` container), and coerces the result to a {@link Response}.
|
|
1393
|
+
*
|
|
1394
|
+
* Errors (a missing route, a method mismatch, a throwing handler or route middleware) are rendered
|
|
1395
|
+
* to a {@link Response} *inside* the pipeline by the {@link ExceptionHandler}, so global middleware
|
|
1396
|
+
* always receive a real response from `next()` and can post-process it (save the session, set
|
|
1397
|
+
* cookies) even when the request failed. Terminable middleware run after the response exists.
|
|
1398
|
+
*
|
|
1399
|
+
* The kernel is socket-free: call `handle(request)` with a synthetic {@link Request} to test the
|
|
1400
|
+
* entire pipeline without a server.
|
|
1401
|
+
*/
|
|
1402
|
+
|
|
1403
|
+
/** Construction options for {@link HttpKernel}. */
|
|
1404
|
+
interface HttpKernelOptions {
|
|
1405
|
+
/** Global middleware wrapping every request, outermost first. */
|
|
1406
|
+
middleware?: MiddlewareEntry[];
|
|
1407
|
+
/** Container used to resolve controller classes for `[Controller, method]` route handlers. */
|
|
1408
|
+
container?: Container;
|
|
1409
|
+
/** Handler that renders thrown errors to responses. Defaults to a fresh {@link ExceptionHandler}. */
|
|
1410
|
+
exceptionHandler?: ExceptionHandler;
|
|
1411
|
+
}
|
|
1412
|
+
declare class HttpKernel {
|
|
1413
|
+
private readonly router;
|
|
1414
|
+
private readonly middleware;
|
|
1415
|
+
private readonly container;
|
|
1416
|
+
private readonly exceptionHandler;
|
|
1417
|
+
/** Composed per-route pipelines; see {@link HttpKernel.routePipeline} for the reuse rules. */
|
|
1418
|
+
private readonly pipelines;
|
|
1419
|
+
/** Resolved route actions (`null` = plain closure). `route.handler` is immutable, so no staleness. */
|
|
1420
|
+
private readonly actions;
|
|
1421
|
+
constructor(router: Router, options?: HttpKernelOptions);
|
|
1422
|
+
/**
|
|
1423
|
+
* Choose the {@link ExceptionHandler} by precedence: an explicit `options.exceptionHandler` wins;
|
|
1424
|
+
* otherwise a handler bound under {@link EXCEPTION_HANDLER} in the container (so an app or service
|
|
1425
|
+
* provider can install a custom handler) is resolved; otherwise a fresh {@link ExceptionHandler}.
|
|
1426
|
+
*/
|
|
1427
|
+
private static resolveHandler;
|
|
1428
|
+
/**
|
|
1429
|
+
* The active {@link ExceptionHandler} (after applying the {@link HttpKernel.resolveHandler}
|
|
1430
|
+
* precedence). Exposed so app wiring can configure its report sink, ignore list, etc.
|
|
1431
|
+
*/
|
|
1432
|
+
getExceptionHandler(): ExceptionHandler;
|
|
1433
|
+
/**
|
|
1434
|
+
* Report `error`, then render it to a {@link Response}. Used at both
|
|
1435
|
+
* pipeline catch sites so every thrown error is both reported and rendered.
|
|
1436
|
+
*/
|
|
1437
|
+
private reportThenRender;
|
|
1438
|
+
/** Run `req` through the full pipeline and return the resulting {@link Response}. */
|
|
1439
|
+
handle(req: Request): Promise<Response>;
|
|
1440
|
+
/**
|
|
1441
|
+
* The composed pipeline for `route` (its resolved middleware stack ending in the route action).
|
|
1442
|
+
* Cached per route so alias/group resolution and closure composition happen once, not per
|
|
1443
|
+
* request. A cached entry is reused only while the route's reference list is unchanged
|
|
1444
|
+
* ({@link sameReferences} — `route.middleware(...)` can append after registration), and stacks
|
|
1445
|
+
* containing `string` references are never cached: their alias/group registrations live in
|
|
1446
|
+
* mutable router registries and must be re-resolved each dispatch.
|
|
1447
|
+
*/
|
|
1448
|
+
private routePipeline;
|
|
1449
|
+
/**
|
|
1450
|
+
* Resolve the router's route-model bindings for the matched params, attaching the resolved models
|
|
1451
|
+
* to the request. A binding that resolves to nullish is a 404 (implicit-binding "not found").
|
|
1452
|
+
*/
|
|
1453
|
+
private bindModels;
|
|
1454
|
+
/**
|
|
1455
|
+
* Invoke a route's handler and coerce the result. A handler is one of: a closure (called with the
|
|
1456
|
+
* request), a `[Controller, method]` action, a `[Controller]` / bare-class invokable (its
|
|
1457
|
+
* `__invoke` is called), all resolved through the container. Bare-class invokables are told apart
|
|
1458
|
+
* from closures by {@link HttpKernel.resolveAction}.
|
|
1459
|
+
*/
|
|
1460
|
+
private runAction;
|
|
1461
|
+
/**
|
|
1462
|
+
* Normalize a {@link RouteHandler} to the controller class plus the method to invoke, or
|
|
1463
|
+
* `undefined` when it is a plain closure. A `[Controller, method]` tuple maps to itself; a
|
|
1464
|
+
* `[Controller]` tuple or a bare controller **class** maps to `[Controller, '__invoke']` (the
|
|
1465
|
+
* single-action controller form). Classes are distinguished from closures by their stringified
|
|
1466
|
+
* source (`class …`), so `router.get(path, Controller)` dispatches to `__invoke` while
|
|
1467
|
+
* `router.get(path, (req) => …)` stays a closure.
|
|
1468
|
+
*/
|
|
1469
|
+
private static resolveAction;
|
|
1470
|
+
/** Resolve a controller instance from the container, or construct it directly when none is set. */
|
|
1471
|
+
private resolveController;
|
|
1472
|
+
/** Coerce a handler result into a {@link Response}: strings → HTML, objects → JSON, nullish → 204. */
|
|
1473
|
+
private static toResponse;
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
/**
|
|
1477
|
+
* A dependency-free `multipart/form-data` parser, the body-side complement to {@link UploadedFile}.
|
|
1478
|
+
* It operates on the RAW request {@link Buffer} (never a utf8-decoded string, which would corrupt
|
|
1479
|
+
* binary file bytes) and splits it into text fields and file parts following RFC 7578 / 2046 CRLF
|
|
1480
|
+
* framing. Everything here is best-effort and defensive: a malformed body yields whatever could be
|
|
1481
|
+
* recovered (often nothing), and parsing never throws on a normal request.
|
|
1482
|
+
*/
|
|
1483
|
+
/** A single text field parsed from a multipart body (a part with no `filename`). */
|
|
1484
|
+
interface MultipartField {
|
|
1485
|
+
/** The field name from `Content-Disposition; name="…"`. */
|
|
1486
|
+
name: string;
|
|
1487
|
+
/** The field value, decoded from the part body as utf8. */
|
|
1488
|
+
value: string;
|
|
1489
|
+
}
|
|
1490
|
+
/** A single file part parsed from a multipart body (a part carrying a `filename`). */
|
|
1491
|
+
interface MultipartFilePart {
|
|
1492
|
+
/** The form field name from `Content-Disposition; name="…"`. */
|
|
1493
|
+
name: string;
|
|
1494
|
+
/** The client-supplied `filename="…"` (may be empty for an empty file input). */
|
|
1495
|
+
filename: string;
|
|
1496
|
+
/** The part's declared `Content-Type`, defaulting to `application/octet-stream`. */
|
|
1497
|
+
contentType: string;
|
|
1498
|
+
/** The raw file bytes, sliced from the request buffer with every byte intact. */
|
|
1499
|
+
content: Buffer;
|
|
1500
|
+
}
|
|
1501
|
+
/** The result of {@link parseMultipart}: the text fields and file parts, in document order. */
|
|
1502
|
+
interface MultipartParseResult {
|
|
1503
|
+
/** Every non-file part, as decoded text fields. */
|
|
1504
|
+
fields: MultipartField[];
|
|
1505
|
+
/** Every file part, with its raw bytes. */
|
|
1506
|
+
files: MultipartFilePart[];
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/** Options for {@link createServer}/{@link serve}. */
|
|
1510
|
+
interface ServerOptions {
|
|
1511
|
+
/**
|
|
1512
|
+
* The largest request body, in bytes, the adapter will buffer before answering
|
|
1513
|
+
* `413 Payload Too Large`. Defaults to 1 MiB (see {@link Request.fromNode}); raise it for routes
|
|
1514
|
+
* that legitimately accept big uploads.
|
|
1515
|
+
*/
|
|
1516
|
+
maxBodyBytes?: number;
|
|
1517
|
+
}
|
|
1518
|
+
/** Create a `node:http` server that pipes every request through `kernel`. Does not start listening. */
|
|
1519
|
+
declare function createServer(kernel: HttpKernel, options?: ServerOptions): Server;
|
|
1520
|
+
/** Create the server and start listening; resolves with the listening {@link Server}. */
|
|
1521
|
+
declare function serve(kernel: HttpKernel, port: number, host?: string, options?: ServerOptions): Promise<Server>;
|
|
1522
|
+
/** Options for {@link gracefulShutdown}. */
|
|
1523
|
+
interface GracefulShutdownOptions {
|
|
1524
|
+
/** Signals that trigger shutdown. Default `['SIGTERM', 'SIGINT']`. */
|
|
1525
|
+
signals?: readonly NodeJS.Signals[];
|
|
1526
|
+
/** Milliseconds to wait for in-flight requests before forcing exit. Default `10000`. */
|
|
1527
|
+
timeout?: number;
|
|
1528
|
+
/** Run after the server stops accepting and before exit — close DB pools, flush logs, etc. */
|
|
1529
|
+
onShutdown?: () => void | Promise<void>;
|
|
1530
|
+
/** Exit hook (override in tests). Default `process.exit`. */
|
|
1531
|
+
exit?: (code: number) => void;
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* Drain and stop a server on a termination signal — the production lifecycle Node needs (k8s/systemd
|
|
1535
|
+
* send `SIGTERM` on a rolling deploy). Stops accepting new connections, lets in-flight requests
|
|
1536
|
+
* finish (up to `timeout`), runs `onShutdown` (close the DB, etc.), then exits 0 — or exits 1 if the
|
|
1537
|
+
* drain times out. Returns an unsubscribe function that removes the signal handlers.
|
|
1538
|
+
*/
|
|
1539
|
+
declare function gracefulShutdown(server: Server, options?: GracefulShutdownOptions): () => void;
|
|
1540
|
+
|
|
1541
|
+
/** Options for {@link securityHeaders}. */
|
|
1542
|
+
interface SecurityHeadersOptions {
|
|
1543
|
+
/**
|
|
1544
|
+
* Send `Strict-Transport-Security` (only meaningful over HTTPS). `true` uses a one-year max-age;
|
|
1545
|
+
* pass `{ maxAge }` to override. Default `false` so local HTTP is not pinned to HTTPS.
|
|
1546
|
+
*/
|
|
1547
|
+
hsts?: boolean | {
|
|
1548
|
+
maxAge?: number;
|
|
1549
|
+
};
|
|
1550
|
+
/** `X-Frame-Options` value, or `false` to omit. Default `'SAMEORIGIN'` (clickjacking guard). */
|
|
1551
|
+
frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
|
|
1552
|
+
/** Send `X-Content-Type-Options: nosniff`. Default `true`. */
|
|
1553
|
+
noSniff?: boolean;
|
|
1554
|
+
/** `Referrer-Policy` value, or `false` to omit. Default `'strict-origin-when-cross-origin'`. */
|
|
1555
|
+
referrerPolicy?: string | false;
|
|
1556
|
+
}
|
|
1557
|
+
/**
|
|
1558
|
+
* Attach baseline security response headers — the helmet-style defaults a server-rendered app should
|
|
1559
|
+
* always set: `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, and optionally HSTS.
|
|
1560
|
+
* Existing headers are never overwritten, so a route can opt out per response.
|
|
1561
|
+
*/
|
|
1562
|
+
declare function securityHeaders(options?: SecurityHeadersOptions): Middleware;
|
|
1563
|
+
/** Options for {@link cors}. */
|
|
1564
|
+
interface CorsOptions {
|
|
1565
|
+
/** Allowed origin(s): `'*'`, an exact origin, a list, or a predicate. Default `'*'`. */
|
|
1566
|
+
origin?: string | readonly string[] | ((origin: string) => boolean);
|
|
1567
|
+
/** Allowed methods. Default the common verbs. */
|
|
1568
|
+
methods?: readonly string[];
|
|
1569
|
+
/** Allowed request headers. Default echoes the request's `Access-Control-Request-Headers`. */
|
|
1570
|
+
allowedHeaders?: readonly string[];
|
|
1571
|
+
/** Response headers exposed to the browser. */
|
|
1572
|
+
exposedHeaders?: readonly string[];
|
|
1573
|
+
/** Send `Access-Control-Allow-Credentials: true`. Default `false`. */
|
|
1574
|
+
credentials?: boolean;
|
|
1575
|
+
/** Preflight cache lifetime in seconds. Default `86400`. */
|
|
1576
|
+
maxAge?: number;
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Cross-Origin Resource Sharing — the `HandleCors` equivalent for API stacks. Answers preflight
|
|
1580
|
+
* `OPTIONS` with the negotiated headers and stamps actual responses with `Access-Control-Allow-*`.
|
|
1581
|
+
*/
|
|
1582
|
+
declare function cors(options?: CorsOptions): Middleware;
|
|
1583
|
+
/** The rate-limiter surface {@link throttle} needs — `@plinthjs/rate-limiter`'s `RateLimiter` fits by shape. */
|
|
1584
|
+
interface RateLimiterSeam {
|
|
1585
|
+
/** Record one hit against `key`, expiring after `decaySeconds`; returns the new count. */
|
|
1586
|
+
hit(key: string, decaySeconds?: number): number;
|
|
1587
|
+
/** Whether `key` has already been hit `maxAttempts` times within its window. */
|
|
1588
|
+
tooManyAttempts(key: string, maxAttempts: number): boolean;
|
|
1589
|
+
/** Seconds until `key` may be attempted again (`0` when available now). */
|
|
1590
|
+
availableIn(key: string): number;
|
|
1591
|
+
}
|
|
1592
|
+
/** Options for {@link throttle}. */
|
|
1593
|
+
interface ThrottleOptions {
|
|
1594
|
+
/** The shared limiter (inject `@plinthjs/rate-limiter`'s `RateLimiter`). */
|
|
1595
|
+
limiter: RateLimiterSeam;
|
|
1596
|
+
/** Max requests allowed per window. Default `60`. */
|
|
1597
|
+
max?: number;
|
|
1598
|
+
/** Window length in seconds. Default `60`. */
|
|
1599
|
+
decaySeconds?: number;
|
|
1600
|
+
/** The throttle key for a request. Default the client ip + method + path. */
|
|
1601
|
+
key?: (req: Request) => string;
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Rate-limit requests — the `throttle:max,minutes` middleware. Over the limit, responds
|
|
1605
|
+
* `429 Too Many Requests` with a `Retry-After` header; otherwise records a hit and continues. Key by
|
|
1606
|
+
* ip+route by default; pass `key` to scope it (e.g. by login email).
|
|
1607
|
+
*/
|
|
1608
|
+
declare function throttle(options: ThrottleOptions): Middleware;
|
|
1609
|
+
|
|
1610
|
+
/**
|
|
1611
|
+
* @plinthjs/http — the conventional API and its supporting layer (Tier 3).
|
|
1612
|
+
*
|
|
1613
|
+
* The {@link Request} / {@link Response} value objects — including response macros
|
|
1614
|
+
* ({@link Response.macro}), redirect helpers with flash intent ({@link Response.redirectTo} /
|
|
1615
|
+
* {@link Response.with}), and file/download builders ({@link Response.file} /
|
|
1616
|
+
* {@link Response.download}) — the async middleware pipeline ({@link Middleware} /
|
|
1617
|
+
* {@link runMiddleware}, with {@link TerminableMiddleware} support), the HTTP exception hierarchy
|
|
1618
|
+
* ({@link HttpException} and friends) and its {@link ExceptionHandler}, the {@link Router} (params,
|
|
1619
|
+
* optional params, groups, named routes + URL generation, signed URLs via {@link Router.signedUrl},
|
|
1620
|
+
* fallback), the {@link HttpKernel} that drives the request lifecycle over the `@plinthjs/core`
|
|
1621
|
+
* container, and a {@link createServer}/{@link serve} adapter over Node's built-in `node:http`.
|
|
1622
|
+
*/
|
|
1623
|
+
/** The Plinth version this build of `http` ships with. */
|
|
1624
|
+
declare const VERSION = "0.1.0";
|
|
1625
|
+
|
|
1626
|
+
export { type BindingResolver, type CachedRoute, Controller, type ControllerAction, type ControllerResolver, type CookieOptions, type CorsOptions, EXCEPTION_HANDLER, ExceptionHandler, type FlashBag, type FromNodeOptions, type GracefulShutdownOptions, HttpException, HttpKernel, type HttpKernelOptions, type HttpMethod, type InvokableAction, type JsonStreamData, type JsonValue, type LoadCacheOptions, type LogLevel, MethodNotAllowedHttpException, type Middleware, type MiddlewareEntry, type MiddlewareReference, type MiddlewareResolver, type MultipartField, type MultipartFilePart, type MultipartParseResult, type Next, NotFoundHttpException, PayloadTooLargeHttpException, type RateLimiterSeam, type RenderableCallback, type ReportSink, type ReportableCallback, Request, type RequestInit, type ResourceMethod, type ResourceOptions, ResourceRegistration, Response, type ResponseMacro, Route, type RouteCache, type RouteGroupOptions, type RouteHandler, type RouteHandlerClosure, type RouteMatch, type RouteResult, Router, type RouterOptions, type SecurityHeadersOptions, type ServerOptions, type SignatureResult, type SingletonMethod, SingletonRegistration, type StreamChunk, type StreamSource, type TerminableMiddleware, type ThrottleOptions, UploadedFile, type UploadedFileInit, VERSION, type ViewRenderer, type WherePattern, cors, createServer, gracefulShutdown, isTerminable, runMiddleware, securityHeaders, serve, terminateMiddleware, throttle };
|