@plinthjs/http 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +157 -2
- package/dist/index.cjs +3091 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1639 -0
- package/dist/index.d.ts +1639 -0
- package/dist/index.js +3061 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,3061 @@
|
|
|
1
|
+
import { once } from 'events';
|
|
2
|
+
import { readFileSync, mkdirSync, writeFileSync } from 'fs';
|
|
3
|
+
import path2 from 'path';
|
|
4
|
+
import { Str, collect, filled } from '@plinthjs/support';
|
|
5
|
+
import { createHmac, timingSafeEqual } from 'crypto';
|
|
6
|
+
import { createServer as createServer$1 } from 'http';
|
|
7
|
+
|
|
8
|
+
// src/controller.ts
|
|
9
|
+
var Controller = class {
|
|
10
|
+
};
|
|
11
|
+
var MIME_TYPES = {
|
|
12
|
+
txt: "text/plain; charset=utf-8",
|
|
13
|
+
html: "text/html; charset=utf-8",
|
|
14
|
+
htm: "text/html; charset=utf-8",
|
|
15
|
+
css: "text/css; charset=utf-8",
|
|
16
|
+
csv: "text/csv; charset=utf-8",
|
|
17
|
+
js: "text/javascript; charset=utf-8",
|
|
18
|
+
mjs: "text/javascript; charset=utf-8",
|
|
19
|
+
json: "application/json; charset=utf-8",
|
|
20
|
+
xml: "application/xml; charset=utf-8",
|
|
21
|
+
pdf: "application/pdf",
|
|
22
|
+
zip: "application/zip",
|
|
23
|
+
gz: "application/gzip",
|
|
24
|
+
png: "image/png",
|
|
25
|
+
jpg: "image/jpeg",
|
|
26
|
+
jpeg: "image/jpeg",
|
|
27
|
+
gif: "image/gif",
|
|
28
|
+
webp: "image/webp",
|
|
29
|
+
svg: "image/svg+xml",
|
|
30
|
+
ico: "image/x-icon",
|
|
31
|
+
woff: "font/woff",
|
|
32
|
+
woff2: "font/woff2",
|
|
33
|
+
ttf: "font/ttf",
|
|
34
|
+
mp4: "video/mp4",
|
|
35
|
+
mp3: "audio/mpeg",
|
|
36
|
+
wav: "audio/wav",
|
|
37
|
+
bin: "application/octet-stream"
|
|
38
|
+
};
|
|
39
|
+
function mimeTypeFor(filePath) {
|
|
40
|
+
const ext = path2.extname(filePath).slice(1).toLowerCase();
|
|
41
|
+
return MIME_TYPES[ext] ?? "application/octet-stream";
|
|
42
|
+
}
|
|
43
|
+
function contentDisposition(filename) {
|
|
44
|
+
const ascii = filename.replaceAll(/[^ -~]/g, "_").replaceAll(/["\\]/g, String.raw`\$&`);
|
|
45
|
+
let header = `attachment; filename="${ascii}"`;
|
|
46
|
+
if (/[^ -~]/.test(filename)) {
|
|
47
|
+
header += `; filename*=UTF-8''${encodeURIComponent(filename)}`;
|
|
48
|
+
}
|
|
49
|
+
return header;
|
|
50
|
+
}
|
|
51
|
+
function isIterableValue(value) {
|
|
52
|
+
if (typeof value !== "object" || value === null) return false;
|
|
53
|
+
const candidate = value;
|
|
54
|
+
return typeof candidate[Symbol.iterator] === "function" || typeof candidate[Symbol.asyncIterator] === "function";
|
|
55
|
+
}
|
|
56
|
+
function stringifyJson(value) {
|
|
57
|
+
return JSON.stringify(value);
|
|
58
|
+
}
|
|
59
|
+
async function* jsonArrayChunks(items) {
|
|
60
|
+
yield "[";
|
|
61
|
+
let first = true;
|
|
62
|
+
for await (const item of items) {
|
|
63
|
+
yield `${first ? "" : ","}${stringifyJson(item) ?? "null"}`;
|
|
64
|
+
first = false;
|
|
65
|
+
}
|
|
66
|
+
yield "]";
|
|
67
|
+
}
|
|
68
|
+
async function* jsonChunks(data) {
|
|
69
|
+
if (isIterableValue(data)) {
|
|
70
|
+
yield* jsonArrayChunks(data);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
yield "{";
|
|
74
|
+
let first = true;
|
|
75
|
+
for (const [key, value] of Object.entries(data)) {
|
|
76
|
+
yield `${first ? "" : ","}${JSON.stringify(key)}:`;
|
|
77
|
+
first = false;
|
|
78
|
+
if (isIterableValue(value)) yield* jsonArrayChunks(value);
|
|
79
|
+
else yield stringifyJson(value) ?? "null";
|
|
80
|
+
}
|
|
81
|
+
yield "}";
|
|
82
|
+
}
|
|
83
|
+
function serializeCookie(name, value, options = {}) {
|
|
84
|
+
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? "/"}`];
|
|
85
|
+
if (options.maxAge !== void 0) parts.push(`Max-Age=${Math.floor(options.maxAge)}`);
|
|
86
|
+
if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);
|
|
87
|
+
if (options.domain) parts.push(`Domain=${options.domain}`);
|
|
88
|
+
if (options.secure) parts.push("Secure");
|
|
89
|
+
if (options.httpOnly) parts.push("HttpOnly");
|
|
90
|
+
if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
|
|
91
|
+
return parts.join("; ");
|
|
92
|
+
}
|
|
93
|
+
var Response = class _Response {
|
|
94
|
+
/** The HTTP status code. */
|
|
95
|
+
status;
|
|
96
|
+
/** The response headers (canonical-ish casing as set). */
|
|
97
|
+
headers;
|
|
98
|
+
/** The response body, already serialized to a string (or `null` for no body). */
|
|
99
|
+
body;
|
|
100
|
+
/** Any `Set-Cookie` header values, kept separate so multiple cookies survive serialization. */
|
|
101
|
+
setCookies = [];
|
|
102
|
+
/**
|
|
103
|
+
* The encoding used to flush {@link Response.body}. Text bodies are UTF-8; binary file bodies are
|
|
104
|
+
* read and written as `'binary'` (latin1) so every byte survives the string round-trip intact and
|
|
105
|
+
* matches the `Content-Length` set by {@link Response.file}/{@link Response.download}.
|
|
106
|
+
*/
|
|
107
|
+
bodyEncoding = "utf8";
|
|
108
|
+
/** Flash intent queued by {@link Response.with}; drained by the session layer (Laravel flash). */
|
|
109
|
+
flashData = {};
|
|
110
|
+
/** The streaming body source, when this is a streamed response (see {@link Response.stream}). */
|
|
111
|
+
streamSource;
|
|
112
|
+
/** The registered response macros, shared across all instances (the `Response::macro` registry). */
|
|
113
|
+
static macros = /* @__PURE__ */ new Map();
|
|
114
|
+
constructor(body, status) {
|
|
115
|
+
this.status = status;
|
|
116
|
+
this.headers = {};
|
|
117
|
+
this.body = body;
|
|
118
|
+
}
|
|
119
|
+
/** Begin building a response with an optional body and status. The `response()` helper equivalent. */
|
|
120
|
+
static make(body = null, status = 200) {
|
|
121
|
+
return new _Response(body, status);
|
|
122
|
+
}
|
|
123
|
+
/** Build a JSON response, serializing `data` and setting `Content-Type`. The `response()->json()` equivalent. */
|
|
124
|
+
static json(data, status = 200) {
|
|
125
|
+
return new _Response(null, status).json(data, status);
|
|
126
|
+
}
|
|
127
|
+
/** Build a plain-text response. */
|
|
128
|
+
static text(body, status = 200) {
|
|
129
|
+
return new _Response(null, status).text(body);
|
|
130
|
+
}
|
|
131
|
+
/** Build an HTML response. */
|
|
132
|
+
static html(body, status = 200) {
|
|
133
|
+
return new _Response(null, status).html(body);
|
|
134
|
+
}
|
|
135
|
+
/** Build an empty `204 No Content` response. The `response()->noContent()` equivalent. */
|
|
136
|
+
static noContent(status = 204) {
|
|
137
|
+
return new _Response(null, status).noContent(status);
|
|
138
|
+
}
|
|
139
|
+
/** Build a redirect to `url`. The `redirect()` helper equivalent. */
|
|
140
|
+
static redirect(url, status = 302) {
|
|
141
|
+
return new _Response(null, status).redirect(url, status);
|
|
142
|
+
}
|
|
143
|
+
/** Build a redirect to `url`. The `redirect()->to()` / `Redirect::to()` equivalent. */
|
|
144
|
+
static redirectTo(url, status = 302) {
|
|
145
|
+
return new _Response(null, status).redirect(url, status);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Build a redirect back to the previous URL, falling back to `fallback` (default `/`) when no
|
|
149
|
+
* referer is known. The `back()` / `redirect()->back()` equivalent.
|
|
150
|
+
*
|
|
151
|
+
* As a static this has no request in scope, so it relies on `fallback`; middleware that knows the
|
|
152
|
+
* incoming `Referer` should pass it explicitly.
|
|
153
|
+
*/
|
|
154
|
+
static back(fallback = "/", status = 302) {
|
|
155
|
+
return new _Response(null, status).redirect(fallback, status);
|
|
156
|
+
}
|
|
157
|
+
// --- File responses ------------------------------------------------------
|
|
158
|
+
/**
|
|
159
|
+
* Build a response that serves the file at `path` inline (no download prompt), inferring
|
|
160
|
+
* `Content-Type` from the extension and setting `Content-Length`. The `response()->file()`
|
|
161
|
+
* equivalent. The file is read synchronously into the body.
|
|
162
|
+
*/
|
|
163
|
+
static file(filePath, headers = {}) {
|
|
164
|
+
const buffer = readFileSync(filePath);
|
|
165
|
+
const response = new _Response(buffer.toString("binary"), 200);
|
|
166
|
+
response.bodyEncoding = "binary";
|
|
167
|
+
response.headers["Content-Type"] = mimeTypeFor(filePath);
|
|
168
|
+
response.headers["Content-Length"] = String(buffer.byteLength);
|
|
169
|
+
Object.assign(response.headers, headers);
|
|
170
|
+
return response;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Build a download response (`Content-Disposition: attachment`) for the file at `path`, using
|
|
174
|
+
* `name` as the download filename (defaulting to the path's basename). The `response()->download()`
|
|
175
|
+
* equivalent. The file is read synchronously into the body.
|
|
176
|
+
*/
|
|
177
|
+
static download(filePath, name, headers = {}) {
|
|
178
|
+
const buffer = readFileSync(filePath);
|
|
179
|
+
const filename = name ?? path2.basename(filePath);
|
|
180
|
+
const response = new _Response(buffer.toString("binary"), 200);
|
|
181
|
+
response.bodyEncoding = "binary";
|
|
182
|
+
response.headers["Content-Type"] = mimeTypeFor(filePath);
|
|
183
|
+
response.headers["Content-Length"] = String(buffer.byteLength);
|
|
184
|
+
response.headers["Content-Disposition"] = contentDisposition(filename);
|
|
185
|
+
Object.assign(response.headers, headers);
|
|
186
|
+
return response;
|
|
187
|
+
}
|
|
188
|
+
// --- Streaming responses (the `response()->stream*()` family) -------------
|
|
189
|
+
/**
|
|
190
|
+
* Build a streamed response: `source` (an iterable, async iterable, or a generator/factory
|
|
191
|
+
* returning one) is consumed chunk by chunk as the response is flushed, each chunk written to the
|
|
192
|
+
* client as it yields — the `response()->stream()` equivalent. No `Content-Length` is set, so
|
|
193
|
+
* Node serves it with chunked transfer encoding. The kernel/server adapter flushes streamed
|
|
194
|
+
* responses via {@link Response.writeStreamTo}.
|
|
195
|
+
*/
|
|
196
|
+
static stream(source, status = 200, headers = {}) {
|
|
197
|
+
const response = new _Response(null, status);
|
|
198
|
+
response.streamSource = source;
|
|
199
|
+
Object.assign(response.headers, headers);
|
|
200
|
+
return response;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Build a streamed download: like {@link Response.stream} but with
|
|
204
|
+
* `Content-Disposition: attachment` for `filename` and a default `application/octet-stream`
|
|
205
|
+
* content type (override via `headers`). The `response()->streamDownload()` equivalent.
|
|
206
|
+
*/
|
|
207
|
+
static streamDownload(source, filename, headers = {}) {
|
|
208
|
+
return _Response.stream(source, 200, {
|
|
209
|
+
"Content-Type": "application/octet-stream",
|
|
210
|
+
"Content-Disposition": contentDisposition(filename),
|
|
211
|
+
...headers
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Build a streamed JSON response — the `response()->streamJson()` equivalent. An iterable (or
|
|
216
|
+
* async iterable) of rows is streamed as one JSON array, each row serialized as it yields; an
|
|
217
|
+
* object is emitted key by key with iterable values streamed as arrays and plain values encoded
|
|
218
|
+
* in place. Useful for serializing large result sets without buffering them.
|
|
219
|
+
*/
|
|
220
|
+
static streamJson(data, status = 200) {
|
|
221
|
+
return _Response.stream(jsonChunks(data), status, {
|
|
222
|
+
"Content-Type": "application/json; charset=utf-8"
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
/** Whether this is a streamed response (flush it with {@link Response.writeStreamTo}). */
|
|
226
|
+
isStream() {
|
|
227
|
+
return this.streamSource !== void 0;
|
|
228
|
+
}
|
|
229
|
+
// --- Macros (the `Response::macro` extension point) -----------------------
|
|
230
|
+
/**
|
|
231
|
+
* Register a reusable response builder under `name`. The Laravel `Response::macro()` equivalent —
|
|
232
|
+
* application code installs a named factory once and invokes it via {@link Response.callMacro}
|
|
233
|
+
* (`Response.callMacro('caps', text)`). Re-registering a name overwrites the previous macro.
|
|
234
|
+
*/
|
|
235
|
+
static macro(name, fn) {
|
|
236
|
+
_Response.macros.set(name, fn);
|
|
237
|
+
}
|
|
238
|
+
/** Whether a macro named `name` has been registered. The `Response::hasMacro()` equivalent. */
|
|
239
|
+
static hasMacro(name) {
|
|
240
|
+
return _Response.macros.has(name);
|
|
241
|
+
}
|
|
242
|
+
/** Install many macros at once from a plain object of builders. The `Macroable::mixin()` analog. */
|
|
243
|
+
static mixin(macros) {
|
|
244
|
+
for (const [name, fn] of Object.entries(macros)) _Response.macros.set(name, fn);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Invoke a previously {@link Response.macro registered} macro by name, forwarding `args` and
|
|
248
|
+
* returning the {@link Response} it builds. Throws when no macro is registered under `name` (the
|
|
249
|
+
* `BadMethodCallException` Laravel raises for an unknown macro). Typed pragmatically: callers cast
|
|
250
|
+
* `args` to the macro's expected parameters.
|
|
251
|
+
*/
|
|
252
|
+
static callMacro(name, ...args) {
|
|
253
|
+
const fn = _Response.macros.get(name);
|
|
254
|
+
if (fn === void 0) throw new Error(`Response macro [${name}] is not defined.`);
|
|
255
|
+
return fn(...args);
|
|
256
|
+
}
|
|
257
|
+
// --- Fluent builders -----------------------------------------------------
|
|
258
|
+
/** Set the status code. */
|
|
259
|
+
setStatus(code) {
|
|
260
|
+
this.status = code;
|
|
261
|
+
return this;
|
|
262
|
+
}
|
|
263
|
+
/** Set a single header. The `->header()` equivalent. */
|
|
264
|
+
header(name, value) {
|
|
265
|
+
this.headers[name] = value;
|
|
266
|
+
return this;
|
|
267
|
+
}
|
|
268
|
+
/** Merge a header map onto the response. The `->withHeaders()` equivalent. */
|
|
269
|
+
withHeaders(headers) {
|
|
270
|
+
Object.assign(this.headers, headers);
|
|
271
|
+
return this;
|
|
272
|
+
}
|
|
273
|
+
/** Serialize `data` to JSON, set the body and `Content-Type`, and (optionally) the status. */
|
|
274
|
+
json(data, status) {
|
|
275
|
+
if (status !== void 0) this.status = status;
|
|
276
|
+
this.headers["Content-Type"] = "application/json; charset=utf-8";
|
|
277
|
+
this.body = JSON.stringify(data);
|
|
278
|
+
return this;
|
|
279
|
+
}
|
|
280
|
+
/** Set a plain-text body and `Content-Type`. */
|
|
281
|
+
text(body) {
|
|
282
|
+
this.headers["Content-Type"] = "text/plain; charset=utf-8";
|
|
283
|
+
this.body = body;
|
|
284
|
+
return this;
|
|
285
|
+
}
|
|
286
|
+
/** Set an HTML body and `Content-Type`. */
|
|
287
|
+
html(body) {
|
|
288
|
+
this.headers["Content-Type"] = "text/html; charset=utf-8";
|
|
289
|
+
this.body = body;
|
|
290
|
+
return this;
|
|
291
|
+
}
|
|
292
|
+
/** Clear the body and set a no-content status. */
|
|
293
|
+
noContent(status = 204) {
|
|
294
|
+
this.status = status;
|
|
295
|
+
this.body = null;
|
|
296
|
+
return this;
|
|
297
|
+
}
|
|
298
|
+
/** Turn this into a redirect to `url` with a `Location` header. */
|
|
299
|
+
redirect(url, status = 302) {
|
|
300
|
+
this.status = status;
|
|
301
|
+
this.headers["Location"] = url;
|
|
302
|
+
this.body = null;
|
|
303
|
+
return this;
|
|
304
|
+
}
|
|
305
|
+
/** Alias of {@link Response.redirect} reading as `redirect()->to()`. */
|
|
306
|
+
redirectTo(url, status = 302) {
|
|
307
|
+
return this.redirect(url, status);
|
|
308
|
+
}
|
|
309
|
+
/** Retarget this redirect at `fallback` (the previous-URL fallback when no referer is known). */
|
|
310
|
+
back(fallback = "/", status = 302) {
|
|
311
|
+
return this.redirect(fallback, status);
|
|
312
|
+
}
|
|
313
|
+
with(keyOrData, value) {
|
|
314
|
+
if (typeof keyOrData === "string") {
|
|
315
|
+
this.flashData[keyOrData] = value;
|
|
316
|
+
} else {
|
|
317
|
+
Object.assign(this.flashData, keyOrData);
|
|
318
|
+
}
|
|
319
|
+
return this;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Flash an `input` bag for repopulating a form after a redirect. The `redirect()->withInput()`
|
|
323
|
+
* equivalent: the bag is stored under the `input` flash key.
|
|
324
|
+
*/
|
|
325
|
+
withInput(input) {
|
|
326
|
+
this.flashData["input"] = input;
|
|
327
|
+
return this;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Flash a validation `errors` bag. The `redirect()->withErrors()` equivalent: the bag is stored
|
|
331
|
+
* under the `errors` flash key for the next request's view.
|
|
332
|
+
*/
|
|
333
|
+
withErrors(errors) {
|
|
334
|
+
this.flashData["errors"] = errors;
|
|
335
|
+
return this;
|
|
336
|
+
}
|
|
337
|
+
/** The queued flash intent (a copy) for the session layer to consume. */
|
|
338
|
+
flashes() {
|
|
339
|
+
return { ...this.flashData };
|
|
340
|
+
}
|
|
341
|
+
/** Read a single queued flash value by key, or `undefined` when absent. */
|
|
342
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is a caller-supplied cast for the stored flash value
|
|
343
|
+
getFlash(key) {
|
|
344
|
+
return key in this.flashData ? this.flashData[key] : void 0;
|
|
345
|
+
}
|
|
346
|
+
/** Queue a `Set-Cookie` header. Multiple calls accumulate distinct cookies. */
|
|
347
|
+
cookie(name, value, options) {
|
|
348
|
+
this.setCookies.push(serializeCookie(name, value, options));
|
|
349
|
+
return this;
|
|
350
|
+
}
|
|
351
|
+
/** The queued `Set-Cookie` header values (a copy). */
|
|
352
|
+
cookies() {
|
|
353
|
+
return [...this.setCookies];
|
|
354
|
+
}
|
|
355
|
+
// --- Output --------------------------------------------------------------
|
|
356
|
+
/** Write the status, headers, and cookies (everything before the body) to `res`. */
|
|
357
|
+
writeHead(res) {
|
|
358
|
+
const headers = this.headers;
|
|
359
|
+
for (const name of Object.keys(headers)) res.setHeader(name, headers[name]);
|
|
360
|
+
if (this.setCookies.length > 0) res.setHeader("Set-Cookie", this.setCookies);
|
|
361
|
+
res.statusCode = this.status;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Flush this response to a Node {@link ServerResponse}: status, headers, cookies, then body.
|
|
365
|
+
* Streamed responses ({@link Response.stream}) must be flushed with the async
|
|
366
|
+
* {@link Response.writeStreamTo} instead — calling `writeTo` on one throws so a stream is never
|
|
367
|
+
* silently dropped.
|
|
368
|
+
*/
|
|
369
|
+
writeTo(res) {
|
|
370
|
+
if (this.streamSource !== void 0) {
|
|
371
|
+
throw new Error("This is a streamed response; flush it with writeStreamTo() instead.");
|
|
372
|
+
}
|
|
373
|
+
this.writeHead(res);
|
|
374
|
+
if (this.body === null) {
|
|
375
|
+
res.end();
|
|
376
|
+
} else {
|
|
377
|
+
res.end(this.body, this.bodyEncoding);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Flush a streamed response to a Node {@link ServerResponse}: status, headers, and cookies first,
|
|
382
|
+
* then each chunk the {@link StreamSource} yields is written as it arrives (respecting
|
|
383
|
+
* backpressure via `drain`), and the response is ended when the source completes. Falls back to
|
|
384
|
+
* {@link Response.writeTo} semantics when this response has no stream.
|
|
385
|
+
*/
|
|
386
|
+
async writeStreamTo(res) {
|
|
387
|
+
const source = this.streamSource;
|
|
388
|
+
if (source === void 0) {
|
|
389
|
+
this.writeTo(res);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
this.writeHead(res);
|
|
393
|
+
const iterable = typeof source === "function" ? source() : source;
|
|
394
|
+
for await (const chunk of iterable) {
|
|
395
|
+
if (!res.write(chunk)) await once(res, "drain");
|
|
396
|
+
}
|
|
397
|
+
res.end();
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
// src/exceptions.ts
|
|
402
|
+
var EXCEPTION_HANDLER = /* @__PURE__ */ Symbol("mason.exceptionHandler");
|
|
403
|
+
var HttpException = class extends Error {
|
|
404
|
+
constructor(status, message = "", headers = {}) {
|
|
405
|
+
super(message);
|
|
406
|
+
this.status = status;
|
|
407
|
+
this.name = "HttpException";
|
|
408
|
+
this.headers = headers;
|
|
409
|
+
}
|
|
410
|
+
status;
|
|
411
|
+
/** Extra headers to attach to the rendered response. */
|
|
412
|
+
headers;
|
|
413
|
+
};
|
|
414
|
+
var NotFoundHttpException = class extends HttpException {
|
|
415
|
+
constructor(message = "Not Found") {
|
|
416
|
+
super(404, message);
|
|
417
|
+
this.name = "NotFoundHttpException";
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
var MethodNotAllowedHttpException = class extends HttpException {
|
|
421
|
+
constructor(allowed = [], message = "Method Not Allowed") {
|
|
422
|
+
super(405, message, allowed.length > 0 ? { Allow: allowed.join(", ") } : {});
|
|
423
|
+
this.name = "MethodNotAllowedHttpException";
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
function reasonPhrase(status) {
|
|
427
|
+
const phrases = {
|
|
428
|
+
400: "Bad Request",
|
|
429
|
+
401: "Unauthorized",
|
|
430
|
+
403: "Forbidden",
|
|
431
|
+
404: "Not Found",
|
|
432
|
+
405: "Method Not Allowed",
|
|
433
|
+
422: "Unprocessable Entity",
|
|
434
|
+
500: "Internal Server Error"
|
|
435
|
+
};
|
|
436
|
+
return phrases[status] ?? "Error";
|
|
437
|
+
}
|
|
438
|
+
var ExceptionHandler = class {
|
|
439
|
+
/**
|
|
440
|
+
* @param debug When `true`, non-HTTP errors expose their real message (and a stack hint in JSON);
|
|
441
|
+
* otherwise they render a generic `500`. The `APP_DEBUG` equivalent.
|
|
442
|
+
*/
|
|
443
|
+
constructor(debug = false) {
|
|
444
|
+
this.debug = debug;
|
|
445
|
+
}
|
|
446
|
+
debug;
|
|
447
|
+
/** Reportable callbacks, run in registration order by {@link ExceptionHandler.report}. */
|
|
448
|
+
reportCallbacks = [];
|
|
449
|
+
/** Renderable callbacks, tried in registration order by {@link ExceptionHandler.render}. */
|
|
450
|
+
renderCallbacks = [];
|
|
451
|
+
/**
|
|
452
|
+
* Error constructors whose instances are not reported. Seeded with {@link HttpException} (an
|
|
453
|
+
* `instanceof` check, so every subclass — 404/405/… — is covered too), mirroring Laravel's small
|
|
454
|
+
* internal don't-report list. Extend with {@link ExceptionHandler.ignore} / shrink with
|
|
455
|
+
* {@link ExceptionHandler.stopIgnoring}.
|
|
456
|
+
*/
|
|
457
|
+
ignored = [HttpException];
|
|
458
|
+
/** The terminal report sink; a no-op by default. Replace via {@link ExceptionHandler.reportUsing}. */
|
|
459
|
+
reportSink = () => {
|
|
460
|
+
};
|
|
461
|
+
/** When `true`, an already-reported error instance is skipped on later {@link report} calls. */
|
|
462
|
+
deduplicate = false;
|
|
463
|
+
/** Exception mappings, applied (first match wins) before reporting/rendering. See {@link map}. */
|
|
464
|
+
mappers = [];
|
|
465
|
+
/** Per-constructor log levels consulted by {@link ExceptionHandler.levelFor}. */
|
|
466
|
+
levels = [];
|
|
467
|
+
/**
|
|
468
|
+
* Input keys never flashed back to the session on a validation redirect — the Laravel
|
|
469
|
+
* `$dontFlash` list, seeded with its defaults. `@plinthjs/http` itself has no redirect/flash path,
|
|
470
|
+
* so the list is stored here and exposed via {@link ExceptionHandler.getDontFlash} for the
|
|
471
|
+
* session/validation layer to consume when it re-flashes old input.
|
|
472
|
+
*/
|
|
473
|
+
dontFlashKeys = ["current_password", "password", "password_confirmation"];
|
|
474
|
+
/** Error instances already reported, for {@link ExceptionHandler.withoutDuplicates} de-duplication. */
|
|
475
|
+
reported = /* @__PURE__ */ new WeakSet();
|
|
476
|
+
/**
|
|
477
|
+
* The status code an error should render as: an {@link HttpException}'s status, a numeric `status`
|
|
478
|
+
* carried structurally by the error (e.g. a validation `422` or authorization `403`), else `500`.
|
|
479
|
+
*/
|
|
480
|
+
statusFor(error) {
|
|
481
|
+
if (error instanceof HttpException) return error.status;
|
|
482
|
+
return carriedStatus(error) ?? 500;
|
|
483
|
+
}
|
|
484
|
+
// --- Exception mapping / levels / dontFlash --------------------------------
|
|
485
|
+
/**
|
|
486
|
+
* Map one exception type to another: whenever an instance of `from` reaches the handler, it is
|
|
487
|
+
* first converted via `to` and the *result* is reported and rendered instead. The Laravel
|
|
488
|
+
* `$exceptions->map(From::class, fn ($e) => new To(..., $e))` equivalent. Mappings are checked in
|
|
489
|
+
* registration order; the first `instanceof` match applies (once — the mapped error is not
|
|
490
|
+
* re-mapped). Chains.
|
|
491
|
+
*/
|
|
492
|
+
map(from, to) {
|
|
493
|
+
this.mappers.push([from, to]);
|
|
494
|
+
return this;
|
|
495
|
+
}
|
|
496
|
+
/** Apply the first matching {@link ExceptionHandler.map} mapping to `error`, if any. */
|
|
497
|
+
mapException(error) {
|
|
498
|
+
for (const [from, to] of this.mappers) {
|
|
499
|
+
if (error instanceof from) return to(error);
|
|
500
|
+
}
|
|
501
|
+
return error;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Set the log level instances of `ctor` are reported at — the Laravel
|
|
505
|
+
* `$exceptions->level(Type::class, LogLevel::WARNING)` equivalent. The level is surfaced as the
|
|
506
|
+
* `level` key of the context passed to the {@link ReportSink}. Chains.
|
|
507
|
+
*/
|
|
508
|
+
level(ctor, logLevel) {
|
|
509
|
+
this.levels.push([ctor, logLevel]);
|
|
510
|
+
return this;
|
|
511
|
+
}
|
|
512
|
+
/** The log level `error` reports at: the first registered `instanceof` match, else `'error'`. */
|
|
513
|
+
levelFor(error) {
|
|
514
|
+
for (const [ctor, logLevel] of this.levels) {
|
|
515
|
+
if (error instanceof ctor) return logLevel;
|
|
516
|
+
}
|
|
517
|
+
return "error";
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Replace the list of input keys that must never be flashed back on a validation redirect — the
|
|
521
|
+
* Laravel `$exceptions->dontFlash([...])` equivalent. Defaults to `current_password`, `password`,
|
|
522
|
+
* and `password_confirmation`. There is no redirect/flash path inside `@plinthjs/http`, so the list
|
|
523
|
+
* is exposed via {@link ExceptionHandler.getDontFlash} for the session/validation layer that
|
|
524
|
+
* re-flashes old input. Chains.
|
|
525
|
+
*/
|
|
526
|
+
dontFlash(keys) {
|
|
527
|
+
this.dontFlashKeys = [...keys];
|
|
528
|
+
return this;
|
|
529
|
+
}
|
|
530
|
+
/** The input keys never flashed back on a validation redirect (a copy). */
|
|
531
|
+
getDontFlash() {
|
|
532
|
+
return [...this.dontFlashKeys];
|
|
533
|
+
}
|
|
534
|
+
// --- Reporting (the `report()` half of Laravel's Handler) -----------------
|
|
535
|
+
/**
|
|
536
|
+
* Register a reportable callback. Runs in order during {@link ExceptionHandler.report}; returning
|
|
537
|
+
* `false` from a callback stops all further reporting of that error. Chains.
|
|
538
|
+
*/
|
|
539
|
+
reportable(callback) {
|
|
540
|
+
this.reportCallbacks.push(callback);
|
|
541
|
+
return this;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Add error constructors to the don't-report list (the Laravel `ignore()` / `$dontReport`
|
|
545
|
+
* equivalent). Matching is by `instanceof`, so a base class also suppresses its subclasses. Chains.
|
|
546
|
+
*/
|
|
547
|
+
ignore(...classes) {
|
|
548
|
+
this.ignored.push(...classes);
|
|
549
|
+
return this;
|
|
550
|
+
}
|
|
551
|
+
/** Alias of {@link ExceptionHandler.ignore} — the Laravel `$dontReport` spelling. */
|
|
552
|
+
dontReport(...classes) {
|
|
553
|
+
return this.ignore(...classes);
|
|
554
|
+
}
|
|
555
|
+
/** Remove error constructors from the don't-report list. The Laravel `stopIgnoring()` equivalent. */
|
|
556
|
+
stopIgnoring(...classes) {
|
|
557
|
+
const drop = new Set(classes);
|
|
558
|
+
for (let i = this.ignored.length - 1; i >= 0; i--) {
|
|
559
|
+
if (drop.has(this.ignored[i])) this.ignored.splice(i, 1);
|
|
560
|
+
}
|
|
561
|
+
return this;
|
|
562
|
+
}
|
|
563
|
+
/** Whether `error` should be reported: `false` when it (or a superclass) is in the ignore list. */
|
|
564
|
+
shouldReport(error) {
|
|
565
|
+
for (const ctor of this.ignored) {
|
|
566
|
+
if (error instanceof ctor) return false;
|
|
567
|
+
}
|
|
568
|
+
return true;
|
|
569
|
+
}
|
|
570
|
+
/** Replace the terminal report sink (the logger seam). The Laravel `reportable`/logger wiring. */
|
|
571
|
+
reportUsing(sink) {
|
|
572
|
+
this.reportSink = sink;
|
|
573
|
+
return this;
|
|
574
|
+
}
|
|
575
|
+
/** De-duplicate reports: the same error instance is reported at most once. The `withoutDuplicates()` flag. */
|
|
576
|
+
withoutDuplicates() {
|
|
577
|
+
this.deduplicate = true;
|
|
578
|
+
return this;
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* A hook for additional report context, merged into every report. Override in a subclass to attach
|
|
582
|
+
* request-scoped data (user id, etc.). The Laravel `Handler::context()` equivalent.
|
|
583
|
+
*/
|
|
584
|
+
context() {
|
|
585
|
+
return {};
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Report `error`: if {@link ExceptionHandler.shouldReport} and not a duplicate (when
|
|
589
|
+
* {@link ExceptionHandler.withoutDuplicates} is on), run the reportable callbacks in order — a
|
|
590
|
+
* `false` return stops the chain (the default sink is skipped) — otherwise fall through to the
|
|
591
|
+
* terminal sink. The Laravel `Handler::report()` equivalent.
|
|
592
|
+
*/
|
|
593
|
+
report(error) {
|
|
594
|
+
const mapped = this.mapException(error);
|
|
595
|
+
if (!this.shouldReport(mapped)) return;
|
|
596
|
+
if (this.deduplicate && typeof mapped === "object" && mapped !== null) {
|
|
597
|
+
if (this.reported.has(mapped)) return;
|
|
598
|
+
this.reported.add(mapped);
|
|
599
|
+
}
|
|
600
|
+
for (const callback of this.reportCallbacks) {
|
|
601
|
+
if (callback(mapped) === false) return;
|
|
602
|
+
}
|
|
603
|
+
this.reportSink(mapped, { level: this.levelFor(mapped), ...this.context() });
|
|
604
|
+
}
|
|
605
|
+
/** Register a renderable callback, tried first by {@link ExceptionHandler.render}. Chains. */
|
|
606
|
+
renderable(callback) {
|
|
607
|
+
this.renderCallbacks.push(callback);
|
|
608
|
+
return this;
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Render `error` to a {@link Response}, negotiating JSON vs. HTML from `req`. Any
|
|
612
|
+
* {@link ExceptionHandler.map} mapping is applied first, so renderables and the default rendering
|
|
613
|
+
* see the mapped error.
|
|
614
|
+
*/
|
|
615
|
+
render(req, rawError) {
|
|
616
|
+
const error = this.mapException(rawError);
|
|
617
|
+
for (const callback of this.renderCallbacks) {
|
|
618
|
+
const response = callback(error, req);
|
|
619
|
+
if (response !== void 0) return response;
|
|
620
|
+
}
|
|
621
|
+
const status = this.statusFor(error);
|
|
622
|
+
const isHttp = error instanceof HttpException;
|
|
623
|
+
const message = this.messageFor(error, status, isHttp);
|
|
624
|
+
const extraHeaders = isHttp ? error.headers : {};
|
|
625
|
+
const errors = carriedErrors(error);
|
|
626
|
+
if (req.wantsJson()) {
|
|
627
|
+
const payload = { message, status };
|
|
628
|
+
if (errors !== void 0) payload["errors"] = errors;
|
|
629
|
+
if (this.debug && error instanceof Error && error.stack) payload["exception"] = error.stack;
|
|
630
|
+
return Response.json(payload, status).withHeaders(extraHeaders);
|
|
631
|
+
}
|
|
632
|
+
if (errors !== void 0) {
|
|
633
|
+
const back = req.header("referer") ?? "/";
|
|
634
|
+
return Response.redirectTo(back).withErrors(errors).withInput(req.except(this.dontFlashKeys));
|
|
635
|
+
}
|
|
636
|
+
const html = `<!doctype html><html><head><title>${status} ${reasonPhrase(status)}</title></head><body><h1>${status} ${reasonPhrase(status)}</h1><p>${escapeHtml(message)}</p></body></html>`;
|
|
637
|
+
return Response.html(html, status).withHeaders(extraHeaders);
|
|
638
|
+
}
|
|
639
|
+
/** The user-facing message for an error, hiding internals for non-debug `500`s. */
|
|
640
|
+
messageFor(error, status, isHttp) {
|
|
641
|
+
if (isHttp && error instanceof HttpException && error.message) return error.message;
|
|
642
|
+
if (status >= 500 && !this.debug) return reasonPhrase(status);
|
|
643
|
+
if (error instanceof Error && error.message) return error.message;
|
|
644
|
+
return reasonPhrase(status);
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
function carriedStatus(error) {
|
|
648
|
+
if (typeof error === "object" && error !== null && "status" in error) {
|
|
649
|
+
const { status } = error;
|
|
650
|
+
if (typeof status === "number") return status;
|
|
651
|
+
}
|
|
652
|
+
return void 0;
|
|
653
|
+
}
|
|
654
|
+
function carriedErrors(error) {
|
|
655
|
+
if (typeof error === "object" && error !== null && "errors" in error) {
|
|
656
|
+
const { errors } = error;
|
|
657
|
+
if (typeof errors === "object" && errors !== null) {
|
|
658
|
+
return errors;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return void 0;
|
|
662
|
+
}
|
|
663
|
+
function escapeHtml(input) {
|
|
664
|
+
return input.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// src/middleware.ts
|
|
668
|
+
function isTerminable(entry) {
|
|
669
|
+
return typeof entry === "object" && typeof entry.terminate === "function";
|
|
670
|
+
}
|
|
671
|
+
function toHandle(entry) {
|
|
672
|
+
return typeof entry === "function" ? entry : entry.handle;
|
|
673
|
+
}
|
|
674
|
+
function composeMiddleware(stack, destination) {
|
|
675
|
+
let next = destination;
|
|
676
|
+
for (let index = stack.length - 1; index >= 0; index -= 1) {
|
|
677
|
+
const entry = stack[index];
|
|
678
|
+
if (entry === void 0) continue;
|
|
679
|
+
const handle = toHandle(entry);
|
|
680
|
+
const inner = next;
|
|
681
|
+
next = (request) => handle(request, inner);
|
|
682
|
+
}
|
|
683
|
+
return next;
|
|
684
|
+
}
|
|
685
|
+
function runMiddleware(req, stack, destination) {
|
|
686
|
+
return composeMiddleware(stack, destination)(req);
|
|
687
|
+
}
|
|
688
|
+
async function terminateMiddleware(req, res, stack) {
|
|
689
|
+
for (const entry of stack) {
|
|
690
|
+
if (isTerminable(entry)) {
|
|
691
|
+
await entry.terminate(req, res);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// src/kernel.ts
|
|
697
|
+
function isClassConstructor(fn) {
|
|
698
|
+
return Function.prototype.toString.call(fn).startsWith("class");
|
|
699
|
+
}
|
|
700
|
+
function sameReferences(a, b) {
|
|
701
|
+
return a.length === b.length && a.every((reference, index) => reference === b[index]);
|
|
702
|
+
}
|
|
703
|
+
var HttpKernel = class _HttpKernel {
|
|
704
|
+
router;
|
|
705
|
+
middleware;
|
|
706
|
+
container;
|
|
707
|
+
exceptionHandler;
|
|
708
|
+
/** Composed per-route pipelines; see {@link HttpKernel.routePipeline} for the reuse rules. */
|
|
709
|
+
pipelines = /* @__PURE__ */ new WeakMap();
|
|
710
|
+
/** Resolved route actions (`null` = plain closure). `route.handler` is immutable, so no staleness. */
|
|
711
|
+
actions = /* @__PURE__ */ new WeakMap();
|
|
712
|
+
constructor(router, options = {}) {
|
|
713
|
+
this.router = router;
|
|
714
|
+
this.middleware = options.middleware ?? [];
|
|
715
|
+
this.container = options.container;
|
|
716
|
+
this.exceptionHandler = _HttpKernel.resolveHandler(options.exceptionHandler, this.container);
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Choose the {@link ExceptionHandler} by precedence: an explicit `options.exceptionHandler` wins;
|
|
720
|
+
* otherwise a handler bound under {@link EXCEPTION_HANDLER} in the container (so an app or service
|
|
721
|
+
* provider can install a custom handler) is resolved; otherwise a fresh {@link ExceptionHandler}.
|
|
722
|
+
*/
|
|
723
|
+
static resolveHandler(explicit, container) {
|
|
724
|
+
if (explicit !== void 0) return explicit;
|
|
725
|
+
if (container?.bound(EXCEPTION_HANDLER) === true) {
|
|
726
|
+
return container.make(EXCEPTION_HANDLER);
|
|
727
|
+
}
|
|
728
|
+
return new ExceptionHandler();
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* The active {@link ExceptionHandler} (after applying the {@link HttpKernel.resolveHandler}
|
|
732
|
+
* precedence). Exposed so app wiring can configure its report sink, ignore list, etc.
|
|
733
|
+
*/
|
|
734
|
+
getExceptionHandler() {
|
|
735
|
+
return this.exceptionHandler;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Report `error` (guarded so a throwing report can never break rendering — the Laravel handler
|
|
739
|
+
* also isolates reporting from rendering), then render it to a {@link Response}. Used at both
|
|
740
|
+
* pipeline catch sites so every thrown error is both reported and rendered.
|
|
741
|
+
*/
|
|
742
|
+
reportThenRender(req, error) {
|
|
743
|
+
try {
|
|
744
|
+
this.exceptionHandler.report(error);
|
|
745
|
+
} catch {
|
|
746
|
+
}
|
|
747
|
+
return this.exceptionHandler.render(req, error);
|
|
748
|
+
}
|
|
749
|
+
/** Run `req` through the full pipeline and return the resulting {@link Response}. */
|
|
750
|
+
async handle(req) {
|
|
751
|
+
let routeTerminables = [];
|
|
752
|
+
const dispatch2 = async (outerReq) => {
|
|
753
|
+
try {
|
|
754
|
+
const matched = this.router.match(outerReq.method(), outerReq.path(), outerReq.host());
|
|
755
|
+
if (matched.type === "not-found") throw new NotFoundHttpException();
|
|
756
|
+
if (matched.type === "method-not-allowed") {
|
|
757
|
+
throw new MethodNotAllowedHttpException(matched.allowed);
|
|
758
|
+
}
|
|
759
|
+
const entry = this.routePipeline(matched.route);
|
|
760
|
+
routeTerminables = entry.terminables;
|
|
761
|
+
let prepared = outerReq.withParams(matched.params);
|
|
762
|
+
const routeName = matched.route.getName();
|
|
763
|
+
if (routeName !== void 0) prepared = prepared.withRouteName(routeName);
|
|
764
|
+
const bound = await this.bindModels(prepared, matched.params);
|
|
765
|
+
return await entry.pipeline(bound);
|
|
766
|
+
} catch (error) {
|
|
767
|
+
return this.reportThenRender(outerReq, error);
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
let response;
|
|
771
|
+
try {
|
|
772
|
+
response = this.middleware.length === 0 ? await dispatch2(req) : await runMiddleware(req, this.middleware, dispatch2);
|
|
773
|
+
} catch (error) {
|
|
774
|
+
response = this.reportThenRender(req, error);
|
|
775
|
+
}
|
|
776
|
+
if (req.method() === "HEAD") response.body = null;
|
|
777
|
+
if (this.middleware.length > 0) {
|
|
778
|
+
await terminateMiddleware(req, response, [...this.middleware, ...routeTerminables]);
|
|
779
|
+
} else if (routeTerminables.length > 0) {
|
|
780
|
+
await terminateMiddleware(req, response, routeTerminables);
|
|
781
|
+
}
|
|
782
|
+
return response;
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* The composed pipeline for `route` (its resolved middleware stack ending in the route action).
|
|
786
|
+
* Cached per route so alias/group resolution and closure composition happen once, not per
|
|
787
|
+
* request. A cached entry is reused only while the route's reference list is unchanged
|
|
788
|
+
* ({@link sameReferences} — `route.middleware(...)` can append after registration), and stacks
|
|
789
|
+
* containing `string` references are never cached: their alias/group registrations live in
|
|
790
|
+
* mutable router registries and must be re-resolved each dispatch.
|
|
791
|
+
*/
|
|
792
|
+
routePipeline(route) {
|
|
793
|
+
const source = route.getMiddleware();
|
|
794
|
+
const cached = this.pipelines.get(route);
|
|
795
|
+
if (cached !== void 0 && sameReferences(cached.source, source)) return cached;
|
|
796
|
+
const entries = this.router.resolveMiddleware(source);
|
|
797
|
+
const built = {
|
|
798
|
+
source,
|
|
799
|
+
terminables: entries.filter((entry) => isTerminable(entry)),
|
|
800
|
+
pipeline: composeMiddleware(entries, (request) => this.runAction(route, request))
|
|
801
|
+
};
|
|
802
|
+
if (!source.some((reference) => typeof reference === "string")) {
|
|
803
|
+
this.pipelines.set(route, built);
|
|
804
|
+
}
|
|
805
|
+
return built;
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Resolve the router's route-model bindings for the matched params, attaching the resolved models
|
|
809
|
+
* to the request. A binding that resolves to nullish is a 404 (implicit-binding "not found").
|
|
810
|
+
*/
|
|
811
|
+
async bindModels(req, params) {
|
|
812
|
+
const keys = Object.keys(params);
|
|
813
|
+
if (keys.length === 0) return req;
|
|
814
|
+
let resolved;
|
|
815
|
+
for (const key of keys) {
|
|
816
|
+
const resolver = this.router.binding(key);
|
|
817
|
+
if (resolver === void 0) continue;
|
|
818
|
+
const value = params[key];
|
|
819
|
+
if (value === void 0) continue;
|
|
820
|
+
const model = await resolver(value, req);
|
|
821
|
+
if (model === null || model === void 0) throw new NotFoundHttpException();
|
|
822
|
+
resolved ??= {};
|
|
823
|
+
resolved[key] = model;
|
|
824
|
+
}
|
|
825
|
+
return resolved === void 0 ? req : req.withBoundModels(resolved);
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Invoke a route's handler and coerce the result. A handler is one of: a closure (called with the
|
|
829
|
+
* request), a `[Controller, method]` action, a `[Controller]` / bare-class invokable (its
|
|
830
|
+
* `__invoke` is called), all resolved through the container. Bare-class invokables are told apart
|
|
831
|
+
* from closures by {@link HttpKernel.resolveAction}.
|
|
832
|
+
*/
|
|
833
|
+
async runAction(route, req) {
|
|
834
|
+
let target = this.actions.get(route);
|
|
835
|
+
if (target === void 0) {
|
|
836
|
+
target = _HttpKernel.resolveAction(route.handler) ?? null;
|
|
837
|
+
this.actions.set(route, target);
|
|
838
|
+
}
|
|
839
|
+
if (target === null) {
|
|
840
|
+
return _HttpKernel.toResponse(await route.handler(req));
|
|
841
|
+
}
|
|
842
|
+
const [controller, method] = target;
|
|
843
|
+
const instance = this.resolveController(controller);
|
|
844
|
+
const action = instance[method];
|
|
845
|
+
if (typeof action !== "function") {
|
|
846
|
+
throw new TypeError(`Controller action [${controller.name}@${method}] is not callable.`);
|
|
847
|
+
}
|
|
848
|
+
return _HttpKernel.toResponse(await action.call(instance, req));
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Normalize a {@link RouteHandler} to the controller class plus the method to invoke, or
|
|
852
|
+
* `undefined` when it is a plain closure. A `[Controller, method]` tuple maps to itself; a
|
|
853
|
+
* `[Controller]` tuple or a bare controller **class** maps to `[Controller, '__invoke']` (the
|
|
854
|
+
* single-action controller form). Classes are distinguished from closures by their stringified
|
|
855
|
+
* source (`class …`), so `router.get(path, Controller)` dispatches to `__invoke` while
|
|
856
|
+
* `router.get(path, (req) => …)` stays a closure.
|
|
857
|
+
*/
|
|
858
|
+
static resolveAction(handler) {
|
|
859
|
+
if (Array.isArray(handler)) {
|
|
860
|
+
const [controller, method] = handler;
|
|
861
|
+
return [controller, method ?? "__invoke"];
|
|
862
|
+
}
|
|
863
|
+
if (typeof handler === "function" && isClassConstructor(handler)) {
|
|
864
|
+
return [handler, "__invoke"];
|
|
865
|
+
}
|
|
866
|
+
return void 0;
|
|
867
|
+
}
|
|
868
|
+
/** Resolve a controller instance from the container, or construct it directly when none is set. */
|
|
869
|
+
resolveController(controller) {
|
|
870
|
+
const instance = this.container ? this.container.make(controller) : new controller();
|
|
871
|
+
return instance;
|
|
872
|
+
}
|
|
873
|
+
/** Coerce a handler result into a {@link Response}: strings → HTML, objects → JSON, nullish → 204. */
|
|
874
|
+
static toResponse(result) {
|
|
875
|
+
if (result instanceof Response) return result;
|
|
876
|
+
if (result === null || result === void 0) return Response.noContent();
|
|
877
|
+
if (typeof result === "string") return Response.html(result);
|
|
878
|
+
return Response.json(result);
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
// src/multipart.ts
|
|
883
|
+
var CRLF = "\r\n";
|
|
884
|
+
var HEADER_SEPARATOR = Buffer.from(CRLF + CRLF, "utf8");
|
|
885
|
+
function boundaryFromContentType(contentType) {
|
|
886
|
+
if (contentType === void 0) return void 0;
|
|
887
|
+
const lower = contentType.toLowerCase();
|
|
888
|
+
if (!lower.includes("multipart/form-data")) return void 0;
|
|
889
|
+
const match = /;\s*boundary=("([^"]*)"|[^;]+)/i.exec(contentType);
|
|
890
|
+
if (match === null) return void 0;
|
|
891
|
+
const raw = match[2] ?? match[1] ?? "";
|
|
892
|
+
return raw.trim().length === 0 ? void 0 : raw.trim();
|
|
893
|
+
}
|
|
894
|
+
function parseHeaders(headerBlock) {
|
|
895
|
+
const headers = /* @__PURE__ */ new Map();
|
|
896
|
+
for (const line of headerBlock.split(CRLF)) {
|
|
897
|
+
if (line.length === 0) continue;
|
|
898
|
+
const colon = line.indexOf(":");
|
|
899
|
+
if (colon === -1) continue;
|
|
900
|
+
const name = line.slice(0, colon).trim().toLowerCase();
|
|
901
|
+
const value = line.slice(colon + 1).trim();
|
|
902
|
+
if (name.length > 0) headers.set(name, value);
|
|
903
|
+
}
|
|
904
|
+
return headers;
|
|
905
|
+
}
|
|
906
|
+
function dispositionParam(disposition, key) {
|
|
907
|
+
const quoted = new RegExp(`${key}${String.raw`\s*=\s*`}"([^"]*)"`, "i").exec(disposition);
|
|
908
|
+
if (quoted !== null) return quoted[1];
|
|
909
|
+
const bare = new RegExp(`${key}${String.raw`\s*=\s*`}([^;]+)`, "i").exec(disposition);
|
|
910
|
+
if (bare === null) return void 0;
|
|
911
|
+
return bare[1] === void 0 ? void 0 : bare[1].trim();
|
|
912
|
+
}
|
|
913
|
+
function parsePart(part, fields, files) {
|
|
914
|
+
const headerEnd = part.indexOf(HEADER_SEPARATOR);
|
|
915
|
+
if (headerEnd === -1) return;
|
|
916
|
+
const headerBlock = part.subarray(0, headerEnd).toString("utf8");
|
|
917
|
+
const body = part.subarray(headerEnd + HEADER_SEPARATOR.length);
|
|
918
|
+
const headers = parseHeaders(headerBlock);
|
|
919
|
+
const disposition = headers.get("content-disposition");
|
|
920
|
+
if (disposition === void 0) return;
|
|
921
|
+
const name = dispositionParam(disposition, "name");
|
|
922
|
+
if (name === void 0) return;
|
|
923
|
+
const filename = dispositionParam(disposition, "filename");
|
|
924
|
+
if (filename === void 0) {
|
|
925
|
+
fields.push({ name, value: body.toString("utf8") });
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
files.push({
|
|
929
|
+
name,
|
|
930
|
+
filename,
|
|
931
|
+
contentType: headers.get("content-type") ?? "application/octet-stream",
|
|
932
|
+
// Copy out of the source buffer so the part owns an independent slice of bytes.
|
|
933
|
+
content: Buffer.from(body)
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
function parseMultipart(buffer, boundary) {
|
|
937
|
+
const fields = [];
|
|
938
|
+
const files = [];
|
|
939
|
+
if (buffer.length === 0 || boundary.length === 0) return { fields, files };
|
|
940
|
+
const delimiter = Buffer.from(`--${boundary}`, "utf8");
|
|
941
|
+
const positions = [];
|
|
942
|
+
let from = buffer.indexOf(delimiter, 0);
|
|
943
|
+
while (from !== -1) {
|
|
944
|
+
positions.push(from);
|
|
945
|
+
from = buffer.indexOf(delimiter, from + delimiter.length);
|
|
946
|
+
}
|
|
947
|
+
if (positions.length < 2) return { fields, files };
|
|
948
|
+
for (let i = 0; i < positions.length - 1; i++) {
|
|
949
|
+
let start = positions[i] + delimiter.length;
|
|
950
|
+
const end = positions[i + 1];
|
|
951
|
+
if (buffer[start] === 45 && buffer[start + 1] === 45) break;
|
|
952
|
+
if (buffer[start] === 13 && buffer[start + 1] === 10) start += 2;
|
|
953
|
+
let stop = end;
|
|
954
|
+
if (buffer[stop - 2] === 13 && buffer[stop - 1] === 10) stop -= 2;
|
|
955
|
+
if (stop <= start) continue;
|
|
956
|
+
parsePart(buffer.subarray(start, stop), fields, files);
|
|
957
|
+
}
|
|
958
|
+
return { fields, files };
|
|
959
|
+
}
|
|
960
|
+
var UploadedFile = class {
|
|
961
|
+
/** The original filename the client supplied. The `getClientOriginalName()` value. */
|
|
962
|
+
clientOriginalName;
|
|
963
|
+
/** The declared MIME type of the upload. */
|
|
964
|
+
mimeType;
|
|
965
|
+
/** The size of the uploaded content in bytes. */
|
|
966
|
+
size;
|
|
967
|
+
/** The uploaded bytes, held in memory. */
|
|
968
|
+
content;
|
|
969
|
+
constructor(init) {
|
|
970
|
+
this.clientOriginalName = init.clientOriginalName;
|
|
971
|
+
this.mimeType = init.mimeType;
|
|
972
|
+
this.content = init.content;
|
|
973
|
+
this.size = init.content.byteLength;
|
|
974
|
+
}
|
|
975
|
+
/** The raw uploaded bytes. The `get()` content accessor (Laravel `$file->get()`). */
|
|
976
|
+
get() {
|
|
977
|
+
return this.content;
|
|
978
|
+
}
|
|
979
|
+
/** The raw uploaded bytes — an alias for {@link UploadedFile.get} reading more naturally as bytes. */
|
|
980
|
+
buffer() {
|
|
981
|
+
return this.content;
|
|
982
|
+
}
|
|
983
|
+
/** The client-supplied original filename. The `$file->getClientOriginalName()` equivalent. */
|
|
984
|
+
getClientOriginalName() {
|
|
985
|
+
return this.clientOriginalName;
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* The file extension derived from the client original name (lower-cased, no leading dot), or `''`
|
|
989
|
+
* when the name has none. The `$file->getClientOriginalExtension()` equivalent.
|
|
990
|
+
*/
|
|
991
|
+
getClientOriginalExtension() {
|
|
992
|
+
return path2.extname(this.clientOriginalName).slice(1).toLowerCase();
|
|
993
|
+
}
|
|
994
|
+
/** The declared MIME type of the upload. The `$file->getMimeType()` equivalent. */
|
|
995
|
+
getMimeType() {
|
|
996
|
+
return this.mimeType;
|
|
997
|
+
}
|
|
998
|
+
/** The size of the uploaded content in bytes. The `$file->getSize()` equivalent. */
|
|
999
|
+
getSize() {
|
|
1000
|
+
return this.size;
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Whether the upload is valid — here, simply that it carries a non-empty filename. Mirrors the
|
|
1004
|
+
* Laravel `$file->isValid()` predicate at this layer (no PHP upload-error codes exist in Node).
|
|
1005
|
+
*/
|
|
1006
|
+
isValid() {
|
|
1007
|
+
return this.clientOriginalName.length > 0;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Write the upload to `directory` under a generated unique name, creating the directory as needed,
|
|
1011
|
+
* and return the full path written. The `$file->store('dir')` equivalent (sans disk abstraction).
|
|
1012
|
+
*/
|
|
1013
|
+
store(directory) {
|
|
1014
|
+
return this.storeAs(directory, this.hashName());
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Write the upload to `directory` under `name`, creating the directory as needed, and return the
|
|
1018
|
+
* full path written. The `$file->storeAs('dir', 'name')` equivalent.
|
|
1019
|
+
*/
|
|
1020
|
+
storeAs(directory, name) {
|
|
1021
|
+
const destination = path2.join(directory, name);
|
|
1022
|
+
return this.move(destination);
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Write the upload to the exact file path `destination`, creating its parent directory as needed,
|
|
1026
|
+
* and return `destination`. The `$file->move()` equivalent — the documented filesystem seam.
|
|
1027
|
+
*/
|
|
1028
|
+
move(destination) {
|
|
1029
|
+
mkdirSync(path2.dirname(destination), { recursive: true });
|
|
1030
|
+
writeFileSync(destination, this.content);
|
|
1031
|
+
return destination;
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* A unique storage filename preserving the original extension — a timestamp/random base, the way
|
|
1035
|
+
* Laravel's `hashName()` produces a collision-resistant name. Used by {@link UploadedFile.store}.
|
|
1036
|
+
*/
|
|
1037
|
+
hashName() {
|
|
1038
|
+
const extension = this.getClientOriginalExtension();
|
|
1039
|
+
const base = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
1040
|
+
return extension.length > 0 ? `${base}.${extension}` : base;
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
|
|
1044
|
+
// src/request.ts
|
|
1045
|
+
var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
|
|
1046
|
+
var PayloadTooLargeHttpException = class extends HttpException {
|
|
1047
|
+
constructor(message = "Payload Too Large") {
|
|
1048
|
+
super(413, message);
|
|
1049
|
+
this.name = "PayloadTooLargeHttpException";
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
function normalizeHeaders(headers) {
|
|
1053
|
+
const map = /* @__PURE__ */ new Map();
|
|
1054
|
+
if (!headers) return map;
|
|
1055
|
+
for (const key of Object.keys(headers)) {
|
|
1056
|
+
const raw = headers[key];
|
|
1057
|
+
if (raw === void 0) continue;
|
|
1058
|
+
map.set(key.toLowerCase(), Array.isArray(raw) ? raw.join(", ") : raw);
|
|
1059
|
+
}
|
|
1060
|
+
return map;
|
|
1061
|
+
}
|
|
1062
|
+
function parseUrlEncoded(input) {
|
|
1063
|
+
const out = {};
|
|
1064
|
+
const params = new URLSearchParams(input);
|
|
1065
|
+
for (const [key, val] of params.entries()) out[key] = val;
|
|
1066
|
+
return out;
|
|
1067
|
+
}
|
|
1068
|
+
var DUMMY_HOST = "http://localhost";
|
|
1069
|
+
function stripPort(host) {
|
|
1070
|
+
if (host === void 0 || host.length === 0) return void 0;
|
|
1071
|
+
const colon = host.lastIndexOf(":");
|
|
1072
|
+
return colon === -1 ? host : host.slice(0, colon);
|
|
1073
|
+
}
|
|
1074
|
+
var EMPTY_BUFFER = Buffer.alloc(0);
|
|
1075
|
+
function isPlainPath(target) {
|
|
1076
|
+
if (target.length === 0 || target.codePointAt(0) !== 47) return false;
|
|
1077
|
+
let prev = 47;
|
|
1078
|
+
for (let i = 1; i < target.length; i++) {
|
|
1079
|
+
const code = target.codePointAt(i) ?? 0;
|
|
1080
|
+
if (code <= 32 || code >= 127) return false;
|
|
1081
|
+
if (code === 34 || // "
|
|
1082
|
+
code === 35 || // #
|
|
1083
|
+
code === 60 || // <
|
|
1084
|
+
code === 62 || // >
|
|
1085
|
+
code === 63 || // ?
|
|
1086
|
+
code === 92 || // \
|
|
1087
|
+
code === 94 || // ^
|
|
1088
|
+
code === 96 || // `
|
|
1089
|
+
code === 123 || // {
|
|
1090
|
+
code === 124 || // |
|
|
1091
|
+
code === 125) {
|
|
1092
|
+
return false;
|
|
1093
|
+
}
|
|
1094
|
+
if (code === 46 && prev === 47) return false;
|
|
1095
|
+
prev = code;
|
|
1096
|
+
}
|
|
1097
|
+
return true;
|
|
1098
|
+
}
|
|
1099
|
+
var TRUTHY_STRINGS = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
|
|
1100
|
+
function coerceBoolean(val) {
|
|
1101
|
+
if (typeof val === "boolean") return val;
|
|
1102
|
+
if (typeof val === "number") return val === 1;
|
|
1103
|
+
if (typeof val === "string") return TRUTHY_STRINGS.has(val.trim().toLowerCase());
|
|
1104
|
+
return false;
|
|
1105
|
+
}
|
|
1106
|
+
function coerceNumber(val) {
|
|
1107
|
+
if (typeof val === "number") return Number.isFinite(val) ? val : void 0;
|
|
1108
|
+
if (typeof val === "boolean") return val ? 1 : 0;
|
|
1109
|
+
if (typeof val === "string") {
|
|
1110
|
+
const trimmed = val.trim();
|
|
1111
|
+
if (trimmed.length === 0) return void 0;
|
|
1112
|
+
const num = Number(trimmed);
|
|
1113
|
+
return Number.isFinite(num) ? num : void 0;
|
|
1114
|
+
}
|
|
1115
|
+
return void 0;
|
|
1116
|
+
}
|
|
1117
|
+
var Request = class _Request {
|
|
1118
|
+
_method;
|
|
1119
|
+
/** The raw request target as received (`/users?page=2`); URL work happens lazily off it. */
|
|
1120
|
+
_target;
|
|
1121
|
+
/** Memoized WHATWG parse of {@link Request._target}; built only when normalization is needed. */
|
|
1122
|
+
_url;
|
|
1123
|
+
/** Memoized pathname; a {@link isPlainPath plain} target resolves by slicing, sparing `new URL`. */
|
|
1124
|
+
_pathname;
|
|
1125
|
+
_host;
|
|
1126
|
+
/** The host as received (port included, if any) — backs {@link Request.httpHost}. */
|
|
1127
|
+
_httpHost;
|
|
1128
|
+
/** The matched route's name, attached by the kernel after a successful match (for `routeIs`). */
|
|
1129
|
+
_routeName;
|
|
1130
|
+
_headers;
|
|
1131
|
+
/** Lazily-decoded utf8 view of {@link Request._rawBuffer} (eager when constructed from a string). */
|
|
1132
|
+
_rawBody;
|
|
1133
|
+
_rawBuffer;
|
|
1134
|
+
/** Memoized parsed body; `undefined` until the first input access forces the parse. */
|
|
1135
|
+
_parsedBody;
|
|
1136
|
+
/** Memoized result of parsing a `multipart/form-data` body; `undefined` until first accessed. */
|
|
1137
|
+
_multipart;
|
|
1138
|
+
_routeParams;
|
|
1139
|
+
_attributes;
|
|
1140
|
+
_boundModels;
|
|
1141
|
+
_mergedInput;
|
|
1142
|
+
/**
|
|
1143
|
+
* Construct from already-resolved primitives. Prefer {@link Request.fromNode} for a live
|
|
1144
|
+
* {@link IncomingMessage}; this constructor is what synthetic tests use directly.
|
|
1145
|
+
*/
|
|
1146
|
+
constructor(init = {}) {
|
|
1147
|
+
this._method = init.method === void 0 ? "GET" : init.method.toUpperCase();
|
|
1148
|
+
this._target = init.url ?? "/";
|
|
1149
|
+
this._url = void 0;
|
|
1150
|
+
this._pathname = void 0;
|
|
1151
|
+
this._headers = normalizeHeaders(init.headers);
|
|
1152
|
+
const rawHost = init.host ?? this._headers.get("host");
|
|
1153
|
+
this._httpHost = rawHost === void 0 || rawHost.length === 0 ? void 0 : rawHost;
|
|
1154
|
+
this._host = stripPort(rawHost);
|
|
1155
|
+
this._routeName = void 0;
|
|
1156
|
+
this._rawBody = init.body;
|
|
1157
|
+
this._rawBuffer = init.bodyBuffer ?? (init.body === void 0 || init.body.length === 0 ? EMPTY_BUFFER : Buffer.from(init.body, "utf8"));
|
|
1158
|
+
this._parsedBody = void 0;
|
|
1159
|
+
this._multipart = void 0;
|
|
1160
|
+
this._routeParams = {};
|
|
1161
|
+
this._attributes = /* @__PURE__ */ new Map();
|
|
1162
|
+
this._boundModels = /* @__PURE__ */ new Map();
|
|
1163
|
+
this._mergedInput = {};
|
|
1164
|
+
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Build a {@link Request} from a live Node {@link IncomingMessage}, draining and parsing the body.
|
|
1167
|
+
* The Laravel `Request::capture()` equivalent for the `node:http` runtime. The body is buffered
|
|
1168
|
+
* up to {@link FromNodeOptions.maxBodyBytes} (default 1 MiB); anything larger rejects with a
|
|
1169
|
+
* {@link PayloadTooLargeHttpException} without buffering past the cap.
|
|
1170
|
+
*/
|
|
1171
|
+
static fromNode(req, options = {}) {
|
|
1172
|
+
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
1173
|
+
const headers = req.headers;
|
|
1174
|
+
const method = req.method ?? "GET";
|
|
1175
|
+
const url = req.url ?? "/";
|
|
1176
|
+
const declared = headers["content-length"];
|
|
1177
|
+
if (declared !== void 0 && Number(declared) > maxBodyBytes) {
|
|
1178
|
+
return Promise.reject(new PayloadTooLargeHttpException());
|
|
1179
|
+
}
|
|
1180
|
+
if ((declared === void 0 || declared === "0") && headers["transfer-encoding"] === void 0) {
|
|
1181
|
+
return Promise.resolve(new _Request({ method, url, headers }));
|
|
1182
|
+
}
|
|
1183
|
+
return new Promise((resolve, reject) => {
|
|
1184
|
+
let single;
|
|
1185
|
+
let chunks;
|
|
1186
|
+
let total = 0;
|
|
1187
|
+
let settled = false;
|
|
1188
|
+
const onData = (chunk) => {
|
|
1189
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1190
|
+
total += buf.length;
|
|
1191
|
+
if (total > maxBodyBytes) {
|
|
1192
|
+
settled = true;
|
|
1193
|
+
req.removeListener("data", onData);
|
|
1194
|
+
req.pause();
|
|
1195
|
+
reject(new PayloadTooLargeHttpException());
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
if (chunks === void 0) {
|
|
1199
|
+
if (single === void 0) single = buf;
|
|
1200
|
+
else {
|
|
1201
|
+
chunks = [single, buf];
|
|
1202
|
+
single = void 0;
|
|
1203
|
+
}
|
|
1204
|
+
} else {
|
|
1205
|
+
chunks.push(buf);
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
req.on("data", onData);
|
|
1209
|
+
req.once("end", () => {
|
|
1210
|
+
if (settled) return;
|
|
1211
|
+
settled = true;
|
|
1212
|
+
const bodyBuffer = chunks === void 0 ? single ?? EMPTY_BUFFER : Buffer.concat(chunks, total);
|
|
1213
|
+
resolve(new _Request({ method, url, headers, bodyBuffer }));
|
|
1214
|
+
});
|
|
1215
|
+
req.once("error", (error) => {
|
|
1216
|
+
if (settled) return;
|
|
1217
|
+
settled = true;
|
|
1218
|
+
reject(error);
|
|
1219
|
+
});
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
/** The memoized WHATWG parse of the request target, for the paths that need normalization. */
|
|
1223
|
+
urlObject() {
|
|
1224
|
+
this._url ??= new URL(this._target, DUMMY_HOST);
|
|
1225
|
+
return this._url;
|
|
1226
|
+
}
|
|
1227
|
+
/** The URL-normalized pathname (untrimmed), via the plain-target fast path when possible. */
|
|
1228
|
+
pathname() {
|
|
1229
|
+
let pathname = this._pathname;
|
|
1230
|
+
if (pathname === void 0) {
|
|
1231
|
+
pathname = isPlainPath(this._target) ? this._target : this.urlObject().pathname;
|
|
1232
|
+
this._pathname = pathname;
|
|
1233
|
+
}
|
|
1234
|
+
return pathname;
|
|
1235
|
+
}
|
|
1236
|
+
/** The URL-normalized search component (`?…` or the empty string). */
|
|
1237
|
+
searchString() {
|
|
1238
|
+
if (this._pathname === void 0) this.pathname();
|
|
1239
|
+
const url = this._url;
|
|
1240
|
+
return url === void 0 ? "" : url.search;
|
|
1241
|
+
}
|
|
1242
|
+
/** The raw body as utf8 text, decoded from the byte buffer on first use and memoized. */
|
|
1243
|
+
rawBody() {
|
|
1244
|
+
let raw = this._rawBody;
|
|
1245
|
+
if (raw === void 0) {
|
|
1246
|
+
raw = this._rawBuffer.length === 0 ? "" : this._rawBuffer.toString("utf8");
|
|
1247
|
+
this._rawBody = raw;
|
|
1248
|
+
}
|
|
1249
|
+
return raw;
|
|
1250
|
+
}
|
|
1251
|
+
/** Parse the body on first access and memoize; clones share the memo (the body is immutable). */
|
|
1252
|
+
parsedBody() {
|
|
1253
|
+
this._parsedBody ??= this.parseBody();
|
|
1254
|
+
return this._parsedBody;
|
|
1255
|
+
}
|
|
1256
|
+
/** Parse the raw body according to the `Content-Type`, falling back to an empty object. */
|
|
1257
|
+
parseBody() {
|
|
1258
|
+
const type = (this._headers.get("content-type") ?? "").toLowerCase();
|
|
1259
|
+
if (type.includes("application/json")) {
|
|
1260
|
+
const raw = this.rawBody();
|
|
1261
|
+
if (raw.length === 0) return {};
|
|
1262
|
+
try {
|
|
1263
|
+
const parsed = JSON.parse(raw);
|
|
1264
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1265
|
+
return parsed;
|
|
1266
|
+
}
|
|
1267
|
+
return {};
|
|
1268
|
+
} catch {
|
|
1269
|
+
return {};
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
if (type.includes("application/x-www-form-urlencoded")) {
|
|
1273
|
+
const raw = this.rawBody();
|
|
1274
|
+
if (raw.length === 0) return {};
|
|
1275
|
+
return parseUrlEncoded(raw);
|
|
1276
|
+
}
|
|
1277
|
+
return {};
|
|
1278
|
+
}
|
|
1279
|
+
/** Whether the `Content-Type` declares a `multipart/form-data` body. */
|
|
1280
|
+
isMultipart() {
|
|
1281
|
+
return (this._headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data");
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Parse the `multipart/form-data` body once and memoize it. Returns an empty result for any
|
|
1285
|
+
* non-multipart request (so json/urlencoded handling is never disturbed) and is best-effort on a
|
|
1286
|
+
* malformed body. The parse reads the binary-safe {@link Request._rawBuffer}, not the utf8 string.
|
|
1287
|
+
*/
|
|
1288
|
+
multipart() {
|
|
1289
|
+
if (this._multipart !== void 0) return this._multipart;
|
|
1290
|
+
let result = { fields: [], files: [] };
|
|
1291
|
+
if (this.isMultipart()) {
|
|
1292
|
+
const boundary = boundaryFromContentType(this._headers.get("content-type"));
|
|
1293
|
+
if (boundary !== void 0) result = parseMultipart(this._rawBuffer, boundary);
|
|
1294
|
+
}
|
|
1295
|
+
this._multipart = result;
|
|
1296
|
+
return result;
|
|
1297
|
+
}
|
|
1298
|
+
// --- Method / URL --------------------------------------------------------
|
|
1299
|
+
/** The HTTP verb (upper-case). The `$request->method()` equivalent. */
|
|
1300
|
+
method() {
|
|
1301
|
+
return this._method;
|
|
1302
|
+
}
|
|
1303
|
+
/** Whether the request uses the given verb (case-insensitive). The `$request->isMethod()` equivalent. */
|
|
1304
|
+
isMethod(method) {
|
|
1305
|
+
return this._method === method.toUpperCase();
|
|
1306
|
+
}
|
|
1307
|
+
/** The path with no query string, e.g. `/users`. The `$request->path()` equivalent. */
|
|
1308
|
+
path() {
|
|
1309
|
+
const pathname = this.pathname();
|
|
1310
|
+
if (pathname.length > 1 && pathname.endsWith("/")) return pathname.replace(/\/+$/, "");
|
|
1311
|
+
return pathname;
|
|
1312
|
+
}
|
|
1313
|
+
/** The full request target including any query string. The `$request->fullUrl()` equivalent. */
|
|
1314
|
+
url() {
|
|
1315
|
+
return `${this.pathname()}${this.searchString()}`;
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* The request host without any port (e.g. `acme.myapp.com`), from the constructor `host` or the
|
|
1319
|
+
* `Host` header, or `undefined` when neither is present. The `$request->host()` equivalent, used
|
|
1320
|
+
* by the {@link import('./router').Router}'s subdomain/domain routing.
|
|
1321
|
+
*/
|
|
1322
|
+
host() {
|
|
1323
|
+
return this._host;
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* The request host **including** any port (e.g. `acme.myapp.com:8080`), as received from the
|
|
1327
|
+
* constructor `host` or the `Host` header. The `$request->httpHost()` equivalent; `undefined`
|
|
1328
|
+
* when no host is known (a synthetic request without a `Host` header).
|
|
1329
|
+
*/
|
|
1330
|
+
httpHost() {
|
|
1331
|
+
return this._httpHost;
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* The scheme plus host (e.g. `https://acme.myapp.com:8080`) — the `$request->schemeAndHttpHost()`
|
|
1335
|
+
* equivalent. The scheme is read from the first `X-Forwarded-Proto` hop, defaulting to `http`
|
|
1336
|
+
* (Mason's adapter sits on plain `node:http`; a TLS-terminating proxy sets the header).
|
|
1337
|
+
* `undefined` when no host is known.
|
|
1338
|
+
*/
|
|
1339
|
+
schemeAndHttpHost() {
|
|
1340
|
+
if (this._httpHost === void 0) return void 0;
|
|
1341
|
+
return `${this.scheme()}://${this._httpHost}`;
|
|
1342
|
+
}
|
|
1343
|
+
/** The request scheme: the first `X-Forwarded-Proto` hop, defaulting to `http`. */
|
|
1344
|
+
scheme() {
|
|
1345
|
+
const forwarded = this._headers.get("x-forwarded-proto");
|
|
1346
|
+
if (forwarded !== void 0) {
|
|
1347
|
+
const first = forwarded.split(",")[0]?.trim().toLowerCase();
|
|
1348
|
+
if (first === "http" || first === "https") return first;
|
|
1349
|
+
}
|
|
1350
|
+
return "http";
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Whether the request arrived over HTTPS — the `$request->isSecure()` equivalent. Reads the first
|
|
1354
|
+
* `X-Forwarded-Proto` hop (Mason sits on plain `node:http` behind a TLS-terminating proxy), so it
|
|
1355
|
+
* is the trust-proxy signal a `secure` cookie or HSTS header should gate on.
|
|
1356
|
+
*/
|
|
1357
|
+
isSecure() {
|
|
1358
|
+
return this.scheme() === "https";
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* The full URL including the query string — `scheme://host/path?query` when the host is known,
|
|
1362
|
+
* otherwise just `/path?query` (matching {@link Request.url} for host-less synthetic requests).
|
|
1363
|
+
* The `$request->fullUrl()` equivalent.
|
|
1364
|
+
*/
|
|
1365
|
+
fullUrl() {
|
|
1366
|
+
const base = this.schemeAndHttpHost();
|
|
1367
|
+
return base === void 0 ? this.url() : `${base}${this.pathname()}${this.searchString()}`;
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* The {@link Request.fullUrl} with `query` merged into the current query string (existing keys
|
|
1371
|
+
* are overridden). The `$request->fullUrlWithQuery()` equivalent.
|
|
1372
|
+
*/
|
|
1373
|
+
fullUrlWithQuery(query) {
|
|
1374
|
+
const params = new URLSearchParams(this.urlObject().searchParams);
|
|
1375
|
+
for (const [key, value] of Object.entries(query)) params.set(key, String(value));
|
|
1376
|
+
return this.rebuildFullUrl(params);
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* The {@link Request.fullUrl} with the given query `keys` removed. The
|
|
1380
|
+
* `$request->fullUrlWithoutQuery()` equivalent.
|
|
1381
|
+
*/
|
|
1382
|
+
fullUrlWithoutQuery(keys) {
|
|
1383
|
+
const params = new URLSearchParams(this.urlObject().searchParams);
|
|
1384
|
+
for (const key of keys) params.delete(key);
|
|
1385
|
+
return this.rebuildFullUrl(params);
|
|
1386
|
+
}
|
|
1387
|
+
/** Reassemble the full URL from the current scheme/host/path plus an edited query bag. */
|
|
1388
|
+
rebuildFullUrl(params) {
|
|
1389
|
+
const search = params.toString();
|
|
1390
|
+
const base = this.schemeAndHttpHost() ?? "";
|
|
1391
|
+
return `${base}${this.pathname()}${search.length > 0 ? `?${search}` : ""}`;
|
|
1392
|
+
}
|
|
1393
|
+
// --- Path / route matching (the `is()` family, `*` wildcards) --------------
|
|
1394
|
+
/**
|
|
1395
|
+
* Whether the request path matches any of the wildcard `patterns` — `*` matches any run of
|
|
1396
|
+
* characters. Patterns are matched against the path **without** its leading slash (so
|
|
1397
|
+
* `req.is('admin/*')` matches `/admin/users`), mirroring `$request->is()`.
|
|
1398
|
+
*/
|
|
1399
|
+
is(...patterns) {
|
|
1400
|
+
const path3 = this.path().replace(/^\//, "");
|
|
1401
|
+
return patterns.some((pattern) => Str.is(pattern, path3));
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Whether the matched route's name matches any of the wildcard `patterns` (e.g.
|
|
1405
|
+
* `req.routeIs('users.*')`). The kernel attaches the name after a successful match via
|
|
1406
|
+
* {@link Request.withRouteName}; `false` for an unnamed or unmatched route. The
|
|
1407
|
+
* `$request->routeIs()` equivalent.
|
|
1408
|
+
*/
|
|
1409
|
+
routeIs(...patterns) {
|
|
1410
|
+
if (this._routeName === void 0) return false;
|
|
1411
|
+
const name = this._routeName;
|
|
1412
|
+
return patterns.some((pattern) => Str.is(pattern, name));
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* Whether {@link Request.fullUrl} matches any of the wildcard `patterns`. The
|
|
1416
|
+
* `$request->fullUrlIs()` equivalent.
|
|
1417
|
+
*/
|
|
1418
|
+
fullUrlIs(...patterns) {
|
|
1419
|
+
const url = this.fullUrl();
|
|
1420
|
+
return patterns.some((pattern) => Str.is(pattern, url));
|
|
1421
|
+
}
|
|
1422
|
+
query(key, def) {
|
|
1423
|
+
if (key === void 0) return this.queryAll();
|
|
1424
|
+
if (this.searchString().length === 0) return def;
|
|
1425
|
+
const val = this.urlObject().searchParams.get(key);
|
|
1426
|
+
return val ?? def;
|
|
1427
|
+
}
|
|
1428
|
+
/** Every query parameter as a plain object. The `$request->query()` (no-arg) equivalent. */
|
|
1429
|
+
queryAll() {
|
|
1430
|
+
const out = {};
|
|
1431
|
+
if (this.searchString().length === 0) return out;
|
|
1432
|
+
for (const [key, val] of this.urlObject().searchParams.entries()) out[key] = val;
|
|
1433
|
+
return out;
|
|
1434
|
+
}
|
|
1435
|
+
// --- Headers -------------------------------------------------------------
|
|
1436
|
+
/** Read a single header (case-insensitive), or `def` when absent. The `$request->header()` equivalent. */
|
|
1437
|
+
header(name, def) {
|
|
1438
|
+
return this._headers.get(name.toLowerCase()) ?? def;
|
|
1439
|
+
}
|
|
1440
|
+
/** Every header as a plain object (lower-cased names). The `$request->headers->all()` equivalent. */
|
|
1441
|
+
headers() {
|
|
1442
|
+
return Object.fromEntries(this._headers.entries());
|
|
1443
|
+
}
|
|
1444
|
+
// --- Input (query + body merged) -----------------------------------------
|
|
1445
|
+
/**
|
|
1446
|
+
* The merged input bag: query parameters overlaid with the parsed body (body wins), then with any
|
|
1447
|
+
* values supplied via {@link Request.merge}/{@link Request.mergeIfMissing} (merged values win).
|
|
1448
|
+
*/
|
|
1449
|
+
all() {
|
|
1450
|
+
const out = this.queryAll();
|
|
1451
|
+
if (this.isMultipart()) {
|
|
1452
|
+
for (const field of this.multipart().fields) out[field.name] = field.value;
|
|
1453
|
+
}
|
|
1454
|
+
return Object.assign(out, this.parsedBody(), this._mergedInput);
|
|
1455
|
+
}
|
|
1456
|
+
/** Read a merged input value by key, or `def` when absent. The `$request->input()` equivalent. */
|
|
1457
|
+
input(key, def) {
|
|
1458
|
+
const all = this.all();
|
|
1459
|
+
return key in all ? all[key] : def;
|
|
1460
|
+
}
|
|
1461
|
+
/** Only the named keys from the merged input. The `$request->only()` equivalent. */
|
|
1462
|
+
only(keys) {
|
|
1463
|
+
const all = this.all();
|
|
1464
|
+
const out = {};
|
|
1465
|
+
for (const key of keys) if (key in all) out[key] = all[key];
|
|
1466
|
+
return out;
|
|
1467
|
+
}
|
|
1468
|
+
/** Every merged input value except the named keys. The `$request->except()` equivalent. */
|
|
1469
|
+
except(keys) {
|
|
1470
|
+
const all = this.all();
|
|
1471
|
+
const drop = new Set(keys);
|
|
1472
|
+
const out = {};
|
|
1473
|
+
for (const [key, val] of Object.entries(all)) if (!drop.has(key)) out[key] = val;
|
|
1474
|
+
return out;
|
|
1475
|
+
}
|
|
1476
|
+
/** Whether the merged input contains the key. The `$request->has()` equivalent. */
|
|
1477
|
+
has(key) {
|
|
1478
|
+
return key in this.all();
|
|
1479
|
+
}
|
|
1480
|
+
// --- Typed input (the `InteractsWithInput` coercion family) ---------------
|
|
1481
|
+
/** Every merged-input key. The `$request->keys()` equivalent. */
|
|
1482
|
+
keys() {
|
|
1483
|
+
return Object.keys(this.all());
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* Read an input value coerced to a boolean — `true`/`1`/`'1'`/`'true'`/`'on'`/`'yes'` (strings
|
|
1487
|
+
* case-insensitive) are `true`, anything else `false`. When the key is absent, `def` (default
|
|
1488
|
+
* `false`) is returned. The `$request->boolean()` equivalent.
|
|
1489
|
+
*/
|
|
1490
|
+
boolean(key, def) {
|
|
1491
|
+
const all = this.all();
|
|
1492
|
+
if (!(key in all)) return def ?? false;
|
|
1493
|
+
return coerceBoolean(all[key]);
|
|
1494
|
+
}
|
|
1495
|
+
/**
|
|
1496
|
+
* Read an input value coerced to an integer (a finite number, truncated toward zero). When the key
|
|
1497
|
+
* is absent or its value has no numeric reading, `def` (default `0`) is returned. The
|
|
1498
|
+
* `$request->integer()` equivalent.
|
|
1499
|
+
*/
|
|
1500
|
+
integer(key, def) {
|
|
1501
|
+
const all = this.all();
|
|
1502
|
+
if (!(key in all)) return def ?? 0;
|
|
1503
|
+
const num = coerceNumber(all[key]);
|
|
1504
|
+
return num === void 0 ? def ?? 0 : Math.trunc(num);
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Read an input value coerced to a floating-point number. When the key is absent or its value has
|
|
1508
|
+
* no numeric reading, `def` (default `0`) is returned. The `$request->float()` equivalent.
|
|
1509
|
+
*/
|
|
1510
|
+
float(key, def) {
|
|
1511
|
+
const all = this.all();
|
|
1512
|
+
if (!(key in all)) return def ?? 0;
|
|
1513
|
+
const num = coerceNumber(all[key]);
|
|
1514
|
+
return num ?? def ?? 0;
|
|
1515
|
+
}
|
|
1516
|
+
/**
|
|
1517
|
+
* Read an input value coerced to a primitive string. When the key is absent, `def` (default `''`)
|
|
1518
|
+
* is returned. The Laravel `$request->string()` equivalent — note this returns a primitive
|
|
1519
|
+
* `string` rather than a `Stringable`; wrap it with `@plinthjs/support`'s `Str.of()` for fluent
|
|
1520
|
+
* helpers if needed.
|
|
1521
|
+
*/
|
|
1522
|
+
string(key, def) {
|
|
1523
|
+
const all = this.all();
|
|
1524
|
+
if (!(key in all)) return def ?? "";
|
|
1525
|
+
return String(all[key]);
|
|
1526
|
+
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Read an input value if (and only if) it is one of `values`, else `undefined`. Generic over the
|
|
1529
|
+
* union of allowed values. The Laravel `$request->enum()` equivalent (returning the value, not a
|
|
1530
|
+
* native enum case). Comparison is by strict equality against the supplied members.
|
|
1531
|
+
*/
|
|
1532
|
+
enum(key, values) {
|
|
1533
|
+
const value = this.input(key);
|
|
1534
|
+
return values.includes(value) ? value : void 0;
|
|
1535
|
+
}
|
|
1536
|
+
/**
|
|
1537
|
+
* Wrap the input in a `@plinthjs/support` {@link Collection}: the value at `key` when given (an array
|
|
1538
|
+
* value is collected as-is; any other single value is wrapped as a one-element collection), or all
|
|
1539
|
+
* input values when omitted. The `$request->collect()` equivalent.
|
|
1540
|
+
*/
|
|
1541
|
+
collect(key) {
|
|
1542
|
+
if (key === void 0) return collect(Object.values(this.all()));
|
|
1543
|
+
const value = this.input(key);
|
|
1544
|
+
if (Array.isArray(value)) return collect(value);
|
|
1545
|
+
return value === void 0 ? collect([]) : collect([value]);
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Whether the key is present AND its value is not "blank" (empty string/array/object, or nullish).
|
|
1549
|
+
* The `$request->filled()` equivalent.
|
|
1550
|
+
*/
|
|
1551
|
+
filled(key) {
|
|
1552
|
+
const all = this.all();
|
|
1553
|
+
return key in all && filled(all[key]);
|
|
1554
|
+
}
|
|
1555
|
+
/** Whether the key is absent OR its value is blank. The inverse of {@link Request.filled}. */
|
|
1556
|
+
isNotFilled(key) {
|
|
1557
|
+
return !this.filled(key);
|
|
1558
|
+
}
|
|
1559
|
+
/** Whether the key is absent from the merged input. The `$request->missing()` equivalent. */
|
|
1560
|
+
missing(key) {
|
|
1561
|
+
return !this.has(key);
|
|
1562
|
+
}
|
|
1563
|
+
/** Whether any of the given keys is present in the merged input. The `$request->hasAny()` equivalent. */
|
|
1564
|
+
hasAny(keys) {
|
|
1565
|
+
const all = this.all();
|
|
1566
|
+
return keys.some((key) => key in all);
|
|
1567
|
+
}
|
|
1568
|
+
/**
|
|
1569
|
+
* Whether any of the given keys is present AND not blank. The `$request->anyFilled()` equivalent.
|
|
1570
|
+
*/
|
|
1571
|
+
anyFilled(keys) {
|
|
1572
|
+
return keys.some((key) => this.filled(key));
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Run `cb` when `key` is **absent** from the merged input, returning its result; otherwise return
|
|
1576
|
+
* `def`. The `$request->whenMissing()` equivalent.
|
|
1577
|
+
*/
|
|
1578
|
+
whenMissing(key, cb, def) {
|
|
1579
|
+
if (this.missing(key)) return cb();
|
|
1580
|
+
return def;
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Run `cb` with the input value when `key` is present, returning its result; otherwise return
|
|
1584
|
+
* `def`. The `$request->whenHas()` equivalent.
|
|
1585
|
+
*/
|
|
1586
|
+
whenHas(key, cb, def) {
|
|
1587
|
+
const all = this.all();
|
|
1588
|
+
if (key in all) return cb(all[key]);
|
|
1589
|
+
return def;
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* Run `cb` with the input value when `key` is present AND not blank, returning its result;
|
|
1593
|
+
* otherwise return `def`. The `$request->whenFilled()` equivalent.
|
|
1594
|
+
*/
|
|
1595
|
+
whenFilled(key, cb, def) {
|
|
1596
|
+
const all = this.all();
|
|
1597
|
+
if (key in all && filled(all[key])) return cb(all[key]);
|
|
1598
|
+
return def;
|
|
1599
|
+
}
|
|
1600
|
+
/**
|
|
1601
|
+
* Return a copy of this request with `input` merged into its input bag, overriding any existing
|
|
1602
|
+
* keys. Immutable: the original is unchanged. The `$request->merge()` equivalent.
|
|
1603
|
+
*/
|
|
1604
|
+
merge(input) {
|
|
1605
|
+
const clone = this.cloneRequest();
|
|
1606
|
+
Object.assign(clone._mergedInput, input);
|
|
1607
|
+
return clone;
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Return a copy of this request with only the keys of `input` that are not already present in the
|
|
1611
|
+
* merged input added. Immutable: the original is unchanged. The `$request->mergeIfMissing()`
|
|
1612
|
+
* equivalent.
|
|
1613
|
+
*/
|
|
1614
|
+
mergeIfMissing(input) {
|
|
1615
|
+
const all = this.all();
|
|
1616
|
+
const additions = {};
|
|
1617
|
+
for (const [key, val] of Object.entries(input)) {
|
|
1618
|
+
if (!(key in all)) additions[key] = val;
|
|
1619
|
+
}
|
|
1620
|
+
const clone = this.cloneRequest();
|
|
1621
|
+
Object.assign(clone._mergedInput, additions);
|
|
1622
|
+
return clone;
|
|
1623
|
+
}
|
|
1624
|
+
// --- Body / content negotiation ------------------------------------------
|
|
1625
|
+
/** The raw, unparsed request body. */
|
|
1626
|
+
body() {
|
|
1627
|
+
return this.rawBody();
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Parse and return the JSON body, or `def` when the body is absent/invalid. Unlike {@link all},
|
|
1631
|
+
* this returns the decoded value verbatim (arrays and scalars included). The `$request->json()`
|
|
1632
|
+
* equivalent.
|
|
1633
|
+
*/
|
|
1634
|
+
json(def) {
|
|
1635
|
+
const raw = this.rawBody();
|
|
1636
|
+
if (raw.length === 0) return def;
|
|
1637
|
+
try {
|
|
1638
|
+
return JSON.parse(raw);
|
|
1639
|
+
} catch {
|
|
1640
|
+
return def;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
/** Whether the `Content-Type` declares a JSON body. The `$request->isJson()` equivalent. */
|
|
1644
|
+
isJson() {
|
|
1645
|
+
return (this._headers.get("content-type") ?? "").toLowerCase().includes("/json");
|
|
1646
|
+
}
|
|
1647
|
+
/** Whether the client prefers a JSON response (Accept / XHR). The `$request->wantsJson()` equivalent. */
|
|
1648
|
+
wantsJson() {
|
|
1649
|
+
const accept = (this._headers.get("accept") ?? "").toLowerCase();
|
|
1650
|
+
if (accept.includes("/json") || accept.includes("+json")) return true;
|
|
1651
|
+
return (this._headers.get("x-requested-with") ?? "").toLowerCase() === "xmlhttprequest";
|
|
1652
|
+
}
|
|
1653
|
+
// --- Auth / cookies ------------------------------------------------------
|
|
1654
|
+
/** The bearer token from `Authorization: Bearer …`, or `undefined`. The `$request->bearerToken()` equivalent. */
|
|
1655
|
+
bearerToken() {
|
|
1656
|
+
const auth = this._headers.get("authorization");
|
|
1657
|
+
if (!auth) return void 0;
|
|
1658
|
+
const match = /^Bearer\s+(.+)$/i.exec(auth);
|
|
1659
|
+
return match ? match[1] : void 0;
|
|
1660
|
+
}
|
|
1661
|
+
/** Read a cookie by name from the `Cookie` header, or `undefined`. The `$request->cookie()` equivalent. */
|
|
1662
|
+
cookie(name) {
|
|
1663
|
+
return this.cookies()[name];
|
|
1664
|
+
}
|
|
1665
|
+
/** Every cookie parsed from the `Cookie` header. */
|
|
1666
|
+
cookies() {
|
|
1667
|
+
const raw = this._headers.get("cookie");
|
|
1668
|
+
const out = {};
|
|
1669
|
+
if (!raw) return out;
|
|
1670
|
+
for (const pair of raw.split(";")) {
|
|
1671
|
+
const eq = pair.indexOf("=");
|
|
1672
|
+
if (eq === -1) continue;
|
|
1673
|
+
const key = pair.slice(0, eq).trim();
|
|
1674
|
+
if (key.length === 0) continue;
|
|
1675
|
+
const val = pair.slice(eq + 1).trim();
|
|
1676
|
+
out[key] = decodeURIComponent(val);
|
|
1677
|
+
}
|
|
1678
|
+
return out;
|
|
1679
|
+
}
|
|
1680
|
+
/** The client IP, read from `X-Forwarded-For` (first hop) then `X-Real-IP`. The `$request->ip()` equivalent. */
|
|
1681
|
+
ip() {
|
|
1682
|
+
const forwarded = this._headers.get("x-forwarded-for");
|
|
1683
|
+
if (forwarded) {
|
|
1684
|
+
const first = forwarded.split(",")[0];
|
|
1685
|
+
if (first) return first.trim();
|
|
1686
|
+
}
|
|
1687
|
+
return this._headers.get("x-real-ip") ?? void 0;
|
|
1688
|
+
}
|
|
1689
|
+
// --- Files (the `multipart/form-data` upload accessors) -------------------
|
|
1690
|
+
/**
|
|
1691
|
+
* The uploaded file(s) for `key`: a single {@link UploadedFile} when one part used the name, an
|
|
1692
|
+
* array when several did, or `undefined` when none did. The `$request->file('avatar')` equivalent.
|
|
1693
|
+
*/
|
|
1694
|
+
file(key) {
|
|
1695
|
+
const matches = this.files(key);
|
|
1696
|
+
if (matches.length === 0) return void 0;
|
|
1697
|
+
if (matches.length === 1) return matches[0];
|
|
1698
|
+
return matches;
|
|
1699
|
+
}
|
|
1700
|
+
/** Every uploaded file submitted under `key`, as an array (empty when none). */
|
|
1701
|
+
files(key) {
|
|
1702
|
+
const out = [];
|
|
1703
|
+
for (const part of this.multipart().files) {
|
|
1704
|
+
if (part.name === key) {
|
|
1705
|
+
out.push(
|
|
1706
|
+
new UploadedFile({
|
|
1707
|
+
clientOriginalName: part.filename,
|
|
1708
|
+
mimeType: part.contentType,
|
|
1709
|
+
content: part.content
|
|
1710
|
+
})
|
|
1711
|
+
);
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
return out;
|
|
1715
|
+
}
|
|
1716
|
+
/** Whether a file was uploaded under `key`. The `$request->hasFile('avatar')` equivalent. */
|
|
1717
|
+
hasFile(key) {
|
|
1718
|
+
return this.multipart().files.some((part) => part.name === key);
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* Every uploaded file keyed by its form field name. A field with multiple files yields an array; a
|
|
1722
|
+
* single-file field yields one {@link UploadedFile}. The `$request->allFiles()` equivalent.
|
|
1723
|
+
*/
|
|
1724
|
+
allFiles() {
|
|
1725
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1726
|
+
for (const part of this.multipart().files) {
|
|
1727
|
+
const file = new UploadedFile({
|
|
1728
|
+
clientOriginalName: part.filename,
|
|
1729
|
+
mimeType: part.contentType,
|
|
1730
|
+
content: part.content
|
|
1731
|
+
});
|
|
1732
|
+
const existing = grouped.get(part.name);
|
|
1733
|
+
if (existing === void 0) grouped.set(part.name, [file]);
|
|
1734
|
+
else existing.push(file);
|
|
1735
|
+
}
|
|
1736
|
+
const out = {};
|
|
1737
|
+
for (const [name, list] of grouped) out[name] = list.length === 1 ? list[0] : list;
|
|
1738
|
+
return out;
|
|
1739
|
+
}
|
|
1740
|
+
// --- Route parameters ----------------------------------------------------
|
|
1741
|
+
/**
|
|
1742
|
+
* A structural copy carrying route parameters and attributes forward (kept immutable). Every
|
|
1743
|
+
* parsed artifact — headers, URL memos, body buffer, parsed/multipart memos — is immutable once
|
|
1744
|
+
* built, so clones share it by reference; only the per-clone bags (route params, attributes,
|
|
1745
|
+
* bound models, merged input) are copied.
|
|
1746
|
+
*/
|
|
1747
|
+
cloneRequest() {
|
|
1748
|
+
const clone = new _Request();
|
|
1749
|
+
clone._method = this._method;
|
|
1750
|
+
clone._target = this._target;
|
|
1751
|
+
clone._url = this._url;
|
|
1752
|
+
clone._pathname = this._pathname;
|
|
1753
|
+
clone._host = this._host;
|
|
1754
|
+
clone._httpHost = this._httpHost;
|
|
1755
|
+
clone._routeName = this._routeName;
|
|
1756
|
+
clone._headers = this._headers;
|
|
1757
|
+
clone._rawBody = this._rawBody;
|
|
1758
|
+
clone._rawBuffer = this._rawBuffer;
|
|
1759
|
+
clone._parsedBody = this._parsedBody;
|
|
1760
|
+
clone._multipart = this._multipart;
|
|
1761
|
+
Object.assign(clone._routeParams, this._routeParams);
|
|
1762
|
+
Object.assign(clone._mergedInput, this._mergedInput);
|
|
1763
|
+
for (const [key, value] of this._attributes) clone._attributes.set(key, value);
|
|
1764
|
+
for (const [key, value] of this._boundModels) clone._boundModels.set(key, value);
|
|
1765
|
+
return clone;
|
|
1766
|
+
}
|
|
1767
|
+
/**
|
|
1768
|
+
* Return a copy of this request with the matched route's name attached (read by
|
|
1769
|
+
* {@link Request.routeIs}). Immutable: the original is unchanged. The kernel calls this after a
|
|
1770
|
+
* successful match on a named route.
|
|
1771
|
+
*/
|
|
1772
|
+
withRouteName(name) {
|
|
1773
|
+
const clone = this.cloneRequest();
|
|
1774
|
+
clone._routeName = name;
|
|
1775
|
+
return clone;
|
|
1776
|
+
}
|
|
1777
|
+
/**
|
|
1778
|
+
* Return a copy of this request with route parameters attached. Immutable: the original is
|
|
1779
|
+
* unchanged. The router calls this after a successful match.
|
|
1780
|
+
*/
|
|
1781
|
+
withParams(params) {
|
|
1782
|
+
const clone = this.cloneRequest();
|
|
1783
|
+
Object.assign(clone._routeParams, params);
|
|
1784
|
+
return clone;
|
|
1785
|
+
}
|
|
1786
|
+
/**
|
|
1787
|
+
* Return a copy of this request with an arbitrary attribute attached — the `$request->attributes`
|
|
1788
|
+
* bag equivalent. Middleware use this to hand request-scoped values (the session, the
|
|
1789
|
+
* authenticated user, …) to downstream handlers without mutating the original.
|
|
1790
|
+
*/
|
|
1791
|
+
withAttribute(key, value) {
|
|
1792
|
+
const clone = this.cloneRequest();
|
|
1793
|
+
clone._attributes.set(key, value);
|
|
1794
|
+
return clone;
|
|
1795
|
+
}
|
|
1796
|
+
/** Read a middleware-attached attribute, or `undefined` when absent. */
|
|
1797
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is a caller-supplied cast for the stored value; removing it forces a cast at every call site
|
|
1798
|
+
attribute(key) {
|
|
1799
|
+
return this._attributes.get(key);
|
|
1800
|
+
}
|
|
1801
|
+
/**
|
|
1802
|
+
* Return a copy of this request with `name` set to `value` (case-insensitive) — e.g. a `forceJson`
|
|
1803
|
+
* middleware setting `Accept: application/json`. The header map is copied (clones normally share it
|
|
1804
|
+
* by reference), so the original request is untouched.
|
|
1805
|
+
*/
|
|
1806
|
+
withHeader(name, value) {
|
|
1807
|
+
const clone = this.cloneRequest();
|
|
1808
|
+
clone._headers = new Map(this._headers);
|
|
1809
|
+
clone._headers.set(name.toLowerCase(), value);
|
|
1810
|
+
return clone;
|
|
1811
|
+
}
|
|
1812
|
+
/**
|
|
1813
|
+
* Return a copy with resolved route-model bindings attached. The {@link HttpKernel} calls this
|
|
1814
|
+
* after resolving the {@link import('./router').Router}'s bindings for a matched route; handlers
|
|
1815
|
+
* read the resolved model with {@link route}.
|
|
1816
|
+
*/
|
|
1817
|
+
withBoundModels(models) {
|
|
1818
|
+
const clone = this.cloneRequest();
|
|
1819
|
+
for (const [key, value] of Object.entries(models)) clone._boundModels.set(key, value);
|
|
1820
|
+
return clone;
|
|
1821
|
+
}
|
|
1822
|
+
/**
|
|
1823
|
+
* The route value for `key`: the resolved bound model when route-model binding applied, otherwise
|
|
1824
|
+
* the raw route parameter (the Laravel `$request->route('user')`). `undefined` when neither exists.
|
|
1825
|
+
*/
|
|
1826
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- caller-supplied cast for the resolved bound model
|
|
1827
|
+
route(key) {
|
|
1828
|
+
if (this._boundModels.has(key)) return this._boundModels.get(key);
|
|
1829
|
+
return key in this._routeParams ? this._routeParams[key] : void 0;
|
|
1830
|
+
}
|
|
1831
|
+
/** Read a single route parameter, or `def` when absent. The `$request->route('id')` equivalent. */
|
|
1832
|
+
param(name, def) {
|
|
1833
|
+
return name in this._routeParams ? this._routeParams[name] : def;
|
|
1834
|
+
}
|
|
1835
|
+
/** Every route parameter as a plain object. */
|
|
1836
|
+
params() {
|
|
1837
|
+
return { ...this._routeParams };
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
var SIGNATURE_PARAM = "signature";
|
|
1841
|
+
var EXPIRES_PARAM = "expires";
|
|
1842
|
+
var ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
|
|
1843
|
+
function escapeRegex(input) {
|
|
1844
|
+
return input.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
|
|
1845
|
+
}
|
|
1846
|
+
function normalizePath(path3) {
|
|
1847
|
+
if (path3 === "/" || path3.startsWith("/") && !path3.endsWith("/") && !path3.includes("//")) {
|
|
1848
|
+
return path3;
|
|
1849
|
+
}
|
|
1850
|
+
let result = path3.startsWith("/") ? path3 : `/${path3}`;
|
|
1851
|
+
result = result.replaceAll(/\/{2,}/g, "/");
|
|
1852
|
+
if (result.length > 1 && result.endsWith("/")) result = result.slice(0, -1);
|
|
1853
|
+
return result;
|
|
1854
|
+
}
|
|
1855
|
+
function compileDomain(domain) {
|
|
1856
|
+
const params = [];
|
|
1857
|
+
let pattern = "";
|
|
1858
|
+
let remaining = domain;
|
|
1859
|
+
while (remaining.length > 0) {
|
|
1860
|
+
const required = /^\{(\w+)\}/.exec(remaining);
|
|
1861
|
+
if (required) {
|
|
1862
|
+
params.push(required[1]);
|
|
1863
|
+
pattern += "([^.]+)";
|
|
1864
|
+
remaining = remaining.slice(required[0].length);
|
|
1865
|
+
continue;
|
|
1866
|
+
}
|
|
1867
|
+
const next = remaining.indexOf("{");
|
|
1868
|
+
const literal = next === -1 ? remaining : remaining.slice(0, next);
|
|
1869
|
+
pattern += escapeRegex(literal);
|
|
1870
|
+
remaining = next === -1 ? "" : remaining.slice(literal.length);
|
|
1871
|
+
}
|
|
1872
|
+
return { regex: new RegExp(`^${pattern}$`, "i"), params };
|
|
1873
|
+
}
|
|
1874
|
+
function parseSegments(path3) {
|
|
1875
|
+
const result = [];
|
|
1876
|
+
for (const segment of path3.split("/")) {
|
|
1877
|
+
if (segment.length === 0) continue;
|
|
1878
|
+
const optional = /^\{(\w+)\?\}$/.exec(segment);
|
|
1879
|
+
if (optional) {
|
|
1880
|
+
result.push({ kind: "optional", name: optional[1] });
|
|
1881
|
+
continue;
|
|
1882
|
+
}
|
|
1883
|
+
const required = /^\{(\w+)\}$/.exec(segment);
|
|
1884
|
+
if (required) {
|
|
1885
|
+
result.push({ kind: "required", name: required[1] });
|
|
1886
|
+
continue;
|
|
1887
|
+
}
|
|
1888
|
+
result.push({ kind: "literal", value: segment });
|
|
1889
|
+
}
|
|
1890
|
+
return result;
|
|
1891
|
+
}
|
|
1892
|
+
function compilePath(path3) {
|
|
1893
|
+
const params = [];
|
|
1894
|
+
let pattern = "";
|
|
1895
|
+
for (const segment of parseSegments(path3)) {
|
|
1896
|
+
if (segment.kind === "optional") {
|
|
1897
|
+
params.push(segment.name);
|
|
1898
|
+
pattern += "(?:/([^/]+))?";
|
|
1899
|
+
} else if (segment.kind === "required") {
|
|
1900
|
+
params.push(segment.name);
|
|
1901
|
+
pattern += "/([^/]+)";
|
|
1902
|
+
} else {
|
|
1903
|
+
pattern += `/${escapeRegex(segment.value)}`;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
return { regex: new RegExp(`^${pattern === "" ? "/" : pattern}$`), params };
|
|
1907
|
+
}
|
|
1908
|
+
function countSegments(path3) {
|
|
1909
|
+
if (path3.length <= 1) return 0;
|
|
1910
|
+
let count = 1;
|
|
1911
|
+
for (let index = 1; index < path3.length; index += 1) {
|
|
1912
|
+
if (path3.codePointAt(index) === 47) count += 1;
|
|
1913
|
+
}
|
|
1914
|
+
return count;
|
|
1915
|
+
}
|
|
1916
|
+
function firstSegment(path3) {
|
|
1917
|
+
if (path3.length <= 1) return "";
|
|
1918
|
+
const end = path3.indexOf("/", 1);
|
|
1919
|
+
return end === -1 ? path3.slice(1) : path3.slice(1, end);
|
|
1920
|
+
}
|
|
1921
|
+
function canonicalize(pathname, params) {
|
|
1922
|
+
const entries = [...params.entries()].filter(([key]) => key !== SIGNATURE_PARAM);
|
|
1923
|
+
entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
1924
|
+
const search = new URLSearchParams(entries).toString();
|
|
1925
|
+
return search.length > 0 ? `${pathname}?${search}` : pathname;
|
|
1926
|
+
}
|
|
1927
|
+
function sign(key, payload) {
|
|
1928
|
+
return createHmac("sha256", key).update(payload).digest("hex");
|
|
1929
|
+
}
|
|
1930
|
+
function hashEquals(a, b) {
|
|
1931
|
+
const left = Buffer.from(a, "hex");
|
|
1932
|
+
const right = Buffer.from(b, "hex");
|
|
1933
|
+
if (left.length === 0 || left.length !== right.length) return false;
|
|
1934
|
+
return timingSafeEqual(left, right);
|
|
1935
|
+
}
|
|
1936
|
+
function toUnixSeconds(expiresAt) {
|
|
1937
|
+
return expiresAt instanceof Date ? Math.floor(expiresAt.getTime() / 1e3) : Math.floor(expiresAt);
|
|
1938
|
+
}
|
|
1939
|
+
function middlewareName(entry) {
|
|
1940
|
+
if (typeof entry === "string") return entry;
|
|
1941
|
+
if (typeof entry === "function") return entry.name;
|
|
1942
|
+
return entry.constructor.name;
|
|
1943
|
+
}
|
|
1944
|
+
function isControllerAction(handler) {
|
|
1945
|
+
return Array.isArray(handler) && handler.length === 2 && typeof handler[1] === "string";
|
|
1946
|
+
}
|
|
1947
|
+
function isInvokableTuple(handler) {
|
|
1948
|
+
return Array.isArray(handler) && handler.length === 1;
|
|
1949
|
+
}
|
|
1950
|
+
function toSerializableAction(handler) {
|
|
1951
|
+
if (isControllerAction(handler)) return handler;
|
|
1952
|
+
if (isInvokableTuple(handler)) return [handler[0], "__invoke"];
|
|
1953
|
+
if (typeof handler === "function" && isClass(handler)) return [handler, "__invoke"];
|
|
1954
|
+
return void 0;
|
|
1955
|
+
}
|
|
1956
|
+
function isClass(fn) {
|
|
1957
|
+
return Function.prototype.toString.call(fn).startsWith("class");
|
|
1958
|
+
}
|
|
1959
|
+
var WHERE_PATTERNS = {
|
|
1960
|
+
number: "[0-9]+",
|
|
1961
|
+
alpha: "[a-zA-Z]+",
|
|
1962
|
+
alphanumeric: "[a-zA-Z0-9]+",
|
|
1963
|
+
uuid: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",
|
|
1964
|
+
ulid: "[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}"
|
|
1965
|
+
};
|
|
1966
|
+
function compileConstraint(pattern) {
|
|
1967
|
+
const source = typeof pattern === "string" ? pattern : pattern.source;
|
|
1968
|
+
return new RegExp(`^(?:${source})$`);
|
|
1969
|
+
}
|
|
1970
|
+
var Route = class {
|
|
1971
|
+
methods;
|
|
1972
|
+
path;
|
|
1973
|
+
handler;
|
|
1974
|
+
compiled;
|
|
1975
|
+
routeName;
|
|
1976
|
+
routeMiddleware;
|
|
1977
|
+
domainPattern;
|
|
1978
|
+
compiledDomain;
|
|
1979
|
+
/** Per-parameter constraints; a parameter only matches when its value satisfies the regex. */
|
|
1980
|
+
constraints = /* @__PURE__ */ new Map();
|
|
1981
|
+
constructor(methods, path3, handler, middleware = [], domain) {
|
|
1982
|
+
this.methods = methods;
|
|
1983
|
+
this.path = path3;
|
|
1984
|
+
this.handler = handler;
|
|
1985
|
+
this.compiled = compilePath(path3);
|
|
1986
|
+
this.routeMiddleware = [...middleware];
|
|
1987
|
+
if (domain !== void 0) this.setDomain(domain);
|
|
1988
|
+
}
|
|
1989
|
+
/** Name this route so it can be resolved by {@link Router.url}. The `->name()` equivalent. */
|
|
1990
|
+
name(name) {
|
|
1991
|
+
this.routeName = name;
|
|
1992
|
+
return this;
|
|
1993
|
+
}
|
|
1994
|
+
/** This route's name, or `undefined` if unnamed. */
|
|
1995
|
+
getName() {
|
|
1996
|
+
return this.routeName;
|
|
1997
|
+
}
|
|
1998
|
+
/**
|
|
1999
|
+
* Constrain this route to a host pattern (e.g. `{account}.myapp.com`). The `->domain()`
|
|
2000
|
+
* equivalent: the route only matches when the request host matches, and any `{param}` labels in
|
|
2001
|
+
* the domain are extracted into the route's parameters (ahead of path params). Chains like the
|
|
2002
|
+
* other builders.
|
|
2003
|
+
*/
|
|
2004
|
+
domain(domain) {
|
|
2005
|
+
this.setDomain(domain);
|
|
2006
|
+
return this;
|
|
2007
|
+
}
|
|
2008
|
+
/** Compile and store the domain pattern; shared by the constructor and {@link Route.domain}. */
|
|
2009
|
+
setDomain(domain) {
|
|
2010
|
+
this.domainPattern = domain;
|
|
2011
|
+
this.compiledDomain = compileDomain(domain);
|
|
2012
|
+
}
|
|
2013
|
+
/** This route's domain pattern, or `undefined` when it matches any host. */
|
|
2014
|
+
getDomain() {
|
|
2015
|
+
return this.domainPattern;
|
|
2016
|
+
}
|
|
2017
|
+
/**
|
|
2018
|
+
* Match a request `host` against this route's domain. Returns the extracted domain params (an
|
|
2019
|
+
* empty object when the route has no domain — a domain-less route matches any host, mirroring
|
|
2020
|
+
* Laravel), or `undefined` when the route has a domain that the host does not satisfy (including
|
|
2021
|
+
* when the route requires a domain but no host was supplied).
|
|
2022
|
+
*/
|
|
2023
|
+
matchDomain(host) {
|
|
2024
|
+
if (this.compiledDomain === void 0) return {};
|
|
2025
|
+
if (host === void 0) return void 0;
|
|
2026
|
+
const result = this.compiledDomain.regex.exec(host);
|
|
2027
|
+
if (!result) return void 0;
|
|
2028
|
+
const params = {};
|
|
2029
|
+
for (const [index, name] of this.compiledDomain.params.entries()) {
|
|
2030
|
+
const value = result[index + 1];
|
|
2031
|
+
if (value !== void 0) params[name] = decodeURIComponent(value);
|
|
2032
|
+
}
|
|
2033
|
+
return params;
|
|
2034
|
+
}
|
|
2035
|
+
where(paramOrPatterns, pattern) {
|
|
2036
|
+
if (typeof paramOrPatterns === "string") {
|
|
2037
|
+
if (pattern === void 0) {
|
|
2038
|
+
throw new Error(`Route.where('${paramOrPatterns}') requires a pattern.`);
|
|
2039
|
+
}
|
|
2040
|
+
this.constraints.set(paramOrPatterns, compileConstraint(pattern));
|
|
2041
|
+
return this;
|
|
2042
|
+
}
|
|
2043
|
+
for (const [param, value] of Object.entries(paramOrPatterns)) {
|
|
2044
|
+
this.constraints.set(param, compileConstraint(value));
|
|
2045
|
+
}
|
|
2046
|
+
return this;
|
|
2047
|
+
}
|
|
2048
|
+
/** Constrain `param` to digits only. The Laravel `->whereNumber()` equivalent. Chains. */
|
|
2049
|
+
whereNumber(param) {
|
|
2050
|
+
return this.where(param, WHERE_PATTERNS.number);
|
|
2051
|
+
}
|
|
2052
|
+
/** Constrain `param` to ASCII letters only. The Laravel `->whereAlpha()` equivalent. Chains. */
|
|
2053
|
+
whereAlpha(param) {
|
|
2054
|
+
return this.where(param, WHERE_PATTERNS.alpha);
|
|
2055
|
+
}
|
|
2056
|
+
/** Constrain `param` to letters and digits. The Laravel `->whereAlphaNumeric()` equivalent. Chains. */
|
|
2057
|
+
whereAlphaNumeric(param) {
|
|
2058
|
+
return this.where(param, WHERE_PATTERNS.alphanumeric);
|
|
2059
|
+
}
|
|
2060
|
+
/** Constrain `param` to a UUID shape. The Laravel `->whereUuid()` equivalent. Chains. */
|
|
2061
|
+
whereUuid(param) {
|
|
2062
|
+
return this.where(param, WHERE_PATTERNS.uuid);
|
|
2063
|
+
}
|
|
2064
|
+
/** Constrain `param` to a ULID shape. The Laravel `->whereUlid()` equivalent. Chains. */
|
|
2065
|
+
whereUlid(param) {
|
|
2066
|
+
return this.where(param, WHERE_PATTERNS.ulid);
|
|
2067
|
+
}
|
|
2068
|
+
/** Constrain `param` to one of `values` (matched literally). The `->whereIn()` equivalent. Chains. */
|
|
2069
|
+
whereIn(param, values) {
|
|
2070
|
+
const alternation = values.map((value) => escapeRegex(value)).join("|");
|
|
2071
|
+
return this.where(param, alternation.length > 0 ? alternation : "(?!)");
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* Append middleware that wraps only this route. Accepts concrete entries (function/class) and
|
|
2075
|
+
* `string` names referencing a registered alias or middleware group (resolved at match time). The
|
|
2076
|
+
* `->middleware()` equivalent.
|
|
2077
|
+
*/
|
|
2078
|
+
middleware(...entries) {
|
|
2079
|
+
this.routeMiddleware.push(...entries);
|
|
2080
|
+
return this;
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* The middleware stack for this route (a copy), as registered — so `string` alias/group names are
|
|
2084
|
+
* returned verbatim. The {@link Router} resolves these to concrete entries via
|
|
2085
|
+
* {@link Router.resolveMiddleware} when dispatching a matched route.
|
|
2086
|
+
*/
|
|
2087
|
+
getMiddleware() {
|
|
2088
|
+
return [...this.routeMiddleware];
|
|
2089
|
+
}
|
|
2090
|
+
/** The ordered names of this route's path parameters. */
|
|
2091
|
+
parameterNames() {
|
|
2092
|
+
return [...this.compiled.params];
|
|
2093
|
+
}
|
|
2094
|
+
/**
|
|
2095
|
+
* Extract route parameters if `path` matches this route's pattern, else `undefined`. Any
|
|
2096
|
+
* {@link Route.where} constraints are enforced here: a parameter value that fails its constraint
|
|
2097
|
+
* makes the whole route a non-match (so an absent optional parameter is never constrained).
|
|
2098
|
+
*/
|
|
2099
|
+
match(path3) {
|
|
2100
|
+
const result = this.compiled.regex.exec(path3);
|
|
2101
|
+
if (!result) return void 0;
|
|
2102
|
+
const params = {};
|
|
2103
|
+
for (const [index, name] of this.compiled.params.entries()) {
|
|
2104
|
+
const value = result[index + 1];
|
|
2105
|
+
if (value !== void 0) {
|
|
2106
|
+
params[name] = value.includes("%") ? decodeURIComponent(value) : value;
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
if (this.constraints.size > 0) {
|
|
2110
|
+
for (const [name, regex] of this.constraints) {
|
|
2111
|
+
const value = params[name];
|
|
2112
|
+
if (value !== void 0 && !regex.test(value)) return void 0;
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
return params;
|
|
2116
|
+
}
|
|
2117
|
+
/** Whether this route serves `method` (HEAD falls through to GET). */
|
|
2118
|
+
handlesMethod(method) {
|
|
2119
|
+
const verb = method.toUpperCase();
|
|
2120
|
+
if (this.methods.includes(verb)) return true;
|
|
2121
|
+
return verb === "HEAD" && this.methods.includes("GET");
|
|
2122
|
+
}
|
|
2123
|
+
/** Build a concrete path from this route's pattern, substituting `params`. */
|
|
2124
|
+
url(params = {}) {
|
|
2125
|
+
const filled = this.path.replaceAll(/\{(\w+)\??\}/g, (_full, name) => {
|
|
2126
|
+
const value = params[name];
|
|
2127
|
+
if (value === void 0) {
|
|
2128
|
+
if (this.path.includes(`{${name}?}`)) return "";
|
|
2129
|
+
throw new Error(`Missing parameter [${name}] for route [${this.path}].`);
|
|
2130
|
+
}
|
|
2131
|
+
return encodeURIComponent(String(value));
|
|
2132
|
+
});
|
|
2133
|
+
return normalizePath(filled);
|
|
2134
|
+
}
|
|
2135
|
+
};
|
|
2136
|
+
var RESOURCE_SPECS = [
|
|
2137
|
+
{ method: "index", verbs: ["GET"], suffix: void 0, member: false },
|
|
2138
|
+
{ method: "create", verbs: ["GET"], suffix: "create", member: false },
|
|
2139
|
+
{ method: "store", verbs: ["POST"], suffix: void 0, member: false },
|
|
2140
|
+
{ method: "show", verbs: ["GET"], suffix: void 0, member: true },
|
|
2141
|
+
{ method: "edit", verbs: ["GET"], suffix: "edit", member: true },
|
|
2142
|
+
{ method: "update", verbs: ["PUT", "PATCH"], suffix: void 0, member: true },
|
|
2143
|
+
{ method: "destroy", verbs: ["DELETE"], suffix: void 0, member: true }
|
|
2144
|
+
];
|
|
2145
|
+
var API_EXCLUDED = ["create", "edit"];
|
|
2146
|
+
var ResourceRegistration = class {
|
|
2147
|
+
constructor(resourceName, controller, api, context, register, options = {}) {
|
|
2148
|
+
this.resourceName = resourceName;
|
|
2149
|
+
this.controller = controller;
|
|
2150
|
+
this.api = api;
|
|
2151
|
+
this.context = context;
|
|
2152
|
+
this.register = register;
|
|
2153
|
+
if (options.only !== void 0) this.onlyMethods = [...options.only];
|
|
2154
|
+
if (options.except !== void 0) this.exceptMethods = [...options.except];
|
|
2155
|
+
if (options.names !== void 0) Object.assign(this.nameOverrides, options.names);
|
|
2156
|
+
if (options.shallow === true) this.isShallow = true;
|
|
2157
|
+
if (typeof options.parameters === "string") this.parameterName = options.parameters;
|
|
2158
|
+
else if (options.parameters !== void 0) Object.assign(this.parameterMap, options.parameters);
|
|
2159
|
+
}
|
|
2160
|
+
resourceName;
|
|
2161
|
+
controller;
|
|
2162
|
+
api;
|
|
2163
|
+
context;
|
|
2164
|
+
register;
|
|
2165
|
+
onlyMethods;
|
|
2166
|
+
exceptMethods;
|
|
2167
|
+
nameOverrides = {};
|
|
2168
|
+
parameterName;
|
|
2169
|
+
parameterMap = {};
|
|
2170
|
+
isShallow = false;
|
|
2171
|
+
builtRoutes;
|
|
2172
|
+
/** Register only these resource methods. Chains. Re-resolving after the first build is a no-op. */
|
|
2173
|
+
only(methods) {
|
|
2174
|
+
this.onlyMethods = [...methods];
|
|
2175
|
+
return this;
|
|
2176
|
+
}
|
|
2177
|
+
/** Register every resource method except these. Chains. */
|
|
2178
|
+
except(methods) {
|
|
2179
|
+
this.exceptMethods = [...methods];
|
|
2180
|
+
return this;
|
|
2181
|
+
}
|
|
2182
|
+
/** Override generated route names per method (e.g. `{ show: 'users.profile' }`). Chains. */
|
|
2183
|
+
names(overrides) {
|
|
2184
|
+
Object.assign(this.nameOverrides, overrides);
|
|
2185
|
+
return this;
|
|
2186
|
+
}
|
|
2187
|
+
/** Override the URI parameter name (string) or per-resource-name map. Chains. */
|
|
2188
|
+
parameters(value) {
|
|
2189
|
+
if (typeof value === "string") this.parameterName = value;
|
|
2190
|
+
else Object.assign(this.parameterMap, value);
|
|
2191
|
+
return this;
|
|
2192
|
+
}
|
|
2193
|
+
/** Mark this resource's member routes as shallow (trailing-param-only URIs). Chains. */
|
|
2194
|
+
shallow(value) {
|
|
2195
|
+
this.isShallow = value ?? true;
|
|
2196
|
+
return this;
|
|
2197
|
+
}
|
|
2198
|
+
/** The methods this registration will produce, after applying `only`/`except` (and `api`). */
|
|
2199
|
+
selectedMethods() {
|
|
2200
|
+
let excluded = this.api ? [...API_EXCLUDED] : [];
|
|
2201
|
+
if (this.exceptMethods !== void 0) excluded = [...excluded, ...this.exceptMethods];
|
|
2202
|
+
return RESOURCE_SPECS.map((spec) => spec.method).filter((method) => {
|
|
2203
|
+
if (this.onlyMethods !== void 0 && !this.onlyMethods.includes(method)) return false;
|
|
2204
|
+
return !excluded.includes(method);
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2207
|
+
/** The resolved URI parameter name for this resource (override → string map → singular of name). */
|
|
2208
|
+
resolvedParameter() {
|
|
2209
|
+
const mapped = this.parameterMap[this.resourceName];
|
|
2210
|
+
if (mapped !== void 0) return mapped;
|
|
2211
|
+
if (this.parameterName !== void 0) return this.parameterName;
|
|
2212
|
+
return Str.singular(this.resourceName);
|
|
2213
|
+
}
|
|
2214
|
+
/** Build (once) and register every selected route, returning them. Idempotent. */
|
|
2215
|
+
resolve() {
|
|
2216
|
+
if (this.builtRoutes !== void 0) return this.builtRoutes;
|
|
2217
|
+
const param = this.resolvedParameter();
|
|
2218
|
+
const selected = new Set(this.selectedMethods());
|
|
2219
|
+
const built = [];
|
|
2220
|
+
for (const spec of RESOURCE_SPECS) {
|
|
2221
|
+
if (!selected.has(spec.method)) continue;
|
|
2222
|
+
const route = this.buildRoute(spec, param);
|
|
2223
|
+
this.register(route);
|
|
2224
|
+
built.push(route);
|
|
2225
|
+
}
|
|
2226
|
+
this.builtRoutes = built;
|
|
2227
|
+
return built;
|
|
2228
|
+
}
|
|
2229
|
+
/**
|
|
2230
|
+
* Construct a single resource {@link Route} for `spec`, naming it `name.method` and applying the
|
|
2231
|
+
* captured group prefix/middleware/domain (so a resource declared inside a group is grouped).
|
|
2232
|
+
*/
|
|
2233
|
+
buildRoute(spec, param) {
|
|
2234
|
+
const shallowMember = this.isShallow && spec.member;
|
|
2235
|
+
const base = shallowMember ? Str.singular(this.resourceName) : this.resourceName;
|
|
2236
|
+
const segments = [base];
|
|
2237
|
+
if (spec.member) segments.push(`{${param}}`);
|
|
2238
|
+
if (spec.suffix !== void 0) segments.push(spec.suffix);
|
|
2239
|
+
const fullPath = normalizePath(`${this.context.prefix}/${segments.join("/")}`);
|
|
2240
|
+
const route = new Route(
|
|
2241
|
+
[...spec.verbs],
|
|
2242
|
+
fullPath,
|
|
2243
|
+
[this.controller, spec.method],
|
|
2244
|
+
this.context.middleware,
|
|
2245
|
+
this.context.domain
|
|
2246
|
+
);
|
|
2247
|
+
if (Object.keys(this.context.where).length > 0) route.where(this.context.where);
|
|
2248
|
+
route.name(this.nameOverrides[spec.method] ?? `${this.resourceName}.${spec.method}`);
|
|
2249
|
+
return route;
|
|
2250
|
+
}
|
|
2251
|
+
};
|
|
2252
|
+
var SINGLETON_SPECS = [
|
|
2253
|
+
{ method: "show", verbs: ["GET"], suffix: void 0, api: true },
|
|
2254
|
+
{ method: "edit", verbs: ["GET"], suffix: "edit", api: false },
|
|
2255
|
+
{ method: "update", verbs: ["PUT", "PATCH"], suffix: void 0, api: true }
|
|
2256
|
+
];
|
|
2257
|
+
var SingletonRegistration = class {
|
|
2258
|
+
constructor(resourceName, controller, api, context, register) {
|
|
2259
|
+
this.resourceName = resourceName;
|
|
2260
|
+
this.controller = controller;
|
|
2261
|
+
this.api = api;
|
|
2262
|
+
this.context = context;
|
|
2263
|
+
this.register = register;
|
|
2264
|
+
}
|
|
2265
|
+
resourceName;
|
|
2266
|
+
controller;
|
|
2267
|
+
api;
|
|
2268
|
+
context;
|
|
2269
|
+
register;
|
|
2270
|
+
isDestroyable = false;
|
|
2271
|
+
builtRoutes;
|
|
2272
|
+
/** Also register `DELETE name` → `destroy`. The Laravel `->destroyable()` equivalent. Chains. */
|
|
2273
|
+
destroyable(value) {
|
|
2274
|
+
this.isDestroyable = value ?? true;
|
|
2275
|
+
return this;
|
|
2276
|
+
}
|
|
2277
|
+
/** Build (once) and register every selected route, returning them. Idempotent. */
|
|
2278
|
+
resolve() {
|
|
2279
|
+
if (this.builtRoutes !== void 0) return this.builtRoutes;
|
|
2280
|
+
const built = [];
|
|
2281
|
+
for (const spec of SINGLETON_SPECS) {
|
|
2282
|
+
if (this.api && !spec.api) continue;
|
|
2283
|
+
built.push(this.buildRoute(spec.method, spec.verbs, spec.suffix));
|
|
2284
|
+
}
|
|
2285
|
+
if (this.isDestroyable) built.push(this.buildRoute("destroy", ["DELETE"]));
|
|
2286
|
+
this.builtRoutes = built;
|
|
2287
|
+
return built;
|
|
2288
|
+
}
|
|
2289
|
+
/** Construct and register a single singleton {@link Route}, named `name.method`. */
|
|
2290
|
+
buildRoute(method, verbs, suffix) {
|
|
2291
|
+
const segments = suffix === void 0 ? this.resourceName : `${this.resourceName}/${suffix}`;
|
|
2292
|
+
const fullPath = normalizePath(`${this.context.prefix}/${segments}`);
|
|
2293
|
+
const route = new Route(
|
|
2294
|
+
[...verbs],
|
|
2295
|
+
fullPath,
|
|
2296
|
+
[this.controller, method],
|
|
2297
|
+
this.context.middleware,
|
|
2298
|
+
this.context.domain
|
|
2299
|
+
);
|
|
2300
|
+
if (Object.keys(this.context.where).length > 0) route.where(this.context.where);
|
|
2301
|
+
route.name(`${this.resourceName}.${method}`);
|
|
2302
|
+
this.register(route);
|
|
2303
|
+
return route;
|
|
2304
|
+
}
|
|
2305
|
+
};
|
|
2306
|
+
var Router = class _Router {
|
|
2307
|
+
routes = [];
|
|
2308
|
+
groupStack = [];
|
|
2309
|
+
fallbackHandler;
|
|
2310
|
+
bindings = /* @__PURE__ */ new Map();
|
|
2311
|
+
middlewareGroups = /* @__PURE__ */ new Map();
|
|
2312
|
+
middlewareAliases = /* @__PURE__ */ new Map();
|
|
2313
|
+
signingKey;
|
|
2314
|
+
pendingResources = [];
|
|
2315
|
+
viewRenderer;
|
|
2316
|
+
dispatchIndex;
|
|
2317
|
+
constructor(options = {}) {
|
|
2318
|
+
this.signingKey = options.key;
|
|
2319
|
+
this.viewRenderer = options.viewRenderer;
|
|
2320
|
+
}
|
|
2321
|
+
/** Register a `GET` route (also answers `HEAD`). */
|
|
2322
|
+
get(path3, handler) {
|
|
2323
|
+
return this.addRoute(["GET"], path3, handler);
|
|
2324
|
+
}
|
|
2325
|
+
/** Register a `POST` route. */
|
|
2326
|
+
post(path3, handler) {
|
|
2327
|
+
return this.addRoute(["POST"], path3, handler);
|
|
2328
|
+
}
|
|
2329
|
+
/** Register a `PUT` route. */
|
|
2330
|
+
put(path3, handler) {
|
|
2331
|
+
return this.addRoute(["PUT"], path3, handler);
|
|
2332
|
+
}
|
|
2333
|
+
/** Register a `PATCH` route. */
|
|
2334
|
+
patch(path3, handler) {
|
|
2335
|
+
return this.addRoute(["PATCH"], path3, handler);
|
|
2336
|
+
}
|
|
2337
|
+
/** Register a `DELETE` route. */
|
|
2338
|
+
delete(path3, handler) {
|
|
2339
|
+
return this.addRoute(["DELETE"], path3, handler);
|
|
2340
|
+
}
|
|
2341
|
+
/** Register an `OPTIONS` route. */
|
|
2342
|
+
options(path3, handler) {
|
|
2343
|
+
return this.addRoute(["OPTIONS"], path3, handler);
|
|
2344
|
+
}
|
|
2345
|
+
/** Register a route answering every standard verb. The `Route::any()` equivalent. */
|
|
2346
|
+
any(path3, handler) {
|
|
2347
|
+
return this.addRoute([...ALL_METHODS], path3, handler);
|
|
2348
|
+
}
|
|
2349
|
+
/** Register a route for an explicit set of verbs. The `Route::match()` equivalent. */
|
|
2350
|
+
on(methods, path3, handler) {
|
|
2351
|
+
return this.addRoute(methods, path3, handler);
|
|
2352
|
+
}
|
|
2353
|
+
// --- Convenience routes (the `Route::view` / `Route::redirect` family) -----
|
|
2354
|
+
/**
|
|
2355
|
+
* Install the renderer {@link Router.view} routes defer to — the seam an app (or a view package)
|
|
2356
|
+
* plugs its template engine into. The Laravel view-factory binding equivalent. Chains.
|
|
2357
|
+
*/
|
|
2358
|
+
renderViewsUsing(renderer) {
|
|
2359
|
+
this.viewRenderer = renderer;
|
|
2360
|
+
return this;
|
|
2361
|
+
}
|
|
2362
|
+
/**
|
|
2363
|
+
* Register a `GET` route that renders `view` with `data` — the Laravel `Route::view()` equivalent.
|
|
2364
|
+
* `@plinthjs/http` ships no template engine, so rendering is deferred to the {@link ViewRenderer}
|
|
2365
|
+
* configured via {@link Router.renderViewsUsing} (or the `viewRenderer` construction option);
|
|
2366
|
+
* dispatching the route without one throws a clear error. The renderer's string becomes an HTML
|
|
2367
|
+
* {@link Response}.
|
|
2368
|
+
*/
|
|
2369
|
+
view(uri, view, data = {}) {
|
|
2370
|
+
return this.get(uri, async (req) => {
|
|
2371
|
+
if (this.viewRenderer === void 0) {
|
|
2372
|
+
throw new Error(
|
|
2373
|
+
`No view renderer is configured to render [${view}]. Install one with renderViewsUsing() or the { viewRenderer } Router option.`
|
|
2374
|
+
);
|
|
2375
|
+
}
|
|
2376
|
+
return Response.html(await this.viewRenderer(view, data, req));
|
|
2377
|
+
});
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* Register a route answering every verb with a redirect to `destination` (default `302`). The
|
|
2381
|
+
* Laravel `Route::redirect()` equivalent.
|
|
2382
|
+
*/
|
|
2383
|
+
redirect(uri, destination, status = 302) {
|
|
2384
|
+
return this.any(uri, () => Response.redirect(destination, status));
|
|
2385
|
+
}
|
|
2386
|
+
/** Register a `301` redirect route. The Laravel `Route::permanentRedirect()` equivalent. */
|
|
2387
|
+
permanentRedirect(uri, destination) {
|
|
2388
|
+
return this.redirect(uri, destination, 301);
|
|
2389
|
+
}
|
|
2390
|
+
// --- Resource routes (the `Route::resource` family) -----------------------
|
|
2391
|
+
/**
|
|
2392
|
+
* Register the seven canonical RESTful routes for `controller` under `name`, mapping each verb+URI
|
|
2393
|
+
* to a controller method — the Laravel `Route::resource()` equivalent:
|
|
2394
|
+
*
|
|
2395
|
+
* - `GET name` → `index` (`name.index`)
|
|
2396
|
+
* - `GET name/create` → `create` (`name.create`)
|
|
2397
|
+
* - `POST name` → `store` (`name.store`)
|
|
2398
|
+
* - `GET name/{param}` → `show` (`name.show`)
|
|
2399
|
+
* - `GET name/{param}/edit` → `edit` (`name.edit`)
|
|
2400
|
+
* - `PUT|PATCH name/{param}` → `update` (`name.update`)
|
|
2401
|
+
* - `DELETE name/{param}` → `destroy` (`name.destroy`)
|
|
2402
|
+
*
|
|
2403
|
+
* `{param}` defaults to `Str.singular(name)` (override via `options.parameters` or `.parameters()`).
|
|
2404
|
+
* Returns a {@link ResourceRegistration} whose `.only()` / `.except()` / `.names()` /
|
|
2405
|
+
* `.parameters()` / `.shallow()` narrow or rename the set; the same controls are accepted via
|
|
2406
|
+
* `options`. Routes are **deferred**: they materialize (as normal, named, middleware-able,
|
|
2407
|
+
* cacheable {@link Route}s) the first time the router is matched/enumerated/url'd/cached, so
|
|
2408
|
+
* chaining after this call still takes effect. The enclosing {@link Router.group} context is
|
|
2409
|
+
* captured now and applied at build time.
|
|
2410
|
+
*/
|
|
2411
|
+
resource(name, controller, options) {
|
|
2412
|
+
return this.registerResource(name, controller, false, options);
|
|
2413
|
+
}
|
|
2414
|
+
/**
|
|
2415
|
+
* Like {@link Router.resource} but for APIs: registers the same routes minus `create` and `edit`
|
|
2416
|
+
* (the HTML form-presenting endpoints). The Laravel `Route::apiResource()` equivalent.
|
|
2417
|
+
*/
|
|
2418
|
+
apiResource(name, controller, options) {
|
|
2419
|
+
return this.registerResource(name, controller, true, options);
|
|
2420
|
+
}
|
|
2421
|
+
/** Shared builder for {@link Router.resource} / {@link Router.apiResource}. */
|
|
2422
|
+
registerResource(name, controller, api, options) {
|
|
2423
|
+
const registration = new ResourceRegistration(
|
|
2424
|
+
name,
|
|
2425
|
+
controller,
|
|
2426
|
+
api,
|
|
2427
|
+
this.currentResourceContext(),
|
|
2428
|
+
(route) => {
|
|
2429
|
+
this.registerRoute(route);
|
|
2430
|
+
},
|
|
2431
|
+
options ?? {}
|
|
2432
|
+
);
|
|
2433
|
+
this.pendingResources.push(registration);
|
|
2434
|
+
return registration;
|
|
2435
|
+
}
|
|
2436
|
+
/**
|
|
2437
|
+
* Register a singleton resource — routes for a resource with exactly one instance (a profile, a
|
|
2438
|
+
* settings page), mapping `GET name` → `show`, `GET name/edit` → `edit`, and `PUT|PATCH name` →
|
|
2439
|
+
* `update` (no `{param}` segment, no `index`/`create`/`store`). The Laravel `Route::singleton()`
|
|
2440
|
+
* equivalent. Chain {@link SingletonRegistration.destroyable} to add `DELETE name` → `destroy`.
|
|
2441
|
+
* Registration is deferred exactly like {@link Router.resource}.
|
|
2442
|
+
*/
|
|
2443
|
+
singleton(name, controller) {
|
|
2444
|
+
return this.registerSingleton(name, controller, false);
|
|
2445
|
+
}
|
|
2446
|
+
/**
|
|
2447
|
+
* Like {@link Router.singleton} but for APIs: omits the HTML `edit` route, registering only
|
|
2448
|
+
* `show` and `update` (plus `destroy` after `.destroyable()`). The Laravel
|
|
2449
|
+
* `Route::apiSingleton()` equivalent.
|
|
2450
|
+
*/
|
|
2451
|
+
apiSingleton(name, controller) {
|
|
2452
|
+
return this.registerSingleton(name, controller, true);
|
|
2453
|
+
}
|
|
2454
|
+
/** Shared builder for {@link Router.singleton} / {@link Router.apiSingleton}. */
|
|
2455
|
+
registerSingleton(name, controller, api) {
|
|
2456
|
+
const registration = new SingletonRegistration(
|
|
2457
|
+
name,
|
|
2458
|
+
controller,
|
|
2459
|
+
api,
|
|
2460
|
+
this.currentResourceContext(),
|
|
2461
|
+
(route) => {
|
|
2462
|
+
this.registerRoute(route);
|
|
2463
|
+
}
|
|
2464
|
+
);
|
|
2465
|
+
this.pendingResources.push(registration);
|
|
2466
|
+
return registration;
|
|
2467
|
+
}
|
|
2468
|
+
/** Snapshot the active group stack into a {@link ResourceContext} for deferred resource building. */
|
|
2469
|
+
currentResourceContext() {
|
|
2470
|
+
const prefix = this.groupStack.map((frame) => frame.prefix).join("");
|
|
2471
|
+
const middleware = this.groupStack.flatMap((frame) => [...frame.middleware]);
|
|
2472
|
+
let domain;
|
|
2473
|
+
for (const frame of this.groupStack) {
|
|
2474
|
+
if (frame.domain !== void 0) domain = frame.domain;
|
|
2475
|
+
}
|
|
2476
|
+
return { prefix, middleware, domain, where: this.currentGroupWhere() };
|
|
2477
|
+
}
|
|
2478
|
+
/** The merged group-level parameter constraints, innermost group winning on a key clash. */
|
|
2479
|
+
currentGroupWhere() {
|
|
2480
|
+
const merged = {};
|
|
2481
|
+
for (const frame of this.groupStack) Object.assign(merged, frame.where);
|
|
2482
|
+
return merged;
|
|
2483
|
+
}
|
|
2484
|
+
/**
|
|
2485
|
+
* Materialize any not-yet-built resource registrations into real routes. Idempotent and cheap
|
|
2486
|
+
* after the first call; invoked by {@link Router.match}, {@link Router.getRoutes},
|
|
2487
|
+
* {@link Router.url}, and {@link Router.toCache} so deferred resources are always resolved before
|
|
2488
|
+
* the routes are observed.
|
|
2489
|
+
*/
|
|
2490
|
+
flushResources() {
|
|
2491
|
+
if (this.pendingResources.length === 0) return;
|
|
2492
|
+
const pending = this.pendingResources.splice(0);
|
|
2493
|
+
for (const registration of pending) registration.resolve();
|
|
2494
|
+
}
|
|
2495
|
+
/** Apply a shared prefix and/or middleware to every route registered inside `callback`. */
|
|
2496
|
+
group(options, callback) {
|
|
2497
|
+
const prefix = options.prefix === void 0 ? "" : normalizePath(options.prefix);
|
|
2498
|
+
const middleware = options.middleware === void 0 ? [] : Array.isArray(options.middleware) ? options.middleware : [options.middleware];
|
|
2499
|
+
this.groupStack.push({ prefix, middleware, domain: options.domain, where: options.where ?? {} });
|
|
2500
|
+
try {
|
|
2501
|
+
callback(this);
|
|
2502
|
+
} finally {
|
|
2503
|
+
this.groupStack.pop();
|
|
2504
|
+
}
|
|
2505
|
+
return this;
|
|
2506
|
+
}
|
|
2507
|
+
/** Register a fallback handler invoked when no route matches. The `Route::fallback()` equivalent. */
|
|
2508
|
+
fallback(handler) {
|
|
2509
|
+
this.fallbackHandler = handler;
|
|
2510
|
+
return this;
|
|
2511
|
+
}
|
|
2512
|
+
/** Register a route-model binding: a `{key}` param resolves through `resolver` (`Route::bind`). */
|
|
2513
|
+
bind(key, resolver) {
|
|
2514
|
+
this.bindings.set(key, resolver);
|
|
2515
|
+
return this;
|
|
2516
|
+
}
|
|
2517
|
+
/** The binding resolver registered for `key`, if any. */
|
|
2518
|
+
binding(key) {
|
|
2519
|
+
return this.bindings.get(key);
|
|
2520
|
+
}
|
|
2521
|
+
// --- Middleware groups + aliases (the `$middlewareGroups` / `$middlewareAliases` family) ------
|
|
2522
|
+
/**
|
|
2523
|
+
* Register a named middleware *group* — a list of references (concrete entries and/or other
|
|
2524
|
+
* alias/group names) that expand in place wherever the group name is used on a route or group. The
|
|
2525
|
+
* Laravel `Route::middlewareGroup('web', [...])` equivalent. Re-registering a name replaces it.
|
|
2526
|
+
* Names are resolved (recursively) at match time by {@link Router.resolveMiddleware}.
|
|
2527
|
+
*/
|
|
2528
|
+
middlewareGroup(name, entries) {
|
|
2529
|
+
this.middlewareGroups.set(name, [...entries]);
|
|
2530
|
+
return this;
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2533
|
+
* Register a middleware *alias* — a short `string` name for a single concrete {@link MiddlewareEntry}.
|
|
2534
|
+
* The Laravel `$middlewareAliases` / `Route::aliasMiddleware('auth', Authenticate)` equivalent.
|
|
2535
|
+
* Re-registering a name replaces it.
|
|
2536
|
+
*/
|
|
2537
|
+
aliasMiddleware(name, entry) {
|
|
2538
|
+
this.middlewareAliases.set(name, entry);
|
|
2539
|
+
return this;
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* The references registered for a middleware group, or `undefined` when no group is registered
|
|
2543
|
+
* under `name`. Returns a copy; mutating it does not affect the registration.
|
|
2544
|
+
*/
|
|
2545
|
+
getMiddlewareGroup(name) {
|
|
2546
|
+
const group = this.middlewareGroups.get(name);
|
|
2547
|
+
return group === void 0 ? void 0 : [...group];
|
|
2548
|
+
}
|
|
2549
|
+
/** The concrete entry registered for a middleware alias, or `undefined` when none is registered. */
|
|
2550
|
+
getMiddlewareAlias(name) {
|
|
2551
|
+
return this.middlewareAliases.get(name);
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* Resolve a middleware reference list to concrete {@link MiddlewareEntry entries}, expanding
|
|
2555
|
+
* `string` names: a name resolves first as an **alias** (→ its single entry), else as a **group**
|
|
2556
|
+
* (→ its references, expanded recursively). An unknown name **throws** — mirroring Laravel, which
|
|
2557
|
+
* raises when a route references a middleware that is neither an alias nor a group. Cyclic group
|
|
2558
|
+
* references (a group that, directly or transitively, contains itself) also throw rather than
|
|
2559
|
+
* recursing without bound. Function/class entries pass through unchanged and in order.
|
|
2560
|
+
*
|
|
2561
|
+
* The {@link HttpKernel} calls this on a matched route's {@link Route.getMiddleware} stack before
|
|
2562
|
+
* running it.
|
|
2563
|
+
*/
|
|
2564
|
+
resolveMiddleware(references) {
|
|
2565
|
+
return this.expandMiddleware(references, []);
|
|
2566
|
+
}
|
|
2567
|
+
/**
|
|
2568
|
+
* Recursive worker for {@link Router.resolveMiddleware}. `groupPath` is the stack of group names
|
|
2569
|
+
* currently being expanded; revisiting a name already on the path is a cycle (a group that
|
|
2570
|
+
* directly or transitively contains itself) and throws. The same group may still appear in
|
|
2571
|
+
* sibling branches — only re-entrancy along a single path is rejected.
|
|
2572
|
+
*/
|
|
2573
|
+
expandMiddleware(references, groupPath) {
|
|
2574
|
+
const resolved = [];
|
|
2575
|
+
for (const reference of references) {
|
|
2576
|
+
if (typeof reference !== "string") {
|
|
2577
|
+
resolved.push(reference);
|
|
2578
|
+
continue;
|
|
2579
|
+
}
|
|
2580
|
+
const alias = this.middlewareAliases.get(reference);
|
|
2581
|
+
if (alias !== void 0) {
|
|
2582
|
+
resolved.push(alias);
|
|
2583
|
+
continue;
|
|
2584
|
+
}
|
|
2585
|
+
const group = this.middlewareGroups.get(reference);
|
|
2586
|
+
if (group !== void 0) {
|
|
2587
|
+
if (groupPath.includes(reference)) {
|
|
2588
|
+
throw new Error(
|
|
2589
|
+
`Middleware group [${reference}] references itself (via ${[...groupPath, reference].join(" -> ")}); resolve the cycle.`
|
|
2590
|
+
);
|
|
2591
|
+
}
|
|
2592
|
+
resolved.push(...this.expandMiddleware(group, [...groupPath, reference]));
|
|
2593
|
+
continue;
|
|
2594
|
+
}
|
|
2595
|
+
throw new Error(
|
|
2596
|
+
`Middleware [${reference}] is not a registered alias or group. Register it with aliasMiddleware()/middlewareGroup(), or pass a concrete middleware entry.`
|
|
2597
|
+
);
|
|
2598
|
+
}
|
|
2599
|
+
return resolved;
|
|
2600
|
+
}
|
|
2601
|
+
/** Every registered route (a copy). Pending resource registrations are materialized first. */
|
|
2602
|
+
getRoutes() {
|
|
2603
|
+
this.flushResources();
|
|
2604
|
+
return [...this.routes];
|
|
2605
|
+
}
|
|
2606
|
+
// --- Route caching (the `route:cache` family) -----------------------------
|
|
2607
|
+
/**
|
|
2608
|
+
* Serialize the registered routes to a plain, JSON-serializable {@link RouteCache} snapshot
|
|
2609
|
+
* (methods, path, name, domain, middleware names, and the `[controller, method]` action).
|
|
2610
|
+
*
|
|
2611
|
+
* Closures cannot be serialized. Mirroring Laravel's `route:cache` — which aborts with
|
|
2612
|
+
* "Unable to prepare route … for serialization. Uses Closure." — this **throws** when any route
|
|
2613
|
+
* uses a closure handler, rather than silently dropping it, so a cache is always complete or
|
|
2614
|
+
* absent. Rehydrate with {@link Router.loadCache} or {@link Router.fromCache}.
|
|
2615
|
+
*/
|
|
2616
|
+
toCache() {
|
|
2617
|
+
this.flushResources();
|
|
2618
|
+
const routes = [];
|
|
2619
|
+
for (const route of this.routes) {
|
|
2620
|
+
const { handler } = route;
|
|
2621
|
+
const serializable = toSerializableAction(handler);
|
|
2622
|
+
if (serializable === void 0) {
|
|
2623
|
+
const named = route.getName();
|
|
2624
|
+
const label = named === void 0 ? route.path : `${route.path} (${named})`;
|
|
2625
|
+
throw new Error(
|
|
2626
|
+
`Unable to prepare route [${label}] for caching: it uses a Closure handler. Convert it to a [Controller, method] action before caching routes.`
|
|
2627
|
+
);
|
|
2628
|
+
}
|
|
2629
|
+
const [controller, method] = serializable;
|
|
2630
|
+
routes.push({
|
|
2631
|
+
methods: [...route.methods],
|
|
2632
|
+
path: route.path,
|
|
2633
|
+
name: route.getName(),
|
|
2634
|
+
domain: route.getDomain(),
|
|
2635
|
+
middleware: route.getMiddleware().map((entry) => middlewareName(entry)),
|
|
2636
|
+
action: [controller.name, method]
|
|
2637
|
+
});
|
|
2638
|
+
}
|
|
2639
|
+
return { routes };
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* Rehydrate a {@link RouteCache} onto this Router, appending the cached routes. `options.controller`
|
|
2643
|
+
* maps each cached controller name back to its constructor; an optional `options.middleware`
|
|
2644
|
+
* resolver reattaches middleware by name (omitted middleware are skipped). Returns `this`.
|
|
2645
|
+
*/
|
|
2646
|
+
loadCache(snapshot, options) {
|
|
2647
|
+
for (const cached of snapshot.routes) {
|
|
2648
|
+
const [controllerName, method] = cached.action;
|
|
2649
|
+
const controller = options.controller(controllerName);
|
|
2650
|
+
const middleware = options.middleware === void 0 ? [] : cached.middleware.map((name) => options.middleware(name));
|
|
2651
|
+
const route = new Route(
|
|
2652
|
+
[...cached.methods],
|
|
2653
|
+
cached.path,
|
|
2654
|
+
[controller, method],
|
|
2655
|
+
middleware,
|
|
2656
|
+
cached.domain
|
|
2657
|
+
);
|
|
2658
|
+
if (cached.name !== void 0) route.name(cached.name);
|
|
2659
|
+
this.registerRoute(route);
|
|
2660
|
+
}
|
|
2661
|
+
return this;
|
|
2662
|
+
}
|
|
2663
|
+
/**
|
|
2664
|
+
* Build a fresh {@link Router} from a {@link RouteCache} snapshot, resolving cached controller
|
|
2665
|
+
* names through `resolver`. The static `route:cache` rehydration entry point; pass
|
|
2666
|
+
* {@link LoadCacheOptions} (or a bare {@link ControllerResolver}) plus optional {@link RouterOptions}.
|
|
2667
|
+
*/
|
|
2668
|
+
static fromCache(snapshot, resolver, options = {}) {
|
|
2669
|
+
const router = new _Router(options);
|
|
2670
|
+
const load = typeof resolver === "function" ? { controller: resolver } : resolver;
|
|
2671
|
+
return router.loadCache(snapshot, load);
|
|
2672
|
+
}
|
|
2673
|
+
/**
|
|
2674
|
+
* Resolve an inbound `method`+`path` to a route, a 405, or a 404. When `host` is supplied, routes
|
|
2675
|
+
* carrying a {@link Route.domain domain} only match a host that satisfies the pattern, and the
|
|
2676
|
+
* domain's `{param}` labels are merged into the result ahead of the path params; routes without a
|
|
2677
|
+
* domain match regardless of host. When `host` is omitted, domain-carrying routes are skipped
|
|
2678
|
+
* (host-agnostic call sites keep their prior behavior for domain-less routes).
|
|
2679
|
+
*/
|
|
2680
|
+
match(method, path3, host) {
|
|
2681
|
+
this.flushResources();
|
|
2682
|
+
const index = this.dispatchIndex ?? this.buildDispatchIndex();
|
|
2683
|
+
const normalized = normalizePath(path3);
|
|
2684
|
+
const verb = method.toUpperCase();
|
|
2685
|
+
const staticEntries = index.staticPaths.get(normalized);
|
|
2686
|
+
const bucket = index.dynamicByLength.get(countSegments(normalized));
|
|
2687
|
+
let firstEntries;
|
|
2688
|
+
let wildcardEntries;
|
|
2689
|
+
if (bucket !== void 0) {
|
|
2690
|
+
firstEntries = bucket.byFirst.get(firstSegment(normalized));
|
|
2691
|
+
if (bucket.wildcard.length > 0) wildcardEntries = bucket.wildcard;
|
|
2692
|
+
}
|
|
2693
|
+
let allowed;
|
|
2694
|
+
let staticAt = 0;
|
|
2695
|
+
let firstAt = 0;
|
|
2696
|
+
let wildcardAt = 0;
|
|
2697
|
+
for (; ; ) {
|
|
2698
|
+
const nextStatic = staticEntries === void 0 ? void 0 : staticEntries[staticAt];
|
|
2699
|
+
const nextFirst = firstEntries === void 0 ? void 0 : firstEntries[firstAt];
|
|
2700
|
+
const nextWildcard = wildcardEntries === void 0 ? void 0 : wildcardEntries[wildcardAt];
|
|
2701
|
+
let entry = nextStatic;
|
|
2702
|
+
let source = 0;
|
|
2703
|
+
if (nextFirst !== void 0 && (entry === void 0 || nextFirst.order < entry.order)) {
|
|
2704
|
+
entry = nextFirst;
|
|
2705
|
+
source = 1;
|
|
2706
|
+
}
|
|
2707
|
+
if (nextWildcard !== void 0 && (entry === void 0 || nextWildcard.order < entry.order)) {
|
|
2708
|
+
entry = nextWildcard;
|
|
2709
|
+
source = 2;
|
|
2710
|
+
}
|
|
2711
|
+
if (entry === void 0) break;
|
|
2712
|
+
const fromStatic = source === 0;
|
|
2713
|
+
if (fromStatic) staticAt += 1;
|
|
2714
|
+
else if (source === 1) firstAt += 1;
|
|
2715
|
+
else wildcardAt += 1;
|
|
2716
|
+
const { route } = entry;
|
|
2717
|
+
let domainParams;
|
|
2718
|
+
if (route.getDomain() !== void 0) {
|
|
2719
|
+
domainParams = route.matchDomain(host);
|
|
2720
|
+
if (domainParams === void 0) continue;
|
|
2721
|
+
}
|
|
2722
|
+
const params = fromStatic ? {} : route.match(normalized);
|
|
2723
|
+
if (params === void 0) continue;
|
|
2724
|
+
if (route.methods.includes(verb) || verb === "HEAD" && route.methods.includes("GET")) {
|
|
2725
|
+
const merged = domainParams === void 0 ? params : { ...domainParams, ...params };
|
|
2726
|
+
return { type: "matched", route, params: merged };
|
|
2727
|
+
}
|
|
2728
|
+
allowed ??= /* @__PURE__ */ new Set();
|
|
2729
|
+
for (const routeVerb of route.methods) allowed.add(routeVerb);
|
|
2730
|
+
}
|
|
2731
|
+
if (allowed !== void 0 && allowed.size > 0) {
|
|
2732
|
+
return { type: "method-not-allowed", allowed: [...allowed] };
|
|
2733
|
+
}
|
|
2734
|
+
if (this.fallbackHandler !== void 0) {
|
|
2735
|
+
const route = new Route([verb], normalized, this.fallbackHandler);
|
|
2736
|
+
return { type: "matched", route, params: {} };
|
|
2737
|
+
}
|
|
2738
|
+
return { type: "not-found" };
|
|
2739
|
+
}
|
|
2740
|
+
/** Build (and memoize) the {@link DispatchIndex} over the current route list. */
|
|
2741
|
+
buildDispatchIndex() {
|
|
2742
|
+
const staticPaths = /* @__PURE__ */ new Map();
|
|
2743
|
+
const dynamicByLength = /* @__PURE__ */ new Map();
|
|
2744
|
+
for (const [order, route] of this.routes.entries()) {
|
|
2745
|
+
const segments = parseSegments(route.path);
|
|
2746
|
+
let optionalCount = 0;
|
|
2747
|
+
let staticPath = "";
|
|
2748
|
+
let isStatic = true;
|
|
2749
|
+
for (const segment of segments) {
|
|
2750
|
+
if (segment.kind === "literal") {
|
|
2751
|
+
staticPath += `/${segment.value}`;
|
|
2752
|
+
} else {
|
|
2753
|
+
isStatic = false;
|
|
2754
|
+
if (segment.kind === "optional") optionalCount += 1;
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
2757
|
+
const entry = { route, order };
|
|
2758
|
+
if (isStatic) {
|
|
2759
|
+
const key = staticPath === "" ? "/" : staticPath;
|
|
2760
|
+
const list = staticPaths.get(key);
|
|
2761
|
+
if (list === void 0) staticPaths.set(key, [entry]);
|
|
2762
|
+
else list.push(entry);
|
|
2763
|
+
continue;
|
|
2764
|
+
}
|
|
2765
|
+
const head = segments[0];
|
|
2766
|
+
const firstLiteral = head?.kind === "literal" ? head.value : void 0;
|
|
2767
|
+
for (let count = segments.length - optionalCount; count <= segments.length; count += 1) {
|
|
2768
|
+
let bucket = dynamicByLength.get(count);
|
|
2769
|
+
if (bucket === void 0) {
|
|
2770
|
+
bucket = { byFirst: /* @__PURE__ */ new Map(), wildcard: [] };
|
|
2771
|
+
dynamicByLength.set(count, bucket);
|
|
2772
|
+
}
|
|
2773
|
+
if (firstLiteral === void 0) {
|
|
2774
|
+
bucket.wildcard.push(entry);
|
|
2775
|
+
} else {
|
|
2776
|
+
const list = bucket.byFirst.get(firstLiteral);
|
|
2777
|
+
if (list === void 0) bucket.byFirst.set(firstLiteral, [entry]);
|
|
2778
|
+
else list.push(entry);
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
const index = { staticPaths, dynamicByLength };
|
|
2783
|
+
this.dispatchIndex = index;
|
|
2784
|
+
return index;
|
|
2785
|
+
}
|
|
2786
|
+
/** Append a registered route and drop the dispatch index so the next match rebuilds it. */
|
|
2787
|
+
registerRoute(route) {
|
|
2788
|
+
this.routes.push(route);
|
|
2789
|
+
this.dispatchIndex = void 0;
|
|
2790
|
+
}
|
|
2791
|
+
/** Build a URL for a named route, optionally appending a query string. The `route()` helper. */
|
|
2792
|
+
url(name, params = {}, query) {
|
|
2793
|
+
this.flushResources();
|
|
2794
|
+
const route = this.routes.find((candidate) => candidate.getName() === name);
|
|
2795
|
+
if (route === void 0) throw new Error(`Route [${name}] is not defined.`);
|
|
2796
|
+
let url = route.url(params);
|
|
2797
|
+
if (query !== void 0) {
|
|
2798
|
+
const search = new URLSearchParams();
|
|
2799
|
+
for (const [key, value] of Object.entries(query)) search.set(key, String(value));
|
|
2800
|
+
const rendered = search.toString();
|
|
2801
|
+
if (rendered.length > 0) url += `?${rendered}`;
|
|
2802
|
+
}
|
|
2803
|
+
return url;
|
|
2804
|
+
}
|
|
2805
|
+
// --- Signed URLs (the `URL::signedRoute` family) --------------------------
|
|
2806
|
+
/** Set (or replace) the secret used to sign and verify URLs. The app-key configuration step. */
|
|
2807
|
+
setSigningKey(key) {
|
|
2808
|
+
this.signingKey = key;
|
|
2809
|
+
return this;
|
|
2810
|
+
}
|
|
2811
|
+
/** The configured signing key, asserting one is set (signing without a key is a programmer error). */
|
|
2812
|
+
requireKey() {
|
|
2813
|
+
if (this.signingKey === void 0 || this.signingKey.length === 0) {
|
|
2814
|
+
throw new Error(
|
|
2815
|
+
"A signing key is required; construct the Router with { key } or setSigningKey()."
|
|
2816
|
+
);
|
|
2817
|
+
}
|
|
2818
|
+
return this.signingKey;
|
|
2819
|
+
}
|
|
2820
|
+
/**
|
|
2821
|
+
* Build a signed URL for the named route. The Laravel `URL::signedRoute()` equivalent: the route
|
|
2822
|
+
* URL is generated as usual, an optional `expires` (a {@link Date} or unix-seconds number) is
|
|
2823
|
+
* appended, and an HMAC `signature` over the canonical URL is added last. Verify it later with
|
|
2824
|
+
* {@link Router.hasValidSignature}.
|
|
2825
|
+
*/
|
|
2826
|
+
signedUrl(name, params = {}, expiresAt, query = {}) {
|
|
2827
|
+
const key = this.requireKey();
|
|
2828
|
+
const search = new URLSearchParams();
|
|
2829
|
+
for (const [param, value] of Object.entries(query)) search.set(param, String(value));
|
|
2830
|
+
if (expiresAt !== void 0) search.set(EXPIRES_PARAM, String(toUnixSeconds(expiresAt)));
|
|
2831
|
+
const pathname = this.url(name, params);
|
|
2832
|
+
const signature = sign(key, canonicalize(pathname, search));
|
|
2833
|
+
search.set(SIGNATURE_PARAM, signature);
|
|
2834
|
+
return `${pathname}?${search.toString()}`;
|
|
2835
|
+
}
|
|
2836
|
+
/**
|
|
2837
|
+
* Build a signed URL that expires after `expiresIn` seconds from now. The Laravel
|
|
2838
|
+
* `URL::temporarySignedRoute()` equivalent (with the expiry expressed in seconds rather than a
|
|
2839
|
+
* `DateTime`/minutes).
|
|
2840
|
+
*/
|
|
2841
|
+
temporarySignedUrl(name, expiresIn, params = {}, query = {}) {
|
|
2842
|
+
const expiresAt = Math.floor(Date.now() / 1e3) + Math.floor(expiresIn);
|
|
2843
|
+
return this.signedUrl(name, params, expiresAt, query);
|
|
2844
|
+
}
|
|
2845
|
+
/**
|
|
2846
|
+
* Validate the signature on a `path?query` string, returning a {@link SignatureResult} describing
|
|
2847
|
+
* the outcome (`valid`, `missing`, `invalid`, or `expired`). The low-level check behind
|
|
2848
|
+
* {@link Router.hasValidSignature}; a `false`-returning caller can use this to distinguish *why*.
|
|
2849
|
+
*/
|
|
2850
|
+
validateSignature(url) {
|
|
2851
|
+
const key = this.requireKey();
|
|
2852
|
+
const parsed = new URL(url, "http://localhost");
|
|
2853
|
+
const provided = parsed.searchParams.get(SIGNATURE_PARAM);
|
|
2854
|
+
if (provided === null) return "missing";
|
|
2855
|
+
const expected = sign(key, canonicalize(parsed.pathname, parsed.searchParams));
|
|
2856
|
+
if (!hashEquals(provided, expected)) return "invalid";
|
|
2857
|
+
const expires = parsed.searchParams.get(EXPIRES_PARAM);
|
|
2858
|
+
if (expires !== null && Number(expires) < Math.floor(Date.now() / 1e3)) return "expired";
|
|
2859
|
+
return "valid";
|
|
2860
|
+
}
|
|
2861
|
+
/**
|
|
2862
|
+
* Whether `req` carries a valid (and unexpired) signature. The `$request->hasValidSignature()`
|
|
2863
|
+
* equivalent: recomputes the HMAC over the request's path+query (minus `signature`) and compares
|
|
2864
|
+
* in constant time.
|
|
2865
|
+
*/
|
|
2866
|
+
hasValidSignature(req) {
|
|
2867
|
+
return this.validateSignature(req.url()) === "valid";
|
|
2868
|
+
}
|
|
2869
|
+
/**
|
|
2870
|
+
* A middleware that aborts unsigned/invalid/expired requests with a `403` (the Laravel
|
|
2871
|
+
* `signed` / `ValidateSignature` middleware). On a valid signature it passes control inward.
|
|
2872
|
+
*/
|
|
2873
|
+
signedMiddleware() {
|
|
2874
|
+
return (req, next) => {
|
|
2875
|
+
if (this.validateSignature(req.url()) !== "valid") {
|
|
2876
|
+
throw new HttpException(403, "Invalid signature.");
|
|
2877
|
+
}
|
|
2878
|
+
return next(req);
|
|
2879
|
+
};
|
|
2880
|
+
}
|
|
2881
|
+
addRoute(methods, path3, handler) {
|
|
2882
|
+
const prefix = this.groupStack.map((frame) => frame.prefix).join("");
|
|
2883
|
+
const groupMiddleware = this.groupStack.flatMap((frame) => [...frame.middleware]);
|
|
2884
|
+
const fullPath = normalizePath(`${prefix}${normalizePath(path3)}`);
|
|
2885
|
+
let domain;
|
|
2886
|
+
for (const frame of this.groupStack) {
|
|
2887
|
+
if (frame.domain !== void 0) domain = frame.domain;
|
|
2888
|
+
}
|
|
2889
|
+
const route = new Route(methods, fullPath, handler, groupMiddleware, domain);
|
|
2890
|
+
const groupWhere = this.currentGroupWhere();
|
|
2891
|
+
if (Object.keys(groupWhere).length > 0) route.where(groupWhere);
|
|
2892
|
+
this.registerRoute(route);
|
|
2893
|
+
return route;
|
|
2894
|
+
}
|
|
2895
|
+
};
|
|
2896
|
+
async function dispatch(kernel, nodeReq, nodeRes, options) {
|
|
2897
|
+
let request;
|
|
2898
|
+
try {
|
|
2899
|
+
request = await Request.fromNode(nodeReq, options);
|
|
2900
|
+
} catch (error) {
|
|
2901
|
+
if (error instanceof PayloadTooLargeHttpException) {
|
|
2902
|
+
nodeRes.writeHead(413, {
|
|
2903
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
2904
|
+
Connection: "close"
|
|
2905
|
+
});
|
|
2906
|
+
nodeRes.end("Payload Too Large");
|
|
2907
|
+
return;
|
|
2908
|
+
}
|
|
2909
|
+
throw error;
|
|
2910
|
+
}
|
|
2911
|
+
const response = await kernel.handle(request);
|
|
2912
|
+
if (response.isStream()) {
|
|
2913
|
+
await response.writeStreamTo(nodeRes);
|
|
2914
|
+
} else {
|
|
2915
|
+
response.writeTo(nodeRes);
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
function createServer(kernel, options = {}) {
|
|
2919
|
+
return createServer$1((nodeReq, nodeRes) => {
|
|
2920
|
+
void dispatch(kernel, nodeReq, nodeRes, options).catch(() => {
|
|
2921
|
+
if (nodeRes.headersSent) {
|
|
2922
|
+
nodeRes.destroy();
|
|
2923
|
+
} else {
|
|
2924
|
+
nodeRes.statusCode = 500;
|
|
2925
|
+
nodeRes.end("Internal Server Error");
|
|
2926
|
+
}
|
|
2927
|
+
});
|
|
2928
|
+
});
|
|
2929
|
+
}
|
|
2930
|
+
function serve(kernel, port, host, options) {
|
|
2931
|
+
const server = createServer(kernel, options);
|
|
2932
|
+
return new Promise((resolve, reject) => {
|
|
2933
|
+
const onError = (error) => {
|
|
2934
|
+
server.off("listening", onListening);
|
|
2935
|
+
reject(error);
|
|
2936
|
+
};
|
|
2937
|
+
const onListening = () => {
|
|
2938
|
+
server.off("error", onError);
|
|
2939
|
+
resolve(server);
|
|
2940
|
+
};
|
|
2941
|
+
server.once("error", onError);
|
|
2942
|
+
if (host === void 0) server.listen(port, onListening);
|
|
2943
|
+
else server.listen(port, host, onListening);
|
|
2944
|
+
});
|
|
2945
|
+
}
|
|
2946
|
+
function gracefulShutdown(server, options = {}) {
|
|
2947
|
+
const signals = options.signals ?? ["SIGTERM", "SIGINT"];
|
|
2948
|
+
const timeout = options.timeout ?? 1e4;
|
|
2949
|
+
const exit = options.exit ?? ((code) => {
|
|
2950
|
+
process.exit(code);
|
|
2951
|
+
});
|
|
2952
|
+
let shuttingDown = false;
|
|
2953
|
+
const handler = () => {
|
|
2954
|
+
if (shuttingDown) return;
|
|
2955
|
+
shuttingDown = true;
|
|
2956
|
+
let timedOut = false;
|
|
2957
|
+
const timer = setTimeout(() => {
|
|
2958
|
+
timedOut = true;
|
|
2959
|
+
void Promise.resolve(options.onShutdown?.()).finally(() => {
|
|
2960
|
+
exit(1);
|
|
2961
|
+
});
|
|
2962
|
+
}, timeout);
|
|
2963
|
+
timer.unref();
|
|
2964
|
+
server.close(() => {
|
|
2965
|
+
if (timedOut) return;
|
|
2966
|
+
clearTimeout(timer);
|
|
2967
|
+
void Promise.resolve(options.onShutdown?.()).then(
|
|
2968
|
+
() => {
|
|
2969
|
+
exit(0);
|
|
2970
|
+
},
|
|
2971
|
+
() => {
|
|
2972
|
+
exit(1);
|
|
2973
|
+
}
|
|
2974
|
+
);
|
|
2975
|
+
});
|
|
2976
|
+
};
|
|
2977
|
+
for (const signal of signals) process.on(signal, handler);
|
|
2978
|
+
return () => {
|
|
2979
|
+
for (const signal of signals) process.off(signal, handler);
|
|
2980
|
+
};
|
|
2981
|
+
}
|
|
2982
|
+
|
|
2983
|
+
// src/presets.ts
|
|
2984
|
+
function securityHeaders(options = {}) {
|
|
2985
|
+
const frameOptions = options.frameOptions ?? "SAMEORIGIN";
|
|
2986
|
+
const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
|
|
2987
|
+
const noSniff = options.noSniff ?? true;
|
|
2988
|
+
const hstsValue = options.hsts === void 0 || options.hsts === false ? void 0 : `max-age=${String((options.hsts === true ? void 0 : options.hsts.maxAge) ?? 31536e3)}; includeSubDomains`;
|
|
2989
|
+
return async (req, next) => {
|
|
2990
|
+
const res = await next(req);
|
|
2991
|
+
const set = (name, value) => {
|
|
2992
|
+
res.headers[name] ??= value;
|
|
2993
|
+
};
|
|
2994
|
+
if (noSniff) set("X-Content-Type-Options", "nosniff");
|
|
2995
|
+
if (frameOptions !== false) set("X-Frame-Options", frameOptions);
|
|
2996
|
+
if (referrerPolicy !== false) set("Referrer-Policy", referrerPolicy);
|
|
2997
|
+
if (hstsValue !== void 0 && req.isSecure()) set("Strict-Transport-Security", hstsValue);
|
|
2998
|
+
return res;
|
|
2999
|
+
};
|
|
3000
|
+
}
|
|
3001
|
+
function resolveOrigin(option, origin) {
|
|
3002
|
+
const setting = option ?? "*";
|
|
3003
|
+
if (setting === "*") return "*";
|
|
3004
|
+
if (origin === void 0) return void 0;
|
|
3005
|
+
if (typeof setting === "function") return setting(origin) ? origin : void 0;
|
|
3006
|
+
if (typeof setting === "string") return setting === origin ? origin : void 0;
|
|
3007
|
+
return setting.includes(origin) ? origin : void 0;
|
|
3008
|
+
}
|
|
3009
|
+
function cors(options = {}) {
|
|
3010
|
+
const methods = (options.methods ?? ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"]).join(", ");
|
|
3011
|
+
const maxAge = String(options.maxAge ?? 86400);
|
|
3012
|
+
return async (req, next) => {
|
|
3013
|
+
const origin = req.header("origin");
|
|
3014
|
+
const allowOrigin = resolveOrigin(options.origin, origin);
|
|
3015
|
+
const headers = {};
|
|
3016
|
+
if (allowOrigin !== void 0) {
|
|
3017
|
+
headers["Access-Control-Allow-Origin"] = allowOrigin;
|
|
3018
|
+
if (allowOrigin !== "*") headers["Vary"] = "Origin";
|
|
3019
|
+
if (options.credentials === true) headers["Access-Control-Allow-Credentials"] = "true";
|
|
3020
|
+
if (options.exposedHeaders !== void 0 && options.exposedHeaders.length > 0) {
|
|
3021
|
+
headers["Access-Control-Expose-Headers"] = options.exposedHeaders.join(", ");
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
if (req.method() === "OPTIONS") {
|
|
3025
|
+
const allowHeaders = options.allowedHeaders === void 0 ? req.header("access-control-request-headers") : options.allowedHeaders.join(", ");
|
|
3026
|
+
return Response.make("", 204).withHeaders({
|
|
3027
|
+
...headers,
|
|
3028
|
+
"Access-Control-Allow-Methods": methods,
|
|
3029
|
+
"Access-Control-Max-Age": maxAge,
|
|
3030
|
+
...allowHeaders === void 0 ? {} : { "Access-Control-Allow-Headers": allowHeaders }
|
|
3031
|
+
});
|
|
3032
|
+
}
|
|
3033
|
+
const res = await next(req);
|
|
3034
|
+
return res.withHeaders(headers);
|
|
3035
|
+
};
|
|
3036
|
+
}
|
|
3037
|
+
function throttle(options) {
|
|
3038
|
+
const max = options.max ?? 60;
|
|
3039
|
+
const decaySeconds = options.decaySeconds ?? 60;
|
|
3040
|
+
const keyFor = options.key ?? ((req) => `${req.ip() ?? "unknown"}|${req.method()}|${req.path()}`);
|
|
3041
|
+
return async (req, next) => {
|
|
3042
|
+
const key = `mason-throttle:${keyFor(req)}`;
|
|
3043
|
+
if (options.limiter.tooManyAttempts(key, max)) {
|
|
3044
|
+
const retryAfter = options.limiter.availableIn(key);
|
|
3045
|
+
return Response.json({ message: "Too Many Attempts." }, 429).withHeaders({
|
|
3046
|
+
"Retry-After": String(retryAfter),
|
|
3047
|
+
"X-RateLimit-Limit": String(max),
|
|
3048
|
+
"X-RateLimit-Remaining": "0"
|
|
3049
|
+
});
|
|
3050
|
+
}
|
|
3051
|
+
options.limiter.hit(key, decaySeconds);
|
|
3052
|
+
return next(req);
|
|
3053
|
+
};
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
// src/index.ts
|
|
3057
|
+
var VERSION = "0.1.0";
|
|
3058
|
+
|
|
3059
|
+
export { Controller, EXCEPTION_HANDLER, ExceptionHandler, HttpException, HttpKernel, MethodNotAllowedHttpException, NotFoundHttpException, PayloadTooLargeHttpException, Request, ResourceRegistration, Response, Route, Router, SingletonRegistration, UploadedFile, VERSION, cors, createServer, gracefulShutdown, isTerminable, runMiddleware, securityHeaders, serve, terminateMiddleware, throttle };
|
|
3060
|
+
//# sourceMappingURL=index.js.map
|
|
3061
|
+
//# sourceMappingURL=index.js.map
|