@warlock.js/core 5.6.0 → 5.8.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/CHANGELOG.md +36 -0
- package/esm/benchmark/profiler.d.mts.map +1 -1
- package/esm/benchmark/profiler.mjs +4 -3
- package/esm/benchmark/profiler.mjs.map +1 -1
- package/esm/cli/cli-commands.manager.mjs +12 -9
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/index.mjs +2 -0
- package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/jwt-secret.check.mjs +55 -0
- package/esm/cli/commands/doctor/checks/jwt-secret.check.mjs.map +1 -0
- package/esm/cli/commands/generate/generators/controller.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/repository.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/resource.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/service.generator.mjs +4 -4
- package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/templates/stubs.mjs +6 -3
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/cli/commands/routes/format-routes-table.mjs +3 -3
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
- package/esm/cli/parse-cli-args.mjs +1 -0
- package/esm/cli/parse-cli-args.mjs.map +1 -1
- package/esm/cli/string-similarity.mjs +13 -4
- package/esm/cli/string-similarity.mjs.map +1 -1
- package/esm/commands/cli-command.d.mts.map +1 -1
- package/esm/commands/cli-command.mjs +5 -2
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/config/config-loader.mjs +3 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.d.mts.map +1 -1
- package/esm/dev-server/dependency-graph.mjs +2 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs +7 -5
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs +2 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs +22 -8
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/encryption/encrypt.mjs +1 -0
- package/esm/encryption/encrypt.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs +8 -2
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/shared/relocate-conflicting-home-route.mjs +6 -1
- package/esm/generations/features/shared/relocate-conflicting-home-route.mjs.map +1 -1
- package/esm/generations/stubs.mjs +6 -6
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/boot-port-preflight.d.mts +25 -1
- package/esm/http/boot-port-preflight.d.mts.map +1 -1
- package/esm/http/boot-port-preflight.mjs +51 -2
- package/esm/http/boot-port-preflight.mjs.map +1 -1
- package/esm/http/index.d.mts +1 -1
- package/esm/http/index.mjs +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs +1 -2
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
- package/esm/http/middleware/utils/cidr-match.mjs +1 -0
- package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +14 -7
- package/esm/http/request.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/esm/repositories/adapters/cascade/filter-applicator.mjs +4 -2
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.mjs +9 -3
- package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
- package/esm/router/route-registry.mjs +1 -1
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs +1 -0
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs +6 -2
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs +6 -1
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/utils/load-environment.mjs +4 -1
- package/esm/utils/load-environment.mjs.map +1 -1
- package/esm/utils/recorded-environment-overrides.mjs +41 -0
- package/esm/utils/recorded-environment-overrides.mjs.map +1 -0
- package/esm/utils/version-compare.d.mts.map +1 -1
- package/esm/utils/version-compare.mjs +12 -4
- package/esm/utils/version-compare.mjs.map +1 -1
- package/esm/vite/lower-stage3-decorators.mjs +1 -0
- package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
- package/package.json +12 -12
|
@@ -1,4 +1,18 @@
|
|
|
1
1
|
//#region ../core/src/http/boot-port-preflight.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Whether the HTTP-port preflight should run for a command's `connectors`
|
|
4
|
+
* preload.
|
|
5
|
+
*
|
|
6
|
+
* The bind-and-release probe is only meaningful when this boot will actually
|
|
7
|
+
* start the http connector: `true` (a full boot — http starts in its late
|
|
8
|
+
* phase) or an explicit list that names `"http"`. A scoped list WITHOUT http —
|
|
9
|
+
* e.g. `warlock seed`'s `["database", "cache", "logger"]`, or `migrate` — never
|
|
10
|
+
* binds the port, so probing it is pointless and actively harmful: the probe
|
|
11
|
+
* collides with a dev server already listening on that port (and inherits a
|
|
12
|
+
* stray `HTTP_PORT`), so a read-only data command fails on a port it was never
|
|
13
|
+
* going to use. Finding f9ace89e.
|
|
14
|
+
*/
|
|
15
|
+
declare function shouldPreflightHttpPort(connectors: readonly string[] | true): boolean;
|
|
2
16
|
/**
|
|
3
17
|
* Probe the port declared in `src/config/http.ts`, if there is one.
|
|
4
18
|
*
|
|
@@ -41,6 +55,16 @@ declare function assertConfiguredHttpPortIsFree(): Promise<void>;
|
|
|
41
55
|
* would otherwise have booted. `HttpConnector` still runs the real check.
|
|
42
56
|
*/
|
|
43
57
|
declare function preflightConfiguredHttpPort(): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* The remedy lines, chosen by where `http.port` actually came from.
|
|
60
|
+
*
|
|
61
|
+
* The provenance is the detector's own finding from env-load, carried here via
|
|
62
|
+
* {@link getRecordedEnvironmentOverride} rather than recomputed — so this asks
|
|
63
|
+
* "did an ambient HTTP_PORT beat .env, and is that the value now colliding?"
|
|
64
|
+
* and, only when the answer is yes, replaces the config-edit advice with the
|
|
65
|
+
* one that will actually free the port.
|
|
66
|
+
*/
|
|
67
|
+
declare function remedyLines(collidingPort: number): string[];
|
|
44
68
|
//#endregion
|
|
45
|
-
export { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort };
|
|
69
|
+
export { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort, remedyLines, shouldPreflightHttpPort };
|
|
46
70
|
//# sourceMappingURL=boot-port-preflight.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boot-port-preflight.d.mts","names":[],"sources":["../../../../../../../core/src/http/boot-port-preflight.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"boot-port-preflight.d.mts","names":[],"sources":["../../../../../../../core/src/http/boot-port-preflight.ts"],"mappings":";;AAyCA;;;;AAA4E;AAkB5E;;;;AAA+D;AA4D/D;;iBA9EgB,uBAAA,CAAwB,UAAoC;;AA8EhB;AAwD5D;;;;AAAiD;;;;;;;;iBApH3B,8BAAA,IAAkC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4DzC,2BAAA,IAA+B,OAAO;;;;;;;;;;iBAwD5C,WAAA,CAAY,aAAqB"}
|
|
@@ -1,9 +1,17 @@
|
|
|
1
|
+
import { getRecordedEnvironmentOverride } from "../utils/recorded-environment-overrides.mjs";
|
|
1
2
|
import { PortInUseError, assertPortIsAvailable } from "./port-preflight.mjs";
|
|
2
3
|
import { resolveBindPort } from "./resolve-bind-port.mjs";
|
|
3
4
|
import config from "@mongez/config";
|
|
4
5
|
|
|
5
6
|
//#region ../core/src/http/boot-port-preflight.ts
|
|
6
7
|
/**
|
|
8
|
+
* The env var whose value `src/config/http.ts` reads for `http.port`
|
|
9
|
+
* (`port: env("HTTP_PORT", …)`). When an ambient value for it beats `.env`,
|
|
10
|
+
* `http.port` resolves to the ambient value and editing the config literal
|
|
11
|
+
* changes nothing — the whole point of the provenance branch below.
|
|
12
|
+
*/
|
|
13
|
+
const HTTP_PORT_ENV_KEY = "HTTP_PORT";
|
|
14
|
+
/**
|
|
7
15
|
* Mirrors `dev-server/supervisor.ts`'s `BOOT_PRECONDITION_EXIT_CODE`. Kept as
|
|
8
16
|
* its own literal here (rather than imported) so this file — reached by both
|
|
9
17
|
* the dev-preload path and the generated, standalone production entry — never
|
|
@@ -17,6 +25,22 @@ const BOOT_PRECONDITION_EXIT_CODE = 78;
|
|
|
17
25
|
*/
|
|
18
26
|
const DEFAULT_BIND_HOST = "localhost";
|
|
19
27
|
/**
|
|
28
|
+
* Whether the HTTP-port preflight should run for a command's `connectors`
|
|
29
|
+
* preload.
|
|
30
|
+
*
|
|
31
|
+
* The bind-and-release probe is only meaningful when this boot will actually
|
|
32
|
+
* start the http connector: `true` (a full boot — http starts in its late
|
|
33
|
+
* phase) or an explicit list that names `"http"`. A scoped list WITHOUT http —
|
|
34
|
+
* e.g. `warlock seed`'s `["database", "cache", "logger"]`, or `migrate` — never
|
|
35
|
+
* binds the port, so probing it is pointless and actively harmful: the probe
|
|
36
|
+
* collides with a dev server already listening on that port (and inherits a
|
|
37
|
+
* stray `HTTP_PORT`), so a read-only data command fails on a port it was never
|
|
38
|
+
* going to use. Finding f9ace89e.
|
|
39
|
+
*/
|
|
40
|
+
function shouldPreflightHttpPort(connectors) {
|
|
41
|
+
return connectors === true || connectors.includes("http");
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
20
44
|
* Probe the port declared in `src/config/http.ts`, if there is one.
|
|
21
45
|
*
|
|
22
46
|
* Reads config rather than taking arguments because the only honest answer to
|
|
@@ -82,6 +106,13 @@ async function preflightConfiguredHttpPort() {
|
|
|
82
106
|
* grep for, the port and host by name, and the command that names the process
|
|
83
107
|
* holding it — the supervisor cannot discover the owning PID for them, but it
|
|
84
108
|
* can hand them the one line that will.
|
|
109
|
+
*
|
|
110
|
+
* The remedy is chosen by PROVENANCE, never appended as a menu. When the
|
|
111
|
+
* colliding port came from an ambient `HTTP_PORT` that beat `.env` (the exact
|
|
112
|
+
* two-rebuild trap of finding 8782b840), "edit src/config/http.ts and rebuild"
|
|
113
|
+
* is actively wrong — the env var wins, so the rebuild changes nothing. In that
|
|
114
|
+
* case name the variable and give the remedy that works (unset it); only when
|
|
115
|
+
* the port genuinely came from config do we point at the config file.
|
|
85
116
|
*/
|
|
86
117
|
function reportPortInUse(error) {
|
|
87
118
|
const ownerCommand = process.platform === "win32" ? `netstat -ano | findstr :${error.port}` : `lsof -i :${error.port}`;
|
|
@@ -90,12 +121,30 @@ function reportPortInUse(error) {
|
|
|
90
121
|
` ✖ EADDRINUSE: port ${error.port} is already in use on ${error.host}`,
|
|
91
122
|
` the application cannot start because something else is already listening there.`,
|
|
92
123
|
` find the owning process: ${ownerCommand}`,
|
|
93
|
-
|
|
124
|
+
...remedyLines(error.port),
|
|
94
125
|
""
|
|
95
126
|
];
|
|
96
127
|
for (const line of lines) console.error(line);
|
|
97
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* The remedy lines, chosen by where `http.port` actually came from.
|
|
131
|
+
*
|
|
132
|
+
* The provenance is the detector's own finding from env-load, carried here via
|
|
133
|
+
* {@link getRecordedEnvironmentOverride} rather than recomputed — so this asks
|
|
134
|
+
* "did an ambient HTTP_PORT beat .env, and is that the value now colliding?"
|
|
135
|
+
* and, only when the answer is yes, replaces the config-edit advice with the
|
|
136
|
+
* one that will actually free the port.
|
|
137
|
+
*/
|
|
138
|
+
function remedyLines(collidingPort) {
|
|
139
|
+
const httpPortOverride = getRecordedEnvironmentOverride(HTTP_PORT_ENV_KEY);
|
|
140
|
+
if (httpPortOverride !== void 0 && Number(String(httpPortOverride.effectiveValue).trim()) === collidingPort) return [
|
|
141
|
+
` this port came from the ${HTTP_PORT_ENV_KEY} environment variable (=${httpPortOverride.effectiveValue}), which overrode .env's ${HTTP_PORT_ENV_KEY}=${httpPortOverride.fileValue}.`,
|
|
142
|
+
` editing src/config/http.ts and rebuilding will NOT change it — the environment variable wins.`,
|
|
143
|
+
` then stop the process above, or unset ${HTTP_PORT_ENV_KEY} and run again.`
|
|
144
|
+
];
|
|
145
|
+
return [` then stop it, or change http.port in src/config/http.ts and rebuild.`];
|
|
146
|
+
}
|
|
98
147
|
|
|
99
148
|
//#endregion
|
|
100
|
-
export { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort };
|
|
149
|
+
export { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort, remedyLines, shouldPreflightHttpPort };
|
|
101
150
|
//# sourceMappingURL=boot-port-preflight.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boot-port-preflight.mjs","names":[],"sources":["../../../../../../../core/src/http/boot-port-preflight.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { assertPortIsAvailable, PortInUseError } from \"./port-preflight\";\nimport { resolveBindPort } from \"./resolve-bind-port\";\n\n/**\n * Mirrors `dev-server/supervisor.ts`'s `BOOT_PRECONDITION_EXIT_CODE`. Kept as\n * its own literal here (rather than imported) so this file — reached by both\n * the dev-preload path and the generated, standalone production entry — never\n * pulls dev-server's supervisor module (child_process, TTY handling, ...)\n * into a production bundle that has no supervisor at all. EX_CONFIG.\n */\nconst BOOT_PRECONDITION_EXIT_CODE = 78;\n\n/**\n * Host used when `http.host` is unset — the same default `HttpConnector`\n * binds with, so the probe tests the address the server will actually take.\n */\nconst DEFAULT_BIND_HOST = \"localhost\";\n\n/**\n * Probe the port declared in `src/config/http.ts`, if there is one.\n *\n * Reads config rather than taking arguments because the only honest answer to\n * \"which port will this boot bind\" lives in the loaded config, and the callers\n * that need this check (the generated production entry) run before anything\n * that could hand it over.\n *\n * A no-op for an app with no `http` config, or an `http.port` that is not a\n * usable port number — those apps never bind, so there is nothing to preflight\n * and nothing to fail on.\n *\n * @throws {PortInUseError} when the configured port is already taken.\n */\nexport async function assertConfiguredHttpPortIsFree(): Promise<void> {\n const httpConfig = config.get(\"http\");\n\n if (!httpConfig) {\n return;\n }\n\n // This runs BEFORE the connectors in the generated production entry, and\n // `preflightConfiguredHttpPort()` below only exits on `PortInUseError` —\n // any other throw is swallowed there. So a bad port must not throw HERE:\n // it stays a no-op, exactly like the previous hand-rolled coercion, and\n // `HttpConnector` (which now also calls `resolveBindPort`) is the one that\n // reports it, a moment later, with a channel a developer will actually see.\n let port: number;\n\n try {\n port = resolveBindPort(httpConfig.port);\n } catch {\n return;\n }\n\n // Port 0 asks the OS to pick a free one, so there is nothing to preflight:\n // probing 0 binds SOME unrelated ephemeral port and \"passes\" without proving\n // anything about the port this boot will end up on. The hand-rolled coercion\n // this replaced skipped 0 by rejecting `port <= 0`; `resolveBindPort` accepts\n // 0 as a legitimate TCP value, so the skip has to be stated here instead of\n // falling out of a range check.\n if (port === 0) {\n return;\n }\n\n await assertPortIsAvailable(port, httpConfig.host || DEFAULT_BIND_HOST);\n}\n\n/**\n * Fail the boot immediately, and by name, when the http port is already taken.\n *\n * Called from the generated production entry BEFORE the early-phase connectors,\n * because the port is the cheapest thing in the boot to check and the one most\n * likely to be wrong. `HttpConnector` is a LATE-phase connector, so its own\n * preflight is not reached until the database has connected, the cache has\n * connected and every module of app code has been imported — 7-13 seconds of\n * work, all of it discarded, before anyone learns the port was busy. This check\n * costs a bind-and-release on a socket that is never served.\n *\n * It does NOT replace `HttpConnector`'s preflight: a port can be taken in the\n * seconds between the two, and only the connector's check sits immediately\n * before the real `listen()`. This one exists to make the common case fast and\n * legible.\n *\n * Reports through `console.error` and NOT through `log.fatal`: the logger has\n * no channels yet at this point in the boot (the logger connector is part of\n * the early phase this runs ahead of), so a logged message here would reach\n * nobody. stderr always reaches the terminal, and `warlock start` forwards the\n * child's stderr verbatim.\n *\n * A probe that fails for any OTHER reason is deliberately swallowed: this is a\n * fast-fail convenience, and it must never be the thing that stops an app which\n * would otherwise have booted. `HttpConnector` still runs the real check.\n */\nexport async function preflightConfiguredHttpPort(): Promise<void> {\n try {\n await assertConfiguredHttpPortIsFree();\n } catch (error) {\n if (!(error instanceof PortInUseError)) {\n return;\n }\n\n reportPortInUse(error);\n\n process.exit(BOOT_PRECONDITION_EXIT_CODE);\n }\n}\n\n/**\n * Print the collision the way the developer needs to read it: the errno they\n * grep for, the port and host by name, and the command that names the process\n * holding it — the supervisor cannot discover the owning PID for them, but it\n * can hand them the one line that will.\n */\nfunction reportPortInUse(error: PortInUseError): void {\n const ownerCommand =\n process.platform === \"win32\"\n ? `netstat -ano | findstr :${error.port}`\n : `lsof -i :${error.port}`;\n\n const lines = [\n \"\",\n ` ✖ EADDRINUSE: port ${error.port} is already in use on ${error.host}`,\n ` the application cannot start because something else is already listening there.`,\n ` find the owning process: ${ownerCommand}`,\n
|
|
1
|
+
{"version":3,"file":"boot-port-preflight.mjs","names":[],"sources":["../../../../../../../core/src/http/boot-port-preflight.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { getRecordedEnvironmentOverride } from \"../utils/recorded-environment-overrides\";\nimport { assertPortIsAvailable, PortInUseError } from \"./port-preflight\";\nimport { resolveBindPort } from \"./resolve-bind-port\";\n\n/**\n * The env var whose value `src/config/http.ts` reads for `http.port`\n * (`port: env(\"HTTP_PORT\", …)`). When an ambient value for it beats `.env`,\n * `http.port` resolves to the ambient value and editing the config literal\n * changes nothing — the whole point of the provenance branch below.\n */\nconst HTTP_PORT_ENV_KEY = \"HTTP_PORT\";\n\n/**\n * Mirrors `dev-server/supervisor.ts`'s `BOOT_PRECONDITION_EXIT_CODE`. Kept as\n * its own literal here (rather than imported) so this file — reached by both\n * the dev-preload path and the generated, standalone production entry — never\n * pulls dev-server's supervisor module (child_process, TTY handling, ...)\n * into a production bundle that has no supervisor at all. EX_CONFIG.\n */\nconst BOOT_PRECONDITION_EXIT_CODE = 78;\n\n/**\n * Host used when `http.host` is unset — the same default `HttpConnector`\n * binds with, so the probe tests the address the server will actually take.\n */\nconst DEFAULT_BIND_HOST = \"localhost\";\n\n/**\n * Whether the HTTP-port preflight should run for a command's `connectors`\n * preload.\n *\n * The bind-and-release probe is only meaningful when this boot will actually\n * start the http connector: `true` (a full boot — http starts in its late\n * phase) or an explicit list that names `\"http\"`. A scoped list WITHOUT http —\n * e.g. `warlock seed`'s `[\"database\", \"cache\", \"logger\"]`, or `migrate` — never\n * binds the port, so probing it is pointless and actively harmful: the probe\n * collides with a dev server already listening on that port (and inherits a\n * stray `HTTP_PORT`), so a read-only data command fails on a port it was never\n * going to use. Finding f9ace89e.\n */\nexport function shouldPreflightHttpPort(connectors: readonly string[] | true): boolean {\n return connectors === true || connectors.includes(\"http\");\n}\n\n/**\n * Probe the port declared in `src/config/http.ts`, if there is one.\n *\n * Reads config rather than taking arguments because the only honest answer to\n * \"which port will this boot bind\" lives in the loaded config, and the callers\n * that need this check (the generated production entry) run before anything\n * that could hand it over.\n *\n * A no-op for an app with no `http` config, or an `http.port` that is not a\n * usable port number — those apps never bind, so there is nothing to preflight\n * and nothing to fail on.\n *\n * @throws {PortInUseError} when the configured port is already taken.\n */\nexport async function assertConfiguredHttpPortIsFree(): Promise<void> {\n const httpConfig = config.get(\"http\");\n\n if (!httpConfig) {\n return;\n }\n\n // This runs BEFORE the connectors in the generated production entry, and\n // `preflightConfiguredHttpPort()` below only exits on `PortInUseError` —\n // any other throw is swallowed there. So a bad port must not throw HERE:\n // it stays a no-op, exactly like the previous hand-rolled coercion, and\n // `HttpConnector` (which now also calls `resolveBindPort`) is the one that\n // reports it, a moment later, with a channel a developer will actually see.\n let port: number;\n\n try {\n port = resolveBindPort(httpConfig.port);\n } catch {\n return;\n }\n\n // Port 0 asks the OS to pick a free one, so there is nothing to preflight:\n // probing 0 binds SOME unrelated ephemeral port and \"passes\" without proving\n // anything about the port this boot will end up on. The hand-rolled coercion\n // this replaced skipped 0 by rejecting `port <= 0`; `resolveBindPort` accepts\n // 0 as a legitimate TCP value, so the skip has to be stated here instead of\n // falling out of a range check.\n if (port === 0) {\n return;\n }\n\n await assertPortIsAvailable(port, httpConfig.host || DEFAULT_BIND_HOST);\n}\n\n/**\n * Fail the boot immediately, and by name, when the http port is already taken.\n *\n * Called from the generated production entry BEFORE the early-phase connectors,\n * because the port is the cheapest thing in the boot to check and the one most\n * likely to be wrong. `HttpConnector` is a LATE-phase connector, so its own\n * preflight is not reached until the database has connected, the cache has\n * connected and every module of app code has been imported — 7-13 seconds of\n * work, all of it discarded, before anyone learns the port was busy. This check\n * costs a bind-and-release on a socket that is never served.\n *\n * It does NOT replace `HttpConnector`'s preflight: a port can be taken in the\n * seconds between the two, and only the connector's check sits immediately\n * before the real `listen()`. This one exists to make the common case fast and\n * legible.\n *\n * Reports through `console.error` and NOT through `log.fatal`: the logger has\n * no channels yet at this point in the boot (the logger connector is part of\n * the early phase this runs ahead of), so a logged message here would reach\n * nobody. stderr always reaches the terminal, and `warlock start` forwards the\n * child's stderr verbatim.\n *\n * A probe that fails for any OTHER reason is deliberately swallowed: this is a\n * fast-fail convenience, and it must never be the thing that stops an app which\n * would otherwise have booted. `HttpConnector` still runs the real check.\n */\nexport async function preflightConfiguredHttpPort(): Promise<void> {\n try {\n await assertConfiguredHttpPortIsFree();\n } catch (error) {\n if (!(error instanceof PortInUseError)) {\n return;\n }\n\n reportPortInUse(error);\n\n process.exit(BOOT_PRECONDITION_EXIT_CODE);\n }\n}\n\n/**\n * Print the collision the way the developer needs to read it: the errno they\n * grep for, the port and host by name, and the command that names the process\n * holding it — the supervisor cannot discover the owning PID for them, but it\n * can hand them the one line that will.\n *\n * The remedy is chosen by PROVENANCE, never appended as a menu. When the\n * colliding port came from an ambient `HTTP_PORT` that beat `.env` (the exact\n * two-rebuild trap of finding 8782b840), \"edit src/config/http.ts and rebuild\"\n * is actively wrong — the env var wins, so the rebuild changes nothing. In that\n * case name the variable and give the remedy that works (unset it); only when\n * the port genuinely came from config do we point at the config file.\n */\nfunction reportPortInUse(error: PortInUseError): void {\n const ownerCommand =\n process.platform === \"win32\"\n ? `netstat -ano | findstr :${error.port}`\n : `lsof -i :${error.port}`;\n\n const lines = [\n \"\",\n ` ✖ EADDRINUSE: port ${error.port} is already in use on ${error.host}`,\n ` the application cannot start because something else is already listening there.`,\n ` find the owning process: ${ownerCommand}`,\n ...remedyLines(error.port),\n \"\",\n ];\n\n for (const line of lines) {\n console.error(line);\n }\n}\n\n/**\n * The remedy lines, chosen by where `http.port` actually came from.\n *\n * The provenance is the detector's own finding from env-load, carried here via\n * {@link getRecordedEnvironmentOverride} rather than recomputed — so this asks\n * \"did an ambient HTTP_PORT beat .env, and is that the value now colliding?\"\n * and, only when the answer is yes, replaces the config-edit advice with the\n * one that will actually free the port.\n */\nexport function remedyLines(collidingPort: number): string[] {\n const httpPortOverride = getRecordedEnvironmentOverride(HTTP_PORT_ENV_KEY);\n\n // Only claim the environment is the source when the ambient value is the one\n // that is actually colliding — an HTTP_PORT override of an UNRELATED port\n // must not misdirect the reader away from their real (config) port.\n const cameFromEnvironment =\n httpPortOverride !== undefined &&\n Number(String(httpPortOverride.effectiveValue).trim()) === collidingPort;\n\n if (cameFromEnvironment) {\n return [\n ` this port came from the ${HTTP_PORT_ENV_KEY} environment variable (=${httpPortOverride!.effectiveValue}), which overrode .env's ${HTTP_PORT_ENV_KEY}=${httpPortOverride!.fileValue}.`,\n ` editing src/config/http.ts and rebuilding will NOT change it — the environment variable wins.`,\n ` then stop the process above, or unset ${HTTP_PORT_ENV_KEY} and run again.`,\n ];\n }\n\n return [` then stop it, or change http.port in src/config/http.ts and rebuild.`];\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,oBAAoB;;;;;;;;AAS1B,MAAM,8BAA8B;;;;;AAMpC,MAAM,oBAAoB;;;;;;;;;;;;;;AAe1B,SAAgB,wBAAwB,YAA+C;CACrF,OAAO,eAAe,QAAQ,WAAW,SAAS,MAAM;AAC1D;;;;;;;;;;;;;;;AAgBA,eAAsB,iCAAgD;CACpE,MAAM,aAAa,OAAO,IAAI,MAAM;CAEpC,IAAI,CAAC,YACH;CASF,IAAI;CAEJ,IAAI;EACF,OAAO,gBAAgB,WAAW,IAAI;CACxC,QAAQ;EACN;CACF;CAQA,IAAI,SAAS,GACX;CAGF,MAAM,sBAAsB,MAAM,WAAW,QAAQ,iBAAiB;AACxE;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,8BAA6C;CACjE,IAAI;EACF,MAAM,+BAA+B;CACvC,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,iBACrB;EAGF,gBAAgB,KAAK;EAErB,QAAQ,KAAK,2BAA2B;CAC1C;AACF;;;;;;;;;;;;;;AAeA,SAAS,gBAAgB,OAA6B;CACpD,MAAM,eACJ,QAAQ,aAAa,UACjB,2BAA2B,MAAM,SACjC,YAAY,MAAM;CAExB,MAAM,QAAQ;EACZ;EACA,wBAAwB,MAAM,KAAK,wBAAwB,MAAM;EACjE;EACA,8BAA8B;EAC9B,GAAG,YAAY,MAAM,IAAI;EACzB;CACF;CAEA,KAAK,MAAM,QAAQ,OACjB,QAAQ,MAAM,IAAI;AAEtB;;;;;;;;;;AAWA,SAAgB,YAAY,eAAiC;CAC3D,MAAM,mBAAmB,+BAA+B,iBAAiB;CASzE,IAHE,qBAAqB,UACrB,OAAO,OAAO,iBAAiB,cAAc,CAAC,CAAC,KAAK,CAAC,MAAM,eAG3D,OAAO;EACL,6BAA6B,kBAAkB,0BAA0B,iBAAkB,eAAe,2BAA2B,kBAAkB,GAAG,iBAAkB,UAAU;EACtL;EACA,2CAA2C,kBAAkB;CAC/D;CAGF,OAAO,CAAC,wEAAwE;AAClF"}
|
package/esm/http/index.d.mts
CHANGED
|
@@ -25,7 +25,7 @@ import { buildIdempotencyCacheKey, hashBody, isValidIdempotencyKey } from "./mid
|
|
|
25
25
|
import { parseSize } from "./middleware/utils/parse-size.mjs";
|
|
26
26
|
import { ClosableServer, FastifyInstance, closeServerWithTimeout, getHttpServer, startHttpServer } from "./server.mjs";
|
|
27
27
|
import { registerHttpPlugins } from "./plugins.mjs";
|
|
28
|
-
import { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort } from "./boot-port-preflight.mjs";
|
|
28
|
+
import { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort, remedyLines, shouldPreflightHttpPort } from "./boot-port-preflight.mjs";
|
|
29
29
|
import { PortInUseError, assertPortIsAvailable, isPortAvailable } from "./port-preflight.mjs";
|
|
30
30
|
import { HttpReadyReport, getHttpReadyReport, resetHttpReadyReport, setHttpReadyReport } from "./ready-report.mjs";
|
|
31
31
|
import { RequestContextStore, requestContext, useCurrentUser, useRequest, useRequestStore } from "./context/request-context.mjs";
|
package/esm/http/index.mjs
CHANGED
|
@@ -20,7 +20,7 @@ import { parseSize } from "./middleware/utils/parse-size.mjs";
|
|
|
20
20
|
import { middleware } from "./middleware/middleware-list.mjs";
|
|
21
21
|
import "./middleware/index.mjs";
|
|
22
22
|
import { PortInUseError, assertPortIsAvailable, isPortAvailable } from "./port-preflight.mjs";
|
|
23
|
-
import { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort } from "./boot-port-preflight.mjs";
|
|
23
|
+
import { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort, remedyLines, shouldPreflightHttpPort } from "./boot-port-preflight.mjs";
|
|
24
24
|
import { getHttpReadyReport, resetHttpReadyReport, setHttpReadyReport } from "./ready-report.mjs";
|
|
25
25
|
import { requestMemo } from "./context/request-memo.mjs";
|
|
26
26
|
|
|
@@ -33,8 +33,7 @@ function maintenanceMiddleware(options = {}) {
|
|
|
33
33
|
return ({ request, response }) => {
|
|
34
34
|
if (!config.get("http.maintenance.enabled", false)) return;
|
|
35
35
|
const allowlist = options.allowlist || config.get("http.maintenance.allowlist", ["/health"]);
|
|
36
|
-
|
|
37
|
-
if (isAllowlisted(pathname, allowlist)) return;
|
|
36
|
+
if (isAllowlisted(request.path.split("?")[0] ?? "/", allowlist)) return;
|
|
38
37
|
const retryAfter = options.retryAfter || config.get("http.maintenance.retryAfter", 60);
|
|
39
38
|
response.header("Retry-After", retryAfter);
|
|
40
39
|
return response.serviceUnavailable({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"maintenance.middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/maintenance.middleware.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport type { Middleware } from \"../../router\";\nimport { HttpErrorCodes } from \"../error-codes\";\nimport { t } from \"./inject-request-context\";\n\n/**\n * Options for the maintenance middleware.\n */\nexport type MaintenanceOptions = {\n /**\n * Path prefixes (ending in `*`) or exact paths to bypass even when\n * maintenance is on. Falls back to `http.maintenance.allowlist`, then\n * `[\"/health\"]`.\n *\n * @example\n * allowlist: [\"/health\", \"/admin/*\", \"/webhooks/stripe\"]\n */\n allowlist?: string[];\n /**\n * Seconds advertised in the `Retry-After` header. Falls back to\n * `http.maintenance.retryAfter`, then `60`.\n */\n retryAfter?: number;\n /**\n * Override the default error message.\n */\n errorMessage?: string;\n};\n\nfunction isAllowlisted(path: string, patterns: string[]) {\n return patterns.some((pattern) => {\n if (pattern.endsWith(\"*\")) {\n return path.startsWith(pattern.slice(0, -1));\n }\n\n return path === pattern;\n });\n}\n\n/**\n * Return 503 + `Retry-After` for every request when `http.maintenance.enabled`\n * is true, except for paths matching the allowlist.\n *\n * Designed for app-wide registration via `http.middleware.all`. Toggled via\n * config — flipping the flag requires a restart (no runtime hot-flip yet).\n * Allowlist defaults to `[\"/health\"]` so health checks still pass during\n * planned downtime.\n *\n * @example\n * // src/config/http.ts\n * import { middleware } from \"@warlock.js/core\";\n *\n * export default {\n * maintenance: { enabled: env(\"MAINTENANCE_MODE\") === \"true\" },\n * middleware: {\n * all: [middleware.maintenance({ allowlist: [\"/health\", \"/admin/*\"] })],\n * },\n * };\n */\nexport function maintenanceMiddleware(options: MaintenanceOptions = {}): Middleware {\n return ({ request, response }) => {\n const enabled = config.get(\"http.maintenance.enabled\", false);\n\n if (!enabled) return;\n\n const allowlist = options.allowlist || config.get(\"http.maintenance.allowlist\", [\"/health\"]);\n\n // `request.path` includes the query string, but allowlist entries are\n // path-only (\"/webhooks/stripe\"), so strip the query before matching —\n // otherwise \"/webhooks/stripe?sig=...\" never matches its exact entry.\n const pathname = request.path.split(\"?\")[0];\n\n if (isAllowlisted(pathname, allowlist)) return;\n\n const retryAfter = options.retryAfter || config.get(\"http.maintenance.retryAfter\", 60);\n\n response.header(\"Retry-After\", retryAfter);\n\n return response.serviceUnavailable({\n error: options.errorMessage || t(\"http.maintenance\"),\n errorCode: HttpErrorCodes.Maintenance,\n });\n };\n}\n"],"mappings":";;;;;AA6BA,SAAS,cAAc,MAAc,UAAoB;CACvD,OAAO,SAAS,MAAM,YAAY;EAChC,IAAI,QAAQ,SAAS,GAAG,GACtB,OAAO,KAAK,WAAW,QAAQ,MAAM,GAAG,EAAE,CAAC;EAG7C,OAAO,SAAS;CAClB,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,sBAAsB,UAA8B,CAAC,GAAe;CAClF,QAAQ,EAAE,SAAS,eAAe;EAGhC,IAAI,CAFY,OAAO,IAAI,4BAA4B,KAE5C,GAAG;EAEd,MAAM,YAAY,QAAQ,aAAa,OAAO,IAAI,8BAA8B,CAAC,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"maintenance.middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/maintenance.middleware.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport type { Middleware } from \"../../router\";\nimport { HttpErrorCodes } from \"../error-codes\";\nimport { t } from \"./inject-request-context\";\n\n/**\n * Options for the maintenance middleware.\n */\nexport type MaintenanceOptions = {\n /**\n * Path prefixes (ending in `*`) or exact paths to bypass even when\n * maintenance is on. Falls back to `http.maintenance.allowlist`, then\n * `[\"/health\"]`.\n *\n * @example\n * allowlist: [\"/health\", \"/admin/*\", \"/webhooks/stripe\"]\n */\n allowlist?: string[];\n /**\n * Seconds advertised in the `Retry-After` header. Falls back to\n * `http.maintenance.retryAfter`, then `60`.\n */\n retryAfter?: number;\n /**\n * Override the default error message.\n */\n errorMessage?: string;\n};\n\nfunction isAllowlisted(path: string, patterns: string[]) {\n return patterns.some((pattern) => {\n if (pattern.endsWith(\"*\")) {\n return path.startsWith(pattern.slice(0, -1));\n }\n\n return path === pattern;\n });\n}\n\n/**\n * Return 503 + `Retry-After` for every request when `http.maintenance.enabled`\n * is true, except for paths matching the allowlist.\n *\n * Designed for app-wide registration via `http.middleware.all`. Toggled via\n * config — flipping the flag requires a restart (no runtime hot-flip yet).\n * Allowlist defaults to `[\"/health\"]` so health checks still pass during\n * planned downtime.\n *\n * @example\n * // src/config/http.ts\n * import { middleware } from \"@warlock.js/core\";\n *\n * export default {\n * maintenance: { enabled: env(\"MAINTENANCE_MODE\") === \"true\" },\n * middleware: {\n * all: [middleware.maintenance({ allowlist: [\"/health\", \"/admin/*\"] })],\n * },\n * };\n */\nexport function maintenanceMiddleware(options: MaintenanceOptions = {}): Middleware {\n return ({ request, response }) => {\n const enabled = config.get(\"http.maintenance.enabled\", false);\n\n if (!enabled) return;\n\n const allowlist = options.allowlist || config.get(\"http.maintenance.allowlist\", [\"/health\"]);\n\n // `request.path` includes the query string, but allowlist entries are\n // path-only (\"/webhooks/stripe\"), so strip the query before matching —\n // otherwise \"/webhooks/stripe?sig=...\" never matches its exact entry.\n const pathname = request.path.split(\"?\")[0] ?? \"/\";\n\n if (isAllowlisted(pathname, allowlist)) return;\n\n const retryAfter = options.retryAfter || config.get(\"http.maintenance.retryAfter\", 60);\n\n response.header(\"Retry-After\", retryAfter);\n\n return response.serviceUnavailable({\n error: options.errorMessage || t(\"http.maintenance\"),\n errorCode: HttpErrorCodes.Maintenance,\n });\n };\n}\n"],"mappings":";;;;;AA6BA,SAAS,cAAc,MAAc,UAAoB;CACvD,OAAO,SAAS,MAAM,YAAY;EAChC,IAAI,QAAQ,SAAS,GAAG,GACtB,OAAO,KAAK,WAAW,QAAQ,MAAM,GAAG,EAAE,CAAC;EAG7C,OAAO,SAAS;CAClB,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,sBAAsB,UAA8B,CAAC,GAAe;CAClF,QAAQ,EAAE,SAAS,eAAe;EAGhC,IAAI,CAFY,OAAO,IAAI,4BAA4B,KAE5C,GAAG;EAEd,MAAM,YAAY,QAAQ,aAAa,OAAO,IAAI,8BAA8B,CAAC,SAAS,CAAC;EAO3F,IAAI,cAFa,QAAQ,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,KAEnB,SAAS,GAAG;EAExC,MAAM,aAAa,QAAQ,cAAc,OAAO,IAAI,+BAA+B,EAAE;EAErF,SAAS,OAAO,eAAe,UAAU;EAEzC,OAAO,SAAS,mBAAmB;GACjC,OAAO,QAAQ,gBAAgB,EAAE,kBAAkB;GACnD;EACF,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cidr-match.d.mts","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"mappings":";iBAkCgB,SAAA,CAAU,EAAA,UAAY,OAAe;AAArD;;;;AAAqD;
|
|
1
|
+
{"version":3,"file":"cidr-match.d.mts","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"mappings":";iBAkCgB,SAAA,CAAU,EAAA,UAAY,OAAe;AAArD;;;;AAAqD;AA+CrD;AA/CA,iBA+CgB,QAAA,CAAS,EAAA,UAAY,QAAkB"}
|
|
@@ -27,6 +27,7 @@ function ipMatches(ip, pattern) {
|
|
|
27
27
|
if (pattern === ip) return true;
|
|
28
28
|
if (!pattern.includes("/")) return false;
|
|
29
29
|
const [base, bitsRaw] = pattern.split("/");
|
|
30
|
+
if (base === void 0 || bitsRaw === void 0) return false;
|
|
30
31
|
const bits = Number(bitsRaw);
|
|
31
32
|
if (!Number.isInteger(bits) || bits < 0 || bits > 32) return false;
|
|
32
33
|
const ipInt = ipv4ToInt(ip);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cidr-match.mjs","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"sourcesContent":["/**\n * Match an IPv4 address against an exact IP or a CIDR block.\n *\n * IPv6 patterns are matched as exact-string only — full IPv6 CIDR support is\n * out of scope; ACLs in production almost always use IPv4 ranges. Add IPv6 CIDR\n * later if a real use-case appears.\n *\n * @example\n * ipMatches(\"10.0.0.5\", \"10.0.0.0/8\"); // true\n * ipMatches(\"10.0.0.5\", \"10.0.0.5\"); // true\n * ipMatches(\"192.168.1.1\", \"10.0.0.0/8\"); // false\n */\nfunction ipv4ToInt(ip: string): number | null {\n const parts = ip.split(\".\");\n\n if (parts.length !== 4) {\n return null;\n }\n\n let result = 0;\n\n for (const part of parts) {\n const num = Number(part);\n\n if (!Number.isInteger(num) || num < 0 || num > 255) {\n return null;\n }\n\n result = (result << 8) + num;\n }\n\n return result >>> 0;\n}\n\nexport function ipMatches(ip: string, pattern: string): boolean {\n if (!ip || !pattern) {\n return false;\n }\n\n if (pattern === ip) {\n return true;\n }\n\n if (!pattern.includes(\"/\")) {\n return false;\n }\n\n const [base, bitsRaw] = pattern.split(\"/\");\n const bits = Number(bitsRaw);\n\n if (!Number.isInteger(bits) || bits < 0 || bits > 32) {\n return false;\n }\n\n const ipInt = ipv4ToInt(ip);\n const baseInt = ipv4ToInt(base);\n\n if (ipInt === null || baseInt === null) {\n return false;\n }\n\n if (bits === 0) {\n return true;\n }\n\n const mask = (~0 << (32 - bits)) >>> 0;\n\n return (ipInt & mask) === (baseInt & mask);\n}\n\n/**\n * Returns true if `ip` matches any pattern in the list.\n *\n * @example\n * anyMatch(\"10.0.0.5\", [\"192.168.0.0/16\", \"10.0.0.0/8\"]); // true\n */\nexport function anyMatch(ip: string, patterns: string[]): boolean {\n return patterns.some((pattern) => ipMatches(ip, pattern));\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAS,UAAU,IAA2B;CAC5C,MAAM,QAAQ,GAAG,MAAM,GAAG;CAE1B,IAAI,MAAM,WAAW,GACnB,OAAO;CAGT,IAAI,SAAS;CAEb,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,MAAM,OAAO,IAAI;EAEvB,IAAI,CAAC,OAAO,UAAU,GAAG,KAAK,MAAM,KAAK,MAAM,KAC7C,OAAO;EAGT,UAAU,UAAU,KAAK;CAC3B;CAEA,OAAO,WAAW;AACpB;AAEA,SAAgB,UAAU,IAAY,SAA0B;CAC9D,IAAI,CAAC,MAAM,CAAC,SACV,OAAO;CAGT,IAAI,YAAY,IACd,OAAO;CAGT,IAAI,CAAC,QAAQ,SAAS,GAAG,GACvB,OAAO;CAGT,MAAM,CAAC,MAAM,WAAW,QAAQ,MAAM,GAAG;
|
|
1
|
+
{"version":3,"file":"cidr-match.mjs","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"sourcesContent":["/**\n * Match an IPv4 address against an exact IP or a CIDR block.\n *\n * IPv6 patterns are matched as exact-string only — full IPv6 CIDR support is\n * out of scope; ACLs in production almost always use IPv4 ranges. Add IPv6 CIDR\n * later if a real use-case appears.\n *\n * @example\n * ipMatches(\"10.0.0.5\", \"10.0.0.0/8\"); // true\n * ipMatches(\"10.0.0.5\", \"10.0.0.5\"); // true\n * ipMatches(\"192.168.1.1\", \"10.0.0.0/8\"); // false\n */\nfunction ipv4ToInt(ip: string): number | null {\n const parts = ip.split(\".\");\n\n if (parts.length !== 4) {\n return null;\n }\n\n let result = 0;\n\n for (const part of parts) {\n const num = Number(part);\n\n if (!Number.isInteger(num) || num < 0 || num > 255) {\n return null;\n }\n\n result = (result << 8) + num;\n }\n\n return result >>> 0;\n}\n\nexport function ipMatches(ip: string, pattern: string): boolean {\n if (!ip || !pattern) {\n return false;\n }\n\n if (pattern === ip) {\n return true;\n }\n\n if (!pattern.includes(\"/\")) {\n return false;\n }\n\n const [base, bitsRaw] = pattern.split(\"/\");\n\n if (base === undefined || bitsRaw === undefined) {\n return false;\n }\n\n const bits = Number(bitsRaw);\n\n if (!Number.isInteger(bits) || bits < 0 || bits > 32) {\n return false;\n }\n\n const ipInt = ipv4ToInt(ip);\n const baseInt = ipv4ToInt(base);\n\n if (ipInt === null || baseInt === null) {\n return false;\n }\n\n if (bits === 0) {\n return true;\n }\n\n const mask = (~0 << (32 - bits)) >>> 0;\n\n return (ipInt & mask) === (baseInt & mask);\n}\n\n/**\n * Returns true if `ip` matches any pattern in the list.\n *\n * @example\n * anyMatch(\"10.0.0.5\", [\"192.168.0.0/16\", \"10.0.0.0/8\"]); // true\n */\nexport function anyMatch(ip: string, patterns: string[]): boolean {\n return patterns.some((pattern) => ipMatches(ip, pattern));\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAS,UAAU,IAA2B;CAC5C,MAAM,QAAQ,GAAG,MAAM,GAAG;CAE1B,IAAI,MAAM,WAAW,GACnB,OAAO;CAGT,IAAI,SAAS;CAEb,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,MAAM,OAAO,IAAI;EAEvB,IAAI,CAAC,OAAO,UAAU,GAAG,KAAK,MAAM,KAAK,MAAM,KAC7C,OAAO;EAGT,UAAU,UAAU,KAAK;CAC3B;CAEA,OAAO,WAAW;AACpB;AAEA,SAAgB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7B,GAAA,CAAI,GAAA,UAAa,YAAA;;;;EAOjB,GAAA,CAAI,GAAA;;;;EAOJ,GAAA,CAAI,GAAA,UAAa,KAAA;;;;EASjB,UAAA,CAAW,GAAA,UAAa,KAAA;;;;EAWxB,KAAA,IAAS,IAAA;;;;MASL,IAAA;;;;EAOJ,OAAA,CAAQ,GAAA,UAAa,KAAA;;;;MASjB,UAAA;;;;EAmBJ,IAAA,CAAK,GAAA,WAAc,YAAA;;;;;EAUnB,KAAA,CAAM,IAAA,WAAe,YAAA;;;;MAOjB,MAAA;;;;EAOJ,QAAA,CAAS,GAAA,UAAa,KAAA;;;;MASlB,KAAA;;;;EAOJ,QAAA,CAAS,GAAA,UAAa,KAAA;;;;EAStB,GAAA;;;;EAOA,eAAA;;;;EAUA,iBAAA;;;;EAmBA,KAAA;;;;EAmBA,IAAA,CAAK,IAAA;;;;EAOL,KAAA,CAAM,IAAA;;;;EAWN,MAAA,CAAO,IAAA;;;;EAOP,IAAA,CAAK,GAAA,UAAa,YAAA;;;;EAqBlB,GAAA,CAAI,GAAA,UAAa,YAAA;;;;MAWb,OAAA;;;;EAOJ,MAAA,CAAO,GAAA,UAAa,YAAA;;;;EASpB,KAAA,CAAM,GAAA,UAAa,YAAA;;;;EASnB,MAAA,CAAO,GAAA,UAAa,YAAA;;;;;;;;;;MAehB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqCJ,QAAA;;;;MAoCI,MAAA;;;;MAOA,GAAA;;;;MAOA,OAAA;;;;MAOA,SAAA;;;;MAOA,OAAA,gBAAuB,WAAA,CAAY,OAAA;;;;EAOvC,SAAA,CAAU,GAAA,EAAK,UAAA,EAAY,KAAA;AAAA"}
|
package/esm/http/request.mjs
CHANGED
|
@@ -364,21 +364,28 @@ var Request = class Request {
|
|
|
364
364
|
if (key.includes("][")) {
|
|
365
365
|
const keyParts = key.split("[");
|
|
366
366
|
const keyName = keyParts[0];
|
|
367
|
-
const
|
|
367
|
+
const firstBracket = keyParts[1];
|
|
368
|
+
const secondBracket = keyParts[2];
|
|
369
|
+
if (keyName === void 0 || firstBracket === void 0 || secondBracket === void 0) {
|
|
370
|
+
set(body, this.bracketKeyToPath(key), this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)));
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
const keyNameParts = firstBracket.split("]");
|
|
368
374
|
const index = Number(keyNameParts[0]);
|
|
369
375
|
if (Number.isNaN(index)) {
|
|
370
376
|
set(body, this.bracketKeyToPath(key), this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)));
|
|
371
377
|
continue;
|
|
372
378
|
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
const keyName2 =
|
|
376
|
-
|
|
379
|
+
const bucket = arrayOfObjectValues[keyName] ??= [];
|
|
380
|
+
const entry = bucket[index] ??= {};
|
|
381
|
+
const keyName2 = secondBracket.split("]")[0];
|
|
382
|
+
if (keyName2 === void 0) continue;
|
|
383
|
+
entry[keyName2] = this.parseValue(value);
|
|
377
384
|
continue;
|
|
378
385
|
}
|
|
379
386
|
const keyParts = key.split("[");
|
|
380
387
|
const keyName = keyParts[0];
|
|
381
|
-
const keyNameParts = keyParts[1].split("]");
|
|
388
|
+
const keyNameParts = (keyParts[1] ?? key).split("]");
|
|
382
389
|
set(body, keyName + "." + keyNameParts[0], this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)));
|
|
383
390
|
continue;
|
|
384
391
|
}
|
|
@@ -827,7 +834,7 @@ var Request = class Request {
|
|
|
827
834
|
if (config.get("http.trustProxy", false) === true) {
|
|
828
835
|
const realIp = this.header("x-real-ip");
|
|
829
836
|
if (realIp) {
|
|
830
|
-
const address = String(realIp).split(",")[0].trim();
|
|
837
|
+
const address = (String(realIp).split(",")[0] ?? "").trim();
|
|
831
838
|
if (address) return address;
|
|
832
839
|
}
|
|
833
840
|
}
|
package/esm/http/request.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.mjs","names":[],"sources":["../../../../../../../core/src/http/request.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport events from \"@mongez/events\";\nimport { trans, transFrom } from \"@mongez/localization\";\nimport { Random, except, get, only, rtrim, set, unset } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport type { LogLevel } from \"@warlock.js/logger\";\nimport { log } from \"@warlock.js/logger\";\nimport { BaseValidator, v } from \"@warlock.js/seal\";\nimport type { FastifyRequest } from \"fastify\";\nimport { randomBytes } from \"node:crypto\";\nimport { type IncomingHttpHeaders } from \"node:http2\";\nimport { config } from \"../config/config-getter\";\nimport { LOCALE_COOKIE_NAME, resolveLocaleConfiguration } from \"../config/locale-configuration\";\nimport type { Middleware, Route } from \"../router\";\nimport { validateAll } from \"../validation/validateAll\";\nimport { createRequestStore } from \"./middleware/inject-request-context\";\nimport { Response } from \"./response\";\nimport type { DecodedAccessToken, RequestEvent, RequestLocals, RequestUser } from \"./types\";\nimport { UploadedFile } from \"./uploaded-file\";\n\ntype StandardHeaders = {\n // copy every declared property from http.IncomingHttpHeaders\n // but remove index signatures\n [\n K in keyof IncomingHttpHeaders as string extends K ? never : number extends K ? never : K\n ]: IncomingHttpHeaders[K];\n};\n\ntype HeaderKeys = keyof StandardHeaders;\n\nexport class Request<RequestValidation = any> {\n /**\n * Underlying Fastify request — a public escape hatch to capabilities the\n * framework's high-level helpers don't yet cover.\n *\n * **Prefer framework methods first**: `request.input()`, `request.header()`,\n * `request.body`, `request.query`, `request.params`, `request.file()`,\n * `request.user`, `request.detectIp()`, etc. They handle locale, parsing,\n * trust-proxy, and validation pipeline integration correctly.\n *\n * **Reach for `baseRequest` only** when the framework genuinely lacks a\n * helper for what you need — and when you do, file an issue so we can add\n * it. The escape hatch is the release valve that lets consumers move\n * faster than the framework, but every long-term reach here is a missing\n * helper waiting to be added.\n */\n public baseRequest!: FastifyRequest;\n\n /**\n * Response Object\n */\n public response!: Response;\n\n /**\n * Route Object\n */\n public route!: Route;\n\n /**\n * Parsed Request Payload\n */\n protected payload: any = {};\n\n /**\n * Backing field for `decodedAccessToken` — see the accessor below.\n */\n private _decodedAccessToken?: DecodedAccessToken;\n\n /**\n * Decoded access token payload (set by auth middleware).\n *\n * A prototype accessor, not a plain field, so assignment can mark the\n * request `authDerived` (see the setter below and `RequestLocals` in\n * `types.ts`) without every call site remembering to do so itself.\n */\n public get decodedAccessToken(): DecodedAccessToken | undefined {\n return this._decodedAccessToken;\n }\n\n public set decodedAccessToken(value: DecodedAccessToken | undefined) {\n this._decodedAccessToken = value;\n this.locals.authDerived = true;\n }\n\n /**\n * Backing field for `user` — see the accessor below.\n */\n private _user?: RequestUser;\n\n /**\n * The authenticated user attached to this request, if any.\n *\n * `RequestUser` is empty by default, so ANY shape is assignable here at the\n * declaration site — the app or auth package declares its real fields via\n * module augmentation:\n *\n * ```typescript\n * declare module \"@warlock.js/core\" {\n * interface RequestUser {\n * id: string | number;\n * }\n * }\n * ```\n *\n * Replaces the v4 `GuardedRequest` convention\n * (`create-warlock/.../guarded.request.ts` — `Request<T> & { user: User }`,\n * an intersection type hand-declared per app) with a property core itself\n * declares and types. `clearCurrentUser()` below is the one place core\n * writes it directly; auth middleware writes it after a successful token\n * resolution.\n *\n * A prototype accessor, not a plain field: the setter also marks the\n * request `authDerived` (see below), so `clearCurrentUser()`'s\n * `this.user = undefined` still counts as touching auth state rather than\n * un-marking it.\n */\n public get user(): RequestUser | undefined {\n return this._user;\n }\n\n public set user(value: RequestUser | undefined) {\n this._user = value;\n this.locals.authDerived = true;\n }\n\n /**\n * Private, server-only, per-request data bag.\n *\n * Distinct from the input payload (`body` / `query` / `params` / `all()`):\n * a write here never surfaces in `request.all()`, `request.validated()`, or\n * `request.input()`. That is the trap `request.set()` sets for private data\n * — it writes into the payload `all` bag, so anything stored there leaks\n * into every input accessor and, from there, into the client-facing\n * payload. `locals` is the correct home for private per-request app data\n * (a resolved session, a fetched-once model) that must never be mistaken\n * for client input.\n *\n * Augmentable via module augmentation, in the module that OWNS the key:\n *\n * ```typescript\n * declare module \"@warlock.js/core\" {\n * interface RequestLocals {\n * session?: { token: string };\n * }\n * }\n * ```\n *\n * A plain class-field initializer is sufficient for \"fresh per request\":\n * `router.ts:925` constructs `new Request()` for every incoming request —\n * `Request` instances are not pooled or reused across requests — so this\n * initializer runs exactly once per request and no value can leak in from\n * a prior one.\n */\n public locals: RequestLocals = {};\n\n /**\n * Forget the authenticated user for this request.\n *\n * The `user` documentation above already names this as \"the one place core\n * writes it directly\", and `@warlock.js/auth`'s middleware already calls it when\n * a token is forged, malformed, expired, or of the wrong type. It was designed,\n * documented and called — just never written, so `auth` could not typecheck.\n *\n * Clearing rather than leaving a stale value matters: a request that failed\n * authentication must not carry the identity of whoever this object last held.\n */\n public clearCurrentUser(): void {\n this.user = undefined;\n }\n\n /**\n * Backing field for the lazily-generated CSP nonce. Left `undefined` until\n * the first `request.nonce` read; see the `nonce` getter below.\n */\n protected _nonce?: string;\n\n /**\n * Per-request Content-Security-Policy nonce — a fresh, unguessable value\n * the web layer hands to `<Scripts nonce={...} />` (the inline payload\n * script) and to the `Content-Security-Policy` header, so a strict\n * `script-src 'nonce-...'` allows only the script this request actually\n * rendered.\n *\n * Generated LAZILY on first access, not eagerly in `setRequest()`: most\n * requests (API routes, anything that isn't rendering HTML) never read it,\n * and spending a `randomBytes` call on every single request for a value\n * most of them discard is wasted entropy draw + CPU. Once generated it is\n * cached in `_nonce`, so every subsequent read within the SAME request\n * returns the identical value — required, since the header and the inline\n * `<script>` tag must agree on one nonce. `_nonce` is a plain field on a\n * per-request `Request` instance (see `locals` above — `router.ts:925`,\n * no pooling), so the cache can never leak into the next request; a fresh\n * `Request` means a fresh, unset `_nonce`.\n *\n * 16 random bytes, base64-encoded — the size the CSP Level 3 spec's own\n * examples use, and far more entropy than an attacker could feasibly guess\n * to defeat the policy.\n */\n public get nonce(): string {\n if (!this._nonce) {\n this._nonce = randomBytes(16).toString(\"base64\");\n }\n\n return this._nonce;\n }\n\n /**\n * Current request instance\n */\n public static current: Request;\n\n /**\n * Translation method\n * Type of it is the same as the type of trans function\n */\n public trans: ReturnType<typeof trans> = trans;\n\n /**\n * Alias to trans method\n */\n public t: ReturnType<typeof trans> = trans;\n\n /*\n * v5 removed the `[key: string]: any` index signature (eed20184). Attaching\n * arbitrary properties compiled silently and hid real bugs behind `any`.\n * The sanctioned extension paths are:\n * - `request.locals` (augment `RequestLocals` via module augmentation) for\n * per-request attached data, e.g. models fetched in validation middleware.\n * - `requestMemo(key, fn)` for per-request memoized computation.\n * - Module augmentation of the `Request` class itself for new typed members.\n */\n\n /**\n * Locale code\n */\n protected _locale = \"\";\n\n /**\n * Validated data\n */\n protected validatedData?: RequestValidation;\n\n /**\n * Request id\n */\n public id = Random.string(32);\n\n /**\n * Start Time\n */\n public startTime = Date.now();\n\n /**\n * End Time\n */\n public endTime?: undefined | number;\n\n /**\n * Set request handler\n */\n public setRequest(request: FastifyRequest) {\n this.baseRequest = request;\n\n this.resolveRequestId();\n\n this.parsePayload();\n\n // Resolve the locale at CALL time, never at bind time. `setRequest` runs\n // before routing, so a locale set later (path locale, `setLocaleCode`, the\n // web layer's C3 derivation) must steer translations too — the old\n // `transFrom.bind(null, localeCode)` snapshot made `request.locale` and\n // `request.trans()` silently disagree for the rest of the request.\n this.trans = this.t = (keyword: string, placeholders?: any) =>\n transFrom(this.getLocaleCode(), keyword, placeholders);\n\n return this;\n }\n\n /**\n * Inherit `X-Request-Id` from the incoming request, fall back to a custom\n * generator, then to the field-init default (`Random.string(32)`).\n *\n * Inherited values are validated (length cap + printable-ASCII) to prevent\n * log-injection from a malicious client. Disable the whole behavior by\n * setting `http.requestId.enabled = false` — in which case the field-init\n * default is used regardless of any incoming header.\n */\n protected resolveRequestId() {\n const requestIdConfig = config.key(\"http.requestId\") || {};\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = (requestIdConfig.header || \"x-request-id\").toLowerCase();\n const incoming = this.baseRequest.headers[headerName];\n\n if (Request.isValidRequestId(incoming)) {\n this.id = incoming;\n\n return;\n }\n\n if (typeof requestIdConfig.generator === \"function\") {\n this.id = requestIdConfig.generator();\n }\n }\n\n /**\n * Validate a candidate request-id value. Accepts non-empty printable ASCII\n * up to 128 characters — tight enough to reject newline / control-character\n * log-injection, loose enough to accept UUIDs, ULIDs, snowflakes, etc.\n */\n protected static isValidRequestId(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= 128 &&\n /^[\\x21-\\x7e]+$/.test(value)\n );\n }\n\n /**\n * Translate from the given locale code\n */\n public transFrom(localeCode: string, keyword: string, placeholders?: any) {\n return transFrom(localeCode, keyword, placeholders);\n }\n\n /**\n * Cache one supported locale without coercing request-controlled input.\n *\n * The default is the answer for a client that asked for NOTHING. A client\n * that did ask is only overridden when its value fails a declared\n * `app.localeCodes` allow-list; with no list declared there is nothing to\n * fail, so the requested locale passes through unchanged.\n */\n protected cacheLocale(candidate: unknown): string {\n const { defaultLocaleCode, localeCodes } = resolveLocaleConfiguration(\n config.key(\"app.localeCode\"),\n config.key(\"app.localeCodes\"),\n );\n\n const requested = typeof candidate === \"string\" && candidate.length > 0 ? candidate : undefined;\n\n this._locale =\n requested !== undefined && (localeCodes === undefined || localeCodes.includes(requested))\n ? requested\n : defaultLocaleCode;\n\n return this._locale;\n }\n\n /**\n * Resolve the first present Mode B source. Unsupported values fail closed to\n * the configured default instead of widening the application's locale set.\n */\n protected resolveLocale(): string {\n const candidate = [\n this.query[\"locale\"],\n this.cookies[LOCALE_COOKIE_NAME],\n this.header(\"locale\"),\n ].find((value) => typeof value === \"string\" && value.length > 0);\n\n return this.cacheLocale(candidate);\n }\n\n /**\n * Get current locale code\n */\n public get locale(): string {\n if (this._locale) return this._locale;\n\n return this.resolveLocale();\n }\n\n /**\n * Set locale code\n */\n public set locale(localeCode: string) {\n this.cacheLocale(localeCode);\n }\n\n /**\n * Set locale code\n */\n public setLocaleCode(localeCode: string) {\n this.locale = localeCode;\n\n return this;\n }\n\n /**\n * @deprecated Use `request.locale`. This alias is removed after one version.\n * The legacy default argument is accepted for source compatibility but the\n * resolved default is owned exclusively by app configuration.\n */\n public getLocaleCode(_legacyDefaultLocaleCode?: string): string {\n return this.locale;\n }\n\n /**\n * Get http protocol\n */\n public get protocol() {\n return this.baseRequest.protocol;\n }\n\n /**\n * Validate the given validation schema\n */\n public async validate(validation: BaseValidator, selectedInputs?: string[]) {\n return await v.validate(validation, selectedInputs ? this.only(selectedInputs) : this.all());\n }\n\n /**\n * Get value of the given header\n */\n public header<TCustomHeader extends string = HeaderKeys>(\n name: TCustomHeader | HeaderKeys,\n defaultValue: any = null,\n ) {\n return this.baseRequest.headers[name.toLocaleLowerCase()] ?? defaultValue;\n }\n\n /**\n * Get all cookies from the current request\n */\n public get cookies(): Record<string, string | undefined> {\n return this.baseRequest.cookies || {};\n }\n\n /**\n * Get a particular cookie value or fallback to default\n */\n public cookie(name: string, defaultValue?: any): string | any {\n const value = this.cookies[name] ?? defaultValue;\n\n try {\n return JSON.parse(value);\n } catch (error) {\n return value;\n }\n }\n\n /**\n * Determine if the request has the specified cookie\n */\n public hasCookie(name: string): boolean {\n return this.cookies[name] !== undefined;\n }\n\n /**\n * Get the current request domain\n */\n public get domain() {\n return this.baseRequest.hostname.replace(/^www\\./, \"\");\n }\n\n /**\n * Get hostname\n */\n public get hostname() {\n return this.domain;\n }\n\n /**\n * Get request origin\n */\n public get origin() {\n return this.baseRequest.headers.origin as string;\n }\n\n /**\n * Get the domain of the origin\n */\n public get originDomain() {\n const domain = this.origin ? new URL(this.origin).hostname : null;\n\n if (domain?.startsWith(\"www.\")) {\n return domain.replace(/^www\\./, \"\");\n }\n\n return domain;\n }\n\n /**\n * Get authorization header value\n */\n public get authorizationValue(): string {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return \"\";\n\n const [type, value] = authorization.split(\" \");\n\n if (![\"bearer\", \"key\"].includes(type.toLowerCase())) return \"\";\n\n return value || \"\";\n }\n\n /**\n * Get access token from Authorization header\n *\n * If the Authorization header does not start with `Bearer` value then return null\n */\n public get accessToken(): string | undefined {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return;\n\n const [type, value] = authorization.split(\" \");\n\n if (type.toLowerCase() !== \"bearer\") return;\n\n return value;\n }\n\n /**\n * Get the authorization header\n */\n public get authorization() {\n return this.header(\"authorization\");\n }\n\n /**\n * Get current request method\n */\n public get method(): string {\n return this.baseRequest.method;\n }\n\n /**\n * Parse the payload and merge it from the request body, params and query string\n */\n /**\n * Turn a bracket-notation key into the dotted path `set()` expects.\n *\n * `a[b][c]` -> `a.b.c`. Used only for NON-numeric nesting; numeric indices\n * keep the array-of-objects path in {@link parseBody}, which builds real\n * arrays rather than objects with numeric keys.\n */\n protected bracketKeyToPath(key: string): string {\n return key.replace(/\\]\\[/g, \".\").replace(/\\[/g, \".\").replace(/\\]/g, \"\");\n }\n\n /**\n * Apply the `key[]` array marker to a parsed value.\n *\n * The subtlety this exists to remove: a key declared `[]` should ALWAYS be an\n * array, but the underlying query/body parser only hands us one when the\n * caller sent the key more than once. Deciding the TYPE from the number of\n * occurrences means one selected filter is a string and two are an array —\n * a shape that changes under the user's hands.\n */\n protected arrayValueFor(value: any, isArrayKey: boolean, parse: (value: any) => any) {\n if (Array.isArray(value)) return value.map(parse);\n\n return isArrayKey ? [parse(value)] : parse(value);\n }\n\n protected parsePayload() {\n this.payload.body = this.parseBody(this.baseRequest.body);\n\n this.payload.query = this.parseBody(this.baseRequest.query);\n this.payload.params = { ...(this.baseRequest.params || {}) };\n this.payload.all = {\n ...this.payload.body,\n ...this.payload.query,\n ...this.payload.params,\n };\n }\n\n /**\n * Parse body payload\n */\n protected parseBody(data: any) {\n try {\n if (!data) return {};\n\n const body: any = {};\n\n const arrayOfObjectValues: any = {};\n\n for (let key in data) {\n const value = data[key];\n\n let isArrayKey = false;\n\n if (key.endsWith(\"[]\")) {\n isArrayKey = true;\n }\n\n key = rtrim(key, \"[]\");\n\n // check if the key is has a square brackets, then convert it into object\n // i.e user[email] => user: {email: \"value\"}\n // also check if its an array of objects\n\n if (key.includes(\"[\")) {\n // check if its an array of objects\n if (key.includes(\"][\")) {\n const keyParts = key.split(\"[\");\n\n const keyName = keyParts[0];\n\n const keyNameParts = keyParts[1].split(\"]\");\n\n const index = Number(keyNameParts[0]);\n\n /*\n A NON-NUMERIC first segment is not an array index — it is a deeper\n nested object. `a[b][c]=x` reaches this branch because it contains\n \"][\", but `Number(\"b\")` is NaN, and the code below used to write to\n `[NaN]`: that sets a \"NaN\" PROPERTY on an array whose length stays\n 0, so the request arrived as `{a: []}` and the value was gone. No\n error, no warning — the caller simply never got `x`.\n\n Deciding between refusing (4xx) and interpreting: a doubly-nested\n key is unambiguous and is exactly what every bracket-notation\n parser means by it, so we interpret. Refusing would reject a URL\n shape that is standard elsewhere and that we ourselves already\n honour one level shallower, five lines below. What was definitely\n wrong was answering with a shape the caller did not send.\n\n Numeric indices keep the array-of-objects path below unchanged —\n `items[0][name]` is still an array.\n */\n if (Number.isNaN(index)) {\n set(\n body,\n this.bracketKeyToPath(key),\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n if (!arrayOfObjectValues[keyName]) {\n arrayOfObjectValues[keyName] = [];\n }\n\n if (!arrayOfObjectValues[keyName][index]) {\n arrayOfObjectValues[keyName][index] = {};\n }\n\n // now get the key after the index\n const keyNameParts2 = keyParts[2].split(\"]\");\n const keyName2 = keyNameParts2[0];\n\n arrayOfObjectValues[keyName][index][keyName2] = this.parseValue(value);\n\n continue;\n }\n\n const keyParts = key.split(\"[\");\n const keyName = keyParts[0];\n const keyNameParts = keyParts[1].split(\"]\");\n\n /*\n `isArrayKey` is honoured HERE, and used not to be. `filter[tags][]=a`\n sets the flag at the top of the loop, but this branch only wrapped\n when the underlying value was ALREADY an array — which it is for two\n or more occurrences and is not for one. So `filter[tags][]=a` arrived\n as `{filter:{tags:\"a\"}}` while `…=a&…=b` arrived as `{tags:[\"a\",\"b\"]}`:\n the same declared shape, two different types, decided by how many\n times the caller happened to send it.\n\n That single-element case is the one a UI hits first — one filter\n chip selected — and `@warlock.js/web`'s decoder reads it as an array,\n so the page and the server disagreed about the same URL.\n */\n set(\n body,\n keyName + \".\" + keyNameParts[0],\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n if (Array.isArray(value)) {\n set(body, key, value.map(this.parseValue.bind(this)));\n } else if (isArrayKey) {\n if (body[key]) {\n body[key].push(this.parseValue(value));\n } else {\n body[key] = [this.parseValue(value)];\n\n continue;\n }\n } else {\n set(body, key, this.parseValue(value));\n }\n }\n\n // now merge the array of objects into the body\n for (const key in arrayOfObjectValues) {\n body[key] = arrayOfObjectValues[key];\n }\n\n return body;\n } catch (error) {\n console.log(error);\n this.log(error, \"error\");\n }\n }\n\n /**\n * Parse the given data\n */\n protected parseValue(data: any) {\n // data.value appears only in the multipart form data\n // if it json, then just return the data\n if (data?.file) return new UploadedFile(data);\n if (data?.value !== undefined && data?.fields && data?.type) {\n data = data.value;\n }\n\n if (data === \"false\") return false;\n\n if (data === \"true\") return true;\n\n if (data === \"null\") return null;\n\n if (typeof data === \"string\") return data.trim();\n\n return data;\n }\n\n /**\n * Set route handler\n */\n public setRoute(route: Route) {\n this.route = route;\n\n // pass the route to the response object\n this.response.setRoute(route);\n\n return this;\n }\n\n /**\n * Trigger an http event\n */\n public trigger(eventName: RequestEvent, ...args: any[]) {\n return events.trigger(`request.${eventName}`, ...args, this);\n }\n\n /**\n * Listen to the given event\n */\n public on(eventName: RequestEvent, callback: any) {\n return events.subscribe(`request.${eventName}`, callback);\n }\n\n /**\n * Make a log message\n */\n public log(message: any, level: LogLevel = \"info\") {\n if (!config.key(\"http.log\")) return;\n\n log.log({\n module: \"request\",\n action: this.route.method + \" \" + this.route.path.replace(\"/*\", \"\") + `:${this.id}`,\n message,\n type: level,\n context: {\n request: this,\n },\n });\n }\n\n /**\n * Get current request path\n */\n public get path() {\n return this.baseRequest.url;\n }\n\n /**\n * {@alias}\n */\n public get url() {\n return this.baseRequest.url;\n }\n\n /**\n * Get full url\n */\n public get fullUrl() {\n return this.protocol + \"://\" + this.hostname + this.path;\n }\n\n /**\n * Drive the middleware chain for the current route, then defer to the\n * controller. Returns the first response value any middleware short-circuits\n * with, or `undefined` to continue into validation + handler.\n *\n * @internal Framework orchestration — do not call from app code. Will move\n * to a dedicated controller dispatcher in a future refactor.\n */\n public async runMiddleware() {\n // measure request time\n // check for middleware first\n const middlewareOutput = await this.executeMiddleware();\n\n if (middlewareOutput !== undefined) {\n // 👇🏻 make sure first its not a response instance\n if (middlewareOutput instanceof Response) return middlewareOutput;\n // 👇🏻 send the response\n return this.response.send(middlewareOutput);\n }\n\n const handler = this.route.handler;\n\n if (!handler.validation) return;\n\n // 👇🏻 check for validation using validateAll helper function\n const validationOutput = await validateAll(handler.validation, this, this.response);\n\n return validationOutput;\n }\n\n /**\n * Return the request handler attached to the current route.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n public getHandler() {\n return this.route.handler;\n }\n\n /**\n * Get inputs that has been validated only\n * You can also pass an array of inputs to get only the validated inputs\n */\n public validated<Output = RequestValidation>(inputs?: (keyof Output | (string & {}))[]): Output {\n if (this.validatedData) {\n return inputs\n ? only(this.validatedData as Output, inputs as string[])\n : (this.validatedData as Output);\n }\n\n return {} as Output;\n }\n\n /**\n * Get inputs that has been validated except the given inputs\n */\n public validatedExcept(...inputs: string[]): RequestValidation {\n return except(this.validated(), inputs);\n }\n\n /**\n * Set validated data\n */\n public setValidatedData(data: RequestValidation) {\n this.validatedData = data;\n }\n\n /**\n * Top-level entry into the request lifecycle — opens the context store,\n * runs middleware, drives the handler, handles errors.\n *\n * @internal Framework orchestration — do not call from app code. Wired\n * from the Fastify route handler in `router.scan()`.\n */\n public async execute() {\n try {\n // call executingAction event\n\n this.log(\"Executing the request\");\n\n return await createRequestStore(this, this.response);\n } catch (error) {\n this.log(error, \"error\");\n\n throw error;\n }\n }\n\n /**\n * Iterate the collected middlewares in order; return the first short-circuit\n * value or `undefined` when every middleware passes through.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected async executeMiddleware() {\n // collect all middlewares for current route\n const middlewares = this.collectMiddlewares();\n\n // check if there are no middlewares, then return\n if (middlewares.length === 0) return;\n\n this.log(\"About to execute request middlewares\");\n\n // trigger the executingMiddleware event\n this.trigger(\"executingMiddleware\", middlewares, this.route);\n\n for (const middleware of middlewares) {\n this.log(\"Executing middleware \" + colors.yellowBright(middleware.name));\n const output = await middleware({\n request: this,\n response: this.response,\n });\n this.log(\"Executed middleware \" + colors.yellowBright(middleware.name), \"success\");\n\n if (output !== undefined) {\n this.log(\n colors.yellow(\"request intercepted by middleware \") + colors.cyanBright(middleware.name),\n \"warn\",\n );\n\n this.trigger(\"executedMiddleware\");\n\n this.log(\"Request middlewares executed\", \"success\");\n\n return output;\n }\n }\n\n this.log(\"Request middlewares executed\", \"success\");\n\n // trigger the executedMiddleware event\n this.trigger(\"executedMiddleware\", middlewares, this.route);\n }\n\n /**\n * Gather the middleware list for the current route — today just the\n * route-level array; future extraction may merge group + app-wide layers.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected collectMiddlewares(): Middleware[] {\n const middlewaresList: Middleware[] = [];\n\n // collect route middlewares\n if (this.route.middleware) {\n middlewaresList.push(...this.route.middleware);\n }\n\n return middlewaresList;\n }\n\n /**\n * Get request input value from query string, params or body\n */\n public input(key: string, defaultValue?: any) {\n return get(this.payload.all, key, defaultValue);\n }\n\n /**\n * Get email input value, this will lowercase the value\n */\n public email(key: string = \"email\", defaultValue: string = \"\"): string {\n return this.input(key, defaultValue)?.toLowerCase() || defaultValue;\n }\n\n /**\n * @alias input\n */\n public get(key: string, defaultValue?: any) {\n return this.input(key, defaultValue);\n }\n\n /**\n * Determine if request has input value\n */\n public has(key: string) {\n return get(this.payload.all, key, undefined) !== undefined;\n }\n\n /**\n * Set request input value\n */\n public set(key: string, value: any) {\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Set the given value if the request does not have the input\n */\n public setDefault(key: string, value: any) {\n if (this.has(key)) return this;\n\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Unset request payload keys\n */\n public unset(...keys: string[]) {\n this.payload.all = unset(this.payload.all, keys);\n\n return this;\n }\n\n /**\n * Get request body\n */\n public get body() {\n return this.payload.body;\n }\n\n /**\n * Set request body value\n */\n public setBody(key: string, value: any) {\n set(this.payload.body, key, value);\n\n return this;\n }\n\n /**\n * Get body inputs except files\n */\n public get bodyInputs() {\n const inputs = this.payload.body;\n\n const bodyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (value.file && value.fieldname) continue;\n\n bodyInputs[key] = value;\n }\n\n return bodyInputs;\n }\n\n /**\n * Get request file in UploadedFile instance\n */\n public file(key: string): UploadedFile | undefined {\n const file = this.input(key);\n\n return file;\n }\n\n /**\n * Get uploaded files from the request for the given name\n * If the given name is not present in the request, return an empty array\n */\n public files(name: string): UploadedFile[] {\n return this.input(name) || [];\n }\n\n /**\n * Get request params\n */\n public get params() {\n return this.payload.params;\n }\n\n /**\n * Set request params value\n */\n public setParam(key: string, value: any) {\n set(this.payload.params, key, value);\n\n return this;\n }\n\n /**\n * Get request query\n */\n public get query() {\n return this.payload.query;\n }\n\n /**\n * Set request query value\n */\n public setQuery(key: string, value: any) {\n set(this.payload.query, key, value);\n\n return this;\n }\n\n /**\n * Get all inputs\n */\n public all() {\n return this.payload.all;\n }\n\n /**\n * Get all inputs except params\n */\n public allExceptParams() {\n return {\n ...this.payload.query,\n ...this.payload.body,\n };\n }\n\n /**\n * Get all heavy inputs except params\n */\n public heavyExceptParams() {\n const inputs = this.allExceptParams();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only heavy inputs, the input with a value\n */\n public heavy() {\n const inputs = this.all();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only the given keys from the request data\n */\n public only(keys: string[]) {\n return only(this.all(), keys);\n }\n\n /**\n * Pluck the given keys from the request data\n */\n public pluck(keys: string[]) {\n const data = this.only(keys);\n\n this.unset(...keys);\n\n return data;\n }\n\n /**\n * Get all request inputs except the given keys\n */\n public except(keys: string[]) {\n return except(this.all(), keys);\n }\n\n /**\n * Get boolean input value\n */\n public bool(key: string, defaultValue = false) {\n const value = this.input(key, defaultValue);\n\n if (value === \"true\") {\n return true;\n }\n\n if (value === \"false\") {\n return false;\n }\n\n if (value === 0) {\n return false;\n }\n\n return Boolean(value);\n }\n\n /**\n * Get integer input value\n */\n public int(key: string, defaultValue: number = 0): number | undefined {\n const value = this.input(key, defaultValue);\n\n if (!value && value !== 0) return undefined;\n\n return parseInt(value);\n }\n\n /**\n * Shorthand getter to get id param\n */\n public get idParam() {\n return this.int(\"id\");\n }\n\n /**\n * Get string input value\n */\n public string(key: string, defaultValue: string = \"\"): string {\n const value = this.input(key, defaultValue);\n\n return String(value);\n }\n\n /**\n * Get float input value\n */\n public float(key: string, defaultValue: number = 0): number {\n const value = this.input(key, defaultValue);\n\n return parseFloat(value) || 0;\n }\n\n /**\n * Get number input value\n */\n public number(key: string, defaultValue: number = 0): number {\n const value = Number(this.input(key, defaultValue));\n\n return isNaN(value) ? defaultValue : value;\n }\n\n /**\n * Immediate-peer IP as Fastify reports it — the address that connected to\n * the server socket, with `trustProxy` resolution applied. Use this when\n * you specifically need the peer address (rate-limit-by-direct-connection,\n * health-check origin verification).\n *\n * **For most use cases prefer `request.detectIp()`** — behind any proxy\n * (load balancer, CDN, sidecar) `ip` reports the proxy, not the real client.\n */\n public get ip() {\n return this.baseRequest.ip;\n }\n\n /**\n * Best-effort real client IP — the value everything IP-scoped keys on\n * (ip-filter allowlists, rate-limit buckets, idempotency scoping).\n *\n * `X-Forwarded-For` resolution is **delegated to Fastify**: `baseRequest.ip`\n * is already the client address Fastify's `trustProxy` machinery picked out\n * of the chain, so every shape `http.trustProxy` accepts is honoured here\n * with exactly the semantics Fastify documents:\n *\n * - `false` (default) — no header is trusted; the socket peer address wins.\n * Both forwarding headers are client-settable, so without a trusted edge\n * that rewrites them any client could otherwise forge its own IP.\n * - `true` — the whole chain is trusted; the leftmost hop (original client)\n * wins.\n * - `number` — that many rightmost hops are trusted, so an edge that\n * APPENDS to `X-Forwarded-For` yields the real client rather than whatever\n * the client prepended.\n * - CIDR / IP list (string, comma-separated string, or array) or a custom\n * predicate — the chain is walked right-to-left and stops at the first hop\n * that isn't a trusted proxy.\n *\n * `X-Real-IP` is NOT part of that resolution — Fastify never looks at it,\n * and unlike `X-Forwarded-For` it carries no chain, so there is nothing to\n * validate a proxy allowlist against. It is therefore honoured\n * only under `trustProxy: true` (\"everything upstream is mine\"), where it is\n * no weaker than the trust already granted. Under a bounded `trustProxy`\n * (CIDR / IP list) it is ignored: a trusted-but-passthrough edge that\n * forwards the client's own `X-Real-IP` verbatim would otherwise hand any\n * client a way around the bound.\n *\n * **Prefer this over `request.ip` for any caller behind a proxy** (load\n * balancer, CDN, reverse proxy, k8s ingress).\n */\n public detectIp() {\n // Trusting `X-Real-IP` is only sound when the config trusts the entire\n // upstream chain; bounded shapes get chain-aware resolution instead.\n // Typed as `unknown`: config.get(key, fallback) infers the FALLBACK's type, so\n // the literal `false` narrowed this to `false` and TypeScript called the\n // comparison unreachable. The stored value is genuinely unconstrained at compile\n // time - trustProxy accepts a boolean, a CIDR list or a predicate - so `unknown`\n // is what it actually is, and the === true check is the narrowing.\n const trustProxy: unknown = config.get(\"http.trustProxy\", false);\n\n if (trustProxy === true) {\n const realIp = this.header(\"x-real-ip\");\n\n if (realIp) {\n const address = String(realIp).split(\",\")[0].trim();\n\n if (address) return address;\n }\n }\n\n // Fastify resolved this against the configured `trustProxy` already:\n // socket peer when trust is off, the correct hop of `X-Forwarded-For`\n // when it is on. Re-parsing the header here would mean a second, weaker\n // trust model that could disagree with `request.ip` and with the plugins\n // (rate limit, proxy) that key on it.\n return this.baseRequest.ip;\n }\n\n /**\n * An alias to detectIp\n */\n public get realIp() {\n return this.detectIp();\n }\n\n /**\n * Get request ips\n */\n public get ips() {\n return this.baseRequest.ips;\n }\n\n /**\n * Get request referer\n */\n public get referer() {\n return this.baseRequest.headers.referer;\n }\n\n /**\n * Get user agent\n */\n public get userAgent() {\n return this.baseRequest.headers[\"user-agent\"];\n }\n\n /**\n * Get request headers\n */\n public get headers(): typeof this.baseRequest.headers {\n return this.baseRequest.headers;\n }\n\n /**\n * Set the given header\n */\n public setHeader(key: HeaderKeys, value: string) {\n this.baseRequest.headers[key.toLowerCase()] = value;\n\n return this;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8BA,IAAa,UAAb,MAAa,QAAiC;;iBA+BnB,CAAC;gBA4FK,CAAC;eA8DS;WAKJ;iBAejB;YAUR,OAAO,OAAO,EAAE;mBAKT,KAAK,IAAI;;;;;;;;;CA/K5B,IAAW,qBAAqD;EAC9D,OAAO,KAAK;CACd;CAEA,IAAW,mBAAmB,OAAuC;EACnE,KAAK,sBAAsB;EAC3B,KAAK,OAAO,cAAc;CAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCA,IAAW,OAAgC;EACzC,OAAO,KAAK;CACd;CAEA,IAAW,KAAK,OAAgC;EAC9C,KAAK,QAAQ;EACb,KAAK,OAAO,cAAc;CAC5B;;;;;;;;;;;;CA2CA,AAAO,mBAAyB;EAC9B,KAAK,OAAO;CACd;;;;;;;;;;;;;;;;;;;;;;;CA8BA,IAAW,QAAgB;EACzB,IAAI,CAAC,KAAK,QACR,KAAK,SAAS,YAAY,EAAE,CAAC,CAAC,SAAS,QAAQ;EAGjD,OAAO,KAAK;CACd;;;;CAwDA,AAAO,WAAW,SAAyB;EACzC,KAAK,cAAc;EAEnB,K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,KAAK,YAAY;CAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCA,AAAO,WAAW;EAUhB,IAF4B,OAAO,IAAI,mBAAmB,KAE7C,MAAM,MAAM;GACvB,MAAM,SAAS,KAAK,OAAO,WAAW;GAEtC,IAAI,QAAQ;IACV,MAAM,UAAU,OAAO,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK;IAElD,IAAI,SAAS,OAAO;GACtB;EACF;EAOA,OAAO,KAAK,YAAY;CAC1B;;;;CAKA,IAAW,SAAS;EAClB,OAAO,KAAK,SAAS;CACvB;;;;CAKA,IAAW,MAAM;EACf,OAAO,KAAK,YAAY;CAC1B;;;;CAKA,IAAW,UAAU;EACnB,OAAO,KAAK,YAAY,QAAQ;CAClC;;;;CAKA,IAAW,YAAY;EACrB,OAAO,KAAK,YAAY,QAAQ;CAClC;;;;CAKA,IAAW,UAA2C;EACpD,OAAO,KAAK,YAAY;CAC1B;;;;CAKA,AAAO,UAAU,KAAiB,OAAe;EAC/C,KAAK,YAAY,QAAQ,IAAI,YAAY,KAAK;EAE9C,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"request.mjs","names":[],"sources":["../../../../../../../core/src/http/request.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport events from \"@mongez/events\";\nimport { trans, transFrom } from \"@mongez/localization\";\nimport { Random, except, get, only, rtrim, set, unset } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport type { LogLevel } from \"@warlock.js/logger\";\nimport { log } from \"@warlock.js/logger\";\nimport { BaseValidator, v } from \"@warlock.js/seal\";\nimport type { FastifyRequest } from \"fastify\";\nimport { randomBytes } from \"node:crypto\";\nimport { type IncomingHttpHeaders } from \"node:http2\";\nimport { config } from \"../config/config-getter\";\nimport { LOCALE_COOKIE_NAME, resolveLocaleConfiguration } from \"../config/locale-configuration\";\nimport type { Middleware, Route } from \"../router\";\nimport { validateAll } from \"../validation/validateAll\";\nimport { createRequestStore } from \"./middleware/inject-request-context\";\nimport { Response } from \"./response\";\nimport type { DecodedAccessToken, RequestEvent, RequestLocals, RequestUser } from \"./types\";\nimport { UploadedFile } from \"./uploaded-file\";\n\ntype StandardHeaders = {\n // copy every declared property from http.IncomingHttpHeaders\n // but remove index signatures\n [\n K in keyof IncomingHttpHeaders as string extends K ? never : number extends K ? never : K\n ]: IncomingHttpHeaders[K];\n};\n\ntype HeaderKeys = keyof StandardHeaders;\n\nexport class Request<RequestValidation = any> {\n /**\n * Underlying Fastify request — a public escape hatch to capabilities the\n * framework's high-level helpers don't yet cover.\n *\n * **Prefer framework methods first**: `request.input()`, `request.header()`,\n * `request.body`, `request.query`, `request.params`, `request.file()`,\n * `request.user`, `request.detectIp()`, etc. They handle locale, parsing,\n * trust-proxy, and validation pipeline integration correctly.\n *\n * **Reach for `baseRequest` only** when the framework genuinely lacks a\n * helper for what you need — and when you do, file an issue so we can add\n * it. The escape hatch is the release valve that lets consumers move\n * faster than the framework, but every long-term reach here is a missing\n * helper waiting to be added.\n */\n public baseRequest!: FastifyRequest;\n\n /**\n * Response Object\n */\n public response!: Response;\n\n /**\n * Route Object\n */\n public route!: Route;\n\n /**\n * Parsed Request Payload\n */\n protected payload: any = {};\n\n /**\n * Backing field for `decodedAccessToken` — see the accessor below.\n */\n private _decodedAccessToken?: DecodedAccessToken;\n\n /**\n * Decoded access token payload (set by auth middleware).\n *\n * A prototype accessor, not a plain field, so assignment can mark the\n * request `authDerived` (see the setter below and `RequestLocals` in\n * `types.ts`) without every call site remembering to do so itself.\n */\n public get decodedAccessToken(): DecodedAccessToken | undefined {\n return this._decodedAccessToken;\n }\n\n public set decodedAccessToken(value: DecodedAccessToken | undefined) {\n this._decodedAccessToken = value;\n this.locals.authDerived = true;\n }\n\n /**\n * Backing field for `user` — see the accessor below.\n */\n private _user?: RequestUser;\n\n /**\n * The authenticated user attached to this request, if any.\n *\n * `RequestUser` is empty by default, so ANY shape is assignable here at the\n * declaration site — the app or auth package declares its real fields via\n * module augmentation:\n *\n * ```typescript\n * declare module \"@warlock.js/core\" {\n * interface RequestUser {\n * id: string | number;\n * }\n * }\n * ```\n *\n * Replaces the v4 `GuardedRequest` convention\n * (`create-warlock/.../guarded.request.ts` — `Request<T> & { user: User }`,\n * an intersection type hand-declared per app) with a property core itself\n * declares and types. `clearCurrentUser()` below is the one place core\n * writes it directly; auth middleware writes it after a successful token\n * resolution.\n *\n * A prototype accessor, not a plain field: the setter also marks the\n * request `authDerived` (see below), so `clearCurrentUser()`'s\n * `this.user = undefined` still counts as touching auth state rather than\n * un-marking it.\n */\n public get user(): RequestUser | undefined {\n return this._user;\n }\n\n public set user(value: RequestUser | undefined) {\n this._user = value;\n this.locals.authDerived = true;\n }\n\n /**\n * Private, server-only, per-request data bag.\n *\n * Distinct from the input payload (`body` / `query` / `params` / `all()`):\n * a write here never surfaces in `request.all()`, `request.validated()`, or\n * `request.input()`. That is the trap `request.set()` sets for private data\n * — it writes into the payload `all` bag, so anything stored there leaks\n * into every input accessor and, from there, into the client-facing\n * payload. `locals` is the correct home for private per-request app data\n * (a resolved session, a fetched-once model) that must never be mistaken\n * for client input.\n *\n * Augmentable via module augmentation, in the module that OWNS the key:\n *\n * ```typescript\n * declare module \"@warlock.js/core\" {\n * interface RequestLocals {\n * session?: { token: string };\n * }\n * }\n * ```\n *\n * A plain class-field initializer is sufficient for \"fresh per request\":\n * `router.ts:925` constructs `new Request()` for every incoming request —\n * `Request` instances are not pooled or reused across requests — so this\n * initializer runs exactly once per request and no value can leak in from\n * a prior one.\n */\n public locals: RequestLocals = {};\n\n /**\n * Forget the authenticated user for this request.\n *\n * The `user` documentation above already names this as \"the one place core\n * writes it directly\", and `@warlock.js/auth`'s middleware already calls it when\n * a token is forged, malformed, expired, or of the wrong type. It was designed,\n * documented and called — just never written, so `auth` could not typecheck.\n *\n * Clearing rather than leaving a stale value matters: a request that failed\n * authentication must not carry the identity of whoever this object last held.\n */\n public clearCurrentUser(): void {\n this.user = undefined;\n }\n\n /**\n * Backing field for the lazily-generated CSP nonce. Left `undefined` until\n * the first `request.nonce` read; see the `nonce` getter below.\n */\n protected _nonce?: string;\n\n /**\n * Per-request Content-Security-Policy nonce — a fresh, unguessable value\n * the web layer hands to `<Scripts nonce={...} />` (the inline payload\n * script) and to the `Content-Security-Policy` header, so a strict\n * `script-src 'nonce-...'` allows only the script this request actually\n * rendered.\n *\n * Generated LAZILY on first access, not eagerly in `setRequest()`: most\n * requests (API routes, anything that isn't rendering HTML) never read it,\n * and spending a `randomBytes` call on every single request for a value\n * most of them discard is wasted entropy draw + CPU. Once generated it is\n * cached in `_nonce`, so every subsequent read within the SAME request\n * returns the identical value — required, since the header and the inline\n * `<script>` tag must agree on one nonce. `_nonce` is a plain field on a\n * per-request `Request` instance (see `locals` above — `router.ts:925`,\n * no pooling), so the cache can never leak into the next request; a fresh\n * `Request` means a fresh, unset `_nonce`.\n *\n * 16 random bytes, base64-encoded — the size the CSP Level 3 spec's own\n * examples use, and far more entropy than an attacker could feasibly guess\n * to defeat the policy.\n */\n public get nonce(): string {\n if (!this._nonce) {\n this._nonce = randomBytes(16).toString(\"base64\");\n }\n\n return this._nonce;\n }\n\n /**\n * Current request instance\n */\n public static current: Request;\n\n /**\n * Translation method\n * Type of it is the same as the type of trans function\n */\n public trans: ReturnType<typeof trans> = trans;\n\n /**\n * Alias to trans method\n */\n public t: ReturnType<typeof trans> = trans;\n\n /*\n * v5 removed the `[key: string]: any` index signature (eed20184). Attaching\n * arbitrary properties compiled silently and hid real bugs behind `any`.\n * The sanctioned extension paths are:\n * - `request.locals` (augment `RequestLocals` via module augmentation) for\n * per-request attached data, e.g. models fetched in validation middleware.\n * - `requestMemo(key, fn)` for per-request memoized computation.\n * - Module augmentation of the `Request` class itself for new typed members.\n */\n\n /**\n * Locale code\n */\n protected _locale = \"\";\n\n /**\n * Validated data\n */\n protected validatedData?: RequestValidation;\n\n /**\n * Request id\n */\n public id = Random.string(32);\n\n /**\n * Start Time\n */\n public startTime = Date.now();\n\n /**\n * End Time\n */\n public endTime?: undefined | number;\n\n /**\n * Set request handler\n */\n public setRequest(request: FastifyRequest) {\n this.baseRequest = request;\n\n this.resolveRequestId();\n\n this.parsePayload();\n\n // Resolve the locale at CALL time, never at bind time. `setRequest` runs\n // before routing, so a locale set later (path locale, `setLocaleCode`, the\n // web layer's C3 derivation) must steer translations too — the old\n // `transFrom.bind(null, localeCode)` snapshot made `request.locale` and\n // `request.trans()` silently disagree for the rest of the request.\n this.trans = this.t = (keyword: string, placeholders?: any) =>\n transFrom(this.getLocaleCode(), keyword, placeholders);\n\n return this;\n }\n\n /**\n * Inherit `X-Request-Id` from the incoming request, fall back to a custom\n * generator, then to the field-init default (`Random.string(32)`).\n *\n * Inherited values are validated (length cap + printable-ASCII) to prevent\n * log-injection from a malicious client. Disable the whole behavior by\n * setting `http.requestId.enabled = false` — in which case the field-init\n * default is used regardless of any incoming header.\n */\n protected resolveRequestId() {\n const requestIdConfig = config.key(\"http.requestId\") || {};\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = (requestIdConfig.header || \"x-request-id\").toLowerCase();\n const incoming = this.baseRequest.headers[headerName];\n\n if (Request.isValidRequestId(incoming)) {\n this.id = incoming;\n\n return;\n }\n\n if (typeof requestIdConfig.generator === \"function\") {\n this.id = requestIdConfig.generator();\n }\n }\n\n /**\n * Validate a candidate request-id value. Accepts non-empty printable ASCII\n * up to 128 characters — tight enough to reject newline / control-character\n * log-injection, loose enough to accept UUIDs, ULIDs, snowflakes, etc.\n */\n protected static isValidRequestId(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= 128 &&\n /^[\\x21-\\x7e]+$/.test(value)\n );\n }\n\n /**\n * Translate from the given locale code\n */\n public transFrom(localeCode: string, keyword: string, placeholders?: any) {\n return transFrom(localeCode, keyword, placeholders);\n }\n\n /**\n * Cache one supported locale without coercing request-controlled input.\n *\n * The default is the answer for a client that asked for NOTHING. A client\n * that did ask is only overridden when its value fails a declared\n * `app.localeCodes` allow-list; with no list declared there is nothing to\n * fail, so the requested locale passes through unchanged.\n */\n protected cacheLocale(candidate: unknown): string {\n const { defaultLocaleCode, localeCodes } = resolveLocaleConfiguration(\n config.key(\"app.localeCode\"),\n config.key(\"app.localeCodes\"),\n );\n\n const requested = typeof candidate === \"string\" && candidate.length > 0 ? candidate : undefined;\n\n this._locale =\n requested !== undefined && (localeCodes === undefined || localeCodes.includes(requested))\n ? requested\n : defaultLocaleCode;\n\n return this._locale;\n }\n\n /**\n * Resolve the first present Mode B source. Unsupported values fail closed to\n * the configured default instead of widening the application's locale set.\n */\n protected resolveLocale(): string {\n const candidate = [\n this.query[\"locale\"],\n this.cookies[LOCALE_COOKIE_NAME],\n this.header(\"locale\"),\n ].find((value) => typeof value === \"string\" && value.length > 0);\n\n return this.cacheLocale(candidate);\n }\n\n /**\n * Get current locale code\n */\n public get locale(): string {\n if (this._locale) return this._locale;\n\n return this.resolveLocale();\n }\n\n /**\n * Set locale code\n */\n public set locale(localeCode: string) {\n this.cacheLocale(localeCode);\n }\n\n /**\n * Set locale code\n */\n public setLocaleCode(localeCode: string) {\n this.locale = localeCode;\n\n return this;\n }\n\n /**\n * @deprecated Use `request.locale`. This alias is removed after one version.\n * The legacy default argument is accepted for source compatibility but the\n * resolved default is owned exclusively by app configuration.\n */\n public getLocaleCode(_legacyDefaultLocaleCode?: string): string {\n return this.locale;\n }\n\n /**\n * Get http protocol\n */\n public get protocol() {\n return this.baseRequest.protocol;\n }\n\n /**\n * Validate the given validation schema\n */\n public async validate(validation: BaseValidator, selectedInputs?: string[]) {\n return await v.validate(validation, selectedInputs ? this.only(selectedInputs) : this.all());\n }\n\n /**\n * Get value of the given header\n */\n public header<TCustomHeader extends string = HeaderKeys>(\n name: TCustomHeader | HeaderKeys,\n defaultValue: any = null,\n ) {\n return this.baseRequest.headers[name.toLocaleLowerCase()] ?? defaultValue;\n }\n\n /**\n * Get all cookies from the current request\n */\n public get cookies(): Record<string, string | undefined> {\n return this.baseRequest.cookies || {};\n }\n\n /**\n * Get a particular cookie value or fallback to default\n */\n public cookie(name: string, defaultValue?: any): string | any {\n const value = this.cookies[name] ?? defaultValue;\n\n try {\n return JSON.parse(value);\n } catch (error) {\n return value;\n }\n }\n\n /**\n * Determine if the request has the specified cookie\n */\n public hasCookie(name: string): boolean {\n return this.cookies[name] !== undefined;\n }\n\n /**\n * Get the current request domain\n */\n public get domain() {\n return this.baseRequest.hostname.replace(/^www\\./, \"\");\n }\n\n /**\n * Get hostname\n */\n public get hostname() {\n return this.domain;\n }\n\n /**\n * Get request origin\n */\n public get origin() {\n return this.baseRequest.headers.origin as string;\n }\n\n /**\n * Get the domain of the origin\n */\n public get originDomain() {\n const domain = this.origin ? new URL(this.origin).hostname : null;\n\n if (domain?.startsWith(\"www.\")) {\n return domain.replace(/^www\\./, \"\");\n }\n\n return domain;\n }\n\n /**\n * Get authorization header value\n */\n public get authorizationValue(): string {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return \"\";\n\n const [type, value] = authorization.split(\" \");\n\n if (![\"bearer\", \"key\"].includes(type.toLowerCase())) return \"\";\n\n return value || \"\";\n }\n\n /**\n * Get access token from Authorization header\n *\n * If the Authorization header does not start with `Bearer` value then return null\n */\n public get accessToken(): string | undefined {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return;\n\n const [type, value] = authorization.split(\" \");\n\n if (type.toLowerCase() !== \"bearer\") return;\n\n return value;\n }\n\n /**\n * Get the authorization header\n */\n public get authorization() {\n return this.header(\"authorization\");\n }\n\n /**\n * Get current request method\n */\n public get method(): string {\n return this.baseRequest.method;\n }\n\n /**\n * Parse the payload and merge it from the request body, params and query string\n */\n /**\n * Turn a bracket-notation key into the dotted path `set()` expects.\n *\n * `a[b][c]` -> `a.b.c`. Used only for NON-numeric nesting; numeric indices\n * keep the array-of-objects path in {@link parseBody}, which builds real\n * arrays rather than objects with numeric keys.\n */\n protected bracketKeyToPath(key: string): string {\n return key.replace(/\\]\\[/g, \".\").replace(/\\[/g, \".\").replace(/\\]/g, \"\");\n }\n\n /**\n * Apply the `key[]` array marker to a parsed value.\n *\n * The subtlety this exists to remove: a key declared `[]` should ALWAYS be an\n * array, but the underlying query/body parser only hands us one when the\n * caller sent the key more than once. Deciding the TYPE from the number of\n * occurrences means one selected filter is a string and two are an array —\n * a shape that changes under the user's hands.\n */\n protected arrayValueFor(value: any, isArrayKey: boolean, parse: (value: any) => any) {\n if (Array.isArray(value)) return value.map(parse);\n\n return isArrayKey ? [parse(value)] : parse(value);\n }\n\n protected parsePayload() {\n this.payload.body = this.parseBody(this.baseRequest.body);\n\n this.payload.query = this.parseBody(this.baseRequest.query);\n this.payload.params = { ...(this.baseRequest.params || {}) };\n this.payload.all = {\n ...this.payload.body,\n ...this.payload.query,\n ...this.payload.params,\n };\n }\n\n /**\n * Parse body payload\n */\n protected parseBody(data: any) {\n try {\n if (!data) return {};\n\n const body: any = {};\n\n const arrayOfObjectValues: any = {};\n\n for (let key in data) {\n const value = data[key];\n\n let isArrayKey = false;\n\n if (key.endsWith(\"[]\")) {\n isArrayKey = true;\n }\n\n key = rtrim(key, \"[]\");\n\n // check if the key is has a square brackets, then convert it into object\n // i.e user[email] => user: {email: \"value\"}\n // also check if its an array of objects\n\n if (key.includes(\"[\")) {\n // check if its an array of objects\n if (key.includes(\"][\")) {\n const keyParts = key.split(\"[\");\n\n const keyName = keyParts[0];\n const firstBracket = keyParts[1];\n const secondBracket = keyParts[2];\n\n /*\n `key.includes(\"][\")` guarantees all three segments — but that is a\n property of the string test above, not of these reads, so each is\n `string | undefined`.\n\n When the shape is not what this branch assumes, fall through to\n the generic bracket path rather than skipping the key. That is the\n same choice the NaN branch below makes, and for the same reason\n spelled out there: the failure this code has already been bitten\n by is answering with a shape the caller did not send. Dropping the\n pair silently would be that bug again, in a new place.\n */\n if (\n keyName === undefined ||\n firstBracket === undefined ||\n secondBracket === undefined\n ) {\n set(\n body,\n this.bracketKeyToPath(key),\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n const keyNameParts = firstBracket.split(\"]\");\n\n const index = Number(keyNameParts[0]);\n\n /*\n A NON-NUMERIC first segment is not an array index — it is a deeper\n nested object. `a[b][c]=x` reaches this branch because it contains\n \"][\", but `Number(\"b\")` is NaN, and the code below used to write to\n `[NaN]`: that sets a \"NaN\" PROPERTY on an array whose length stays\n 0, so the request arrived as `{a: []}` and the value was gone. No\n error, no warning — the caller simply never got `x`.\n\n Deciding between refusing (4xx) and interpreting: a doubly-nested\n key is unambiguous and is exactly what every bracket-notation\n parser means by it, so we interpret. Refusing would reject a URL\n shape that is standard elsewhere and that we ourselves already\n honour one level shallower, five lines below. What was definitely\n wrong was answering with a shape the caller did not send.\n\n Numeric indices keep the array-of-objects path below unchanged —\n `items[0][name]` is still an array.\n */\n if (Number.isNaN(index)) {\n set(\n body,\n this.bracketKeyToPath(key),\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n const bucket = (arrayOfObjectValues[keyName] ??= []);\n\n const entry = (bucket[index] ??= {});\n\n // now get the key after the index\n const keyNameParts2 = secondBracket.split(\"]\");\n const keyName2 = keyNameParts2[0];\n\n // `split` always yields a first element, so this holds — but an\n // undefined key here would write a property literally named\n // \"undefined\" onto the entry, which is the same silent-wrong-shape\n // outcome the comment above describes.\n if (keyName2 === undefined) continue;\n\n entry[keyName2] = this.parseValue(value);\n\n continue;\n }\n\n const keyParts = key.split(\"[\");\n const keyName = keyParts[0];\n // `key.includes(\"[\")` puts at least two segments here. Falling back\n // to the whole key rather than asserting keeps the parse total: an\n // undefined segment would make `keyNameParts[0]` undefined too, and\n // this branch writes that straight into the body shape.\n const keyNameParts = (keyParts[1] ?? key).split(\"]\");\n\n /*\n `isArrayKey` is honoured HERE, and used not to be. `filter[tags][]=a`\n sets the flag at the top of the loop, but this branch only wrapped\n when the underlying value was ALREADY an array — which it is for two\n or more occurrences and is not for one. So `filter[tags][]=a` arrived\n as `{filter:{tags:\"a\"}}` while `…=a&…=b` arrived as `{tags:[\"a\",\"b\"]}`:\n the same declared shape, two different types, decided by how many\n times the caller happened to send it.\n\n That single-element case is the one a UI hits first — one filter\n chip selected — and `@warlock.js/web`'s decoder reads it as an array,\n so the page and the server disagreed about the same URL.\n */\n set(\n body,\n keyName + \".\" + keyNameParts[0],\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n if (Array.isArray(value)) {\n set(body, key, value.map(this.parseValue.bind(this)));\n } else if (isArrayKey) {\n if (body[key]) {\n body[key].push(this.parseValue(value));\n } else {\n body[key] = [this.parseValue(value)];\n\n continue;\n }\n } else {\n set(body, key, this.parseValue(value));\n }\n }\n\n // now merge the array of objects into the body\n for (const key in arrayOfObjectValues) {\n body[key] = arrayOfObjectValues[key];\n }\n\n return body;\n } catch (error) {\n console.log(error);\n this.log(error, \"error\");\n }\n }\n\n /**\n * Parse the given data\n */\n protected parseValue(data: any) {\n // data.value appears only in the multipart form data\n // if it json, then just return the data\n if (data?.file) return new UploadedFile(data);\n if (data?.value !== undefined && data?.fields && data?.type) {\n data = data.value;\n }\n\n if (data === \"false\") return false;\n\n if (data === \"true\") return true;\n\n if (data === \"null\") return null;\n\n if (typeof data === \"string\") return data.trim();\n\n return data;\n }\n\n /**\n * Set route handler\n */\n public setRoute(route: Route) {\n this.route = route;\n\n // pass the route to the response object\n this.response.setRoute(route);\n\n return this;\n }\n\n /**\n * Trigger an http event\n */\n public trigger(eventName: RequestEvent, ...args: any[]) {\n return events.trigger(`request.${eventName}`, ...args, this);\n }\n\n /**\n * Listen to the given event\n */\n public on(eventName: RequestEvent, callback: any) {\n return events.subscribe(`request.${eventName}`, callback);\n }\n\n /**\n * Make a log message\n */\n public log(message: any, level: LogLevel = \"info\") {\n if (!config.key(\"http.log\")) return;\n\n log.log({\n module: \"request\",\n action: this.route.method + \" \" + this.route.path.replace(\"/*\", \"\") + `:${this.id}`,\n message,\n type: level,\n context: {\n request: this,\n },\n });\n }\n\n /**\n * Get current request path\n */\n public get path() {\n return this.baseRequest.url;\n }\n\n /**\n * {@alias}\n */\n public get url() {\n return this.baseRequest.url;\n }\n\n /**\n * Get full url\n */\n public get fullUrl() {\n return this.protocol + \"://\" + this.hostname + this.path;\n }\n\n /**\n * Drive the middleware chain for the current route, then defer to the\n * controller. Returns the first response value any middleware short-circuits\n * with, or `undefined` to continue into validation + handler.\n *\n * @internal Framework orchestration — do not call from app code. Will move\n * to a dedicated controller dispatcher in a future refactor.\n */\n public async runMiddleware() {\n // measure request time\n // check for middleware first\n const middlewareOutput = await this.executeMiddleware();\n\n if (middlewareOutput !== undefined) {\n // 👇🏻 make sure first its not a response instance\n if (middlewareOutput instanceof Response) return middlewareOutput;\n // 👇🏻 send the response\n return this.response.send(middlewareOutput);\n }\n\n const handler = this.route.handler;\n\n if (!handler.validation) return;\n\n // 👇🏻 check for validation using validateAll helper function\n const validationOutput = await validateAll(handler.validation, this, this.response);\n\n return validationOutput;\n }\n\n /**\n * Return the request handler attached to the current route.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n public getHandler() {\n return this.route.handler;\n }\n\n /**\n * Get inputs that has been validated only\n * You can also pass an array of inputs to get only the validated inputs\n */\n public validated<Output = RequestValidation>(inputs?: (keyof Output | (string & {}))[]): Output {\n if (this.validatedData) {\n return inputs\n ? only(this.validatedData as Output, inputs as string[])\n : (this.validatedData as Output);\n }\n\n return {} as Output;\n }\n\n /**\n * Get inputs that has been validated except the given inputs\n */\n public validatedExcept(...inputs: string[]): RequestValidation {\n return except(this.validated(), inputs);\n }\n\n /**\n * Set validated data\n */\n public setValidatedData(data: RequestValidation) {\n this.validatedData = data;\n }\n\n /**\n * Top-level entry into the request lifecycle — opens the context store,\n * runs middleware, drives the handler, handles errors.\n *\n * @internal Framework orchestration — do not call from app code. Wired\n * from the Fastify route handler in `router.scan()`.\n */\n public async execute() {\n try {\n // call executingAction event\n\n this.log(\"Executing the request\");\n\n return await createRequestStore(this, this.response);\n } catch (error) {\n this.log(error, \"error\");\n\n throw error;\n }\n }\n\n /**\n * Iterate the collected middlewares in order; return the first short-circuit\n * value or `undefined` when every middleware passes through.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected async executeMiddleware() {\n // collect all middlewares for current route\n const middlewares = this.collectMiddlewares();\n\n // check if there are no middlewares, then return\n if (middlewares.length === 0) return;\n\n this.log(\"About to execute request middlewares\");\n\n // trigger the executingMiddleware event\n this.trigger(\"executingMiddleware\", middlewares, this.route);\n\n for (const middleware of middlewares) {\n this.log(\"Executing middleware \" + colors.yellowBright(middleware.name));\n const output = await middleware({\n request: this,\n response: this.response,\n });\n this.log(\"Executed middleware \" + colors.yellowBright(middleware.name), \"success\");\n\n if (output !== undefined) {\n this.log(\n colors.yellow(\"request intercepted by middleware \") + colors.cyanBright(middleware.name),\n \"warn\",\n );\n\n this.trigger(\"executedMiddleware\");\n\n this.log(\"Request middlewares executed\", \"success\");\n\n return output;\n }\n }\n\n this.log(\"Request middlewares executed\", \"success\");\n\n // trigger the executedMiddleware event\n this.trigger(\"executedMiddleware\", middlewares, this.route);\n }\n\n /**\n * Gather the middleware list for the current route — today just the\n * route-level array; future extraction may merge group + app-wide layers.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected collectMiddlewares(): Middleware[] {\n const middlewaresList: Middleware[] = [];\n\n // collect route middlewares\n if (this.route.middleware) {\n middlewaresList.push(...this.route.middleware);\n }\n\n return middlewaresList;\n }\n\n /**\n * Get request input value from query string, params or body\n */\n public input(key: string, defaultValue?: any) {\n return get(this.payload.all, key, defaultValue);\n }\n\n /**\n * Get email input value, this will lowercase the value\n */\n public email(key: string = \"email\", defaultValue: string = \"\"): string {\n return this.input(key, defaultValue)?.toLowerCase() || defaultValue;\n }\n\n /**\n * @alias input\n */\n public get(key: string, defaultValue?: any) {\n return this.input(key, defaultValue);\n }\n\n /**\n * Determine if request has input value\n */\n public has(key: string) {\n return get(this.payload.all, key, undefined) !== undefined;\n }\n\n /**\n * Set request input value\n */\n public set(key: string, value: any) {\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Set the given value if the request does not have the input\n */\n public setDefault(key: string, value: any) {\n if (this.has(key)) return this;\n\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Unset request payload keys\n */\n public unset(...keys: string[]) {\n this.payload.all = unset(this.payload.all, keys);\n\n return this;\n }\n\n /**\n * Get request body\n */\n public get body() {\n return this.payload.body;\n }\n\n /**\n * Set request body value\n */\n public setBody(key: string, value: any) {\n set(this.payload.body, key, value);\n\n return this;\n }\n\n /**\n * Get body inputs except files\n */\n public get bodyInputs() {\n const inputs = this.payload.body;\n\n const bodyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (value.file && value.fieldname) continue;\n\n bodyInputs[key] = value;\n }\n\n return bodyInputs;\n }\n\n /**\n * Get request file in UploadedFile instance\n */\n public file(key: string): UploadedFile | undefined {\n const file = this.input(key);\n\n return file;\n }\n\n /**\n * Get uploaded files from the request for the given name\n * If the given name is not present in the request, return an empty array\n */\n public files(name: string): UploadedFile[] {\n return this.input(name) || [];\n }\n\n /**\n * Get request params\n */\n public get params() {\n return this.payload.params;\n }\n\n /**\n * Set request params value\n */\n public setParam(key: string, value: any) {\n set(this.payload.params, key, value);\n\n return this;\n }\n\n /**\n * Get request query\n */\n public get query() {\n return this.payload.query;\n }\n\n /**\n * Set request query value\n */\n public setQuery(key: string, value: any) {\n set(this.payload.query, key, value);\n\n return this;\n }\n\n /**\n * Get all inputs\n */\n public all() {\n return this.payload.all;\n }\n\n /**\n * Get all inputs except params\n */\n public allExceptParams() {\n return {\n ...this.payload.query,\n ...this.payload.body,\n };\n }\n\n /**\n * Get all heavy inputs except params\n */\n public heavyExceptParams() {\n const inputs = this.allExceptParams();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only heavy inputs, the input with a value\n */\n public heavy() {\n const inputs = this.all();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only the given keys from the request data\n */\n public only(keys: string[]) {\n return only(this.all(), keys);\n }\n\n /**\n * Pluck the given keys from the request data\n */\n public pluck(keys: string[]) {\n const data = this.only(keys);\n\n this.unset(...keys);\n\n return data;\n }\n\n /**\n * Get all request inputs except the given keys\n */\n public except(keys: string[]) {\n return except(this.all(), keys);\n }\n\n /**\n * Get boolean input value\n */\n public bool(key: string, defaultValue = false) {\n const value = this.input(key, defaultValue);\n\n if (value === \"true\") {\n return true;\n }\n\n if (value === \"false\") {\n return false;\n }\n\n if (value === 0) {\n return false;\n }\n\n return Boolean(value);\n }\n\n /**\n * Get integer input value\n */\n public int(key: string, defaultValue: number = 0): number | undefined {\n const value = this.input(key, defaultValue);\n\n if (!value && value !== 0) return undefined;\n\n return parseInt(value);\n }\n\n /**\n * Shorthand getter to get id param\n */\n public get idParam() {\n return this.int(\"id\");\n }\n\n /**\n * Get string input value\n */\n public string(key: string, defaultValue: string = \"\"): string {\n const value = this.input(key, defaultValue);\n\n return String(value);\n }\n\n /**\n * Get float input value\n */\n public float(key: string, defaultValue: number = 0): number {\n const value = this.input(key, defaultValue);\n\n return parseFloat(value) || 0;\n }\n\n /**\n * Get number input value\n */\n public number(key: string, defaultValue: number = 0): number {\n const value = Number(this.input(key, defaultValue));\n\n return isNaN(value) ? defaultValue : value;\n }\n\n /**\n * Immediate-peer IP as Fastify reports it — the address that connected to\n * the server socket, with `trustProxy` resolution applied. Use this when\n * you specifically need the peer address (rate-limit-by-direct-connection,\n * health-check origin verification).\n *\n * **For most use cases prefer `request.detectIp()`** — behind any proxy\n * (load balancer, CDN, sidecar) `ip` reports the proxy, not the real client.\n */\n public get ip() {\n return this.baseRequest.ip;\n }\n\n /**\n * Best-effort real client IP — the value everything IP-scoped keys on\n * (ip-filter allowlists, rate-limit buckets, idempotency scoping).\n *\n * `X-Forwarded-For` resolution is **delegated to Fastify**: `baseRequest.ip`\n * is already the client address Fastify's `trustProxy` machinery picked out\n * of the chain, so every shape `http.trustProxy` accepts is honoured here\n * with exactly the semantics Fastify documents:\n *\n * - `false` (default) — no header is trusted; the socket peer address wins.\n * Both forwarding headers are client-settable, so without a trusted edge\n * that rewrites them any client could otherwise forge its own IP.\n * - `true` — the whole chain is trusted; the leftmost hop (original client)\n * wins.\n * - `number` — that many rightmost hops are trusted, so an edge that\n * APPENDS to `X-Forwarded-For` yields the real client rather than whatever\n * the client prepended.\n * - CIDR / IP list (string, comma-separated string, or array) or a custom\n * predicate — the chain is walked right-to-left and stops at the first hop\n * that isn't a trusted proxy.\n *\n * `X-Real-IP` is NOT part of that resolution — Fastify never looks at it,\n * and unlike `X-Forwarded-For` it carries no chain, so there is nothing to\n * validate a proxy allowlist against. It is therefore honoured\n * only under `trustProxy: true` (\"everything upstream is mine\"), where it is\n * no weaker than the trust already granted. Under a bounded `trustProxy`\n * (CIDR / IP list) it is ignored: a trusted-but-passthrough edge that\n * forwards the client's own `X-Real-IP` verbatim would otherwise hand any\n * client a way around the bound.\n *\n * **Prefer this over `request.ip` for any caller behind a proxy** (load\n * balancer, CDN, reverse proxy, k8s ingress).\n */\n public detectIp() {\n // Trusting `X-Real-IP` is only sound when the config trusts the entire\n // upstream chain; bounded shapes get chain-aware resolution instead.\n // Typed as `unknown`: config.get(key, fallback) infers the FALLBACK's type, so\n // the literal `false` narrowed this to `false` and TypeScript called the\n // comparison unreachable. The stored value is genuinely unconstrained at compile\n // time - trustProxy accepts a boolean, a CIDR list or a predicate - so `unknown`\n // is what it actually is, and the === true check is the narrowing.\n const trustProxy: unknown = config.get(\"http.trustProxy\", false);\n\n if (trustProxy === true) {\n const realIp = this.header(\"x-real-ip\");\n\n if (realIp) {\n // `split` always yields a first element, so `?? \"\"` changes nothing —\n // and an empty address is already falsy, so it falls through to the\n // next source exactly as a blank header does. This is the CLIENT IP\n // used for rate limiting and logging; it must never become the string\n // \"undefined\".\n const address = (String(realIp).split(\",\")[0] ?? \"\").trim();\n\n if (address) return address;\n }\n }\n\n // Fastify resolved this against the configured `trustProxy` already:\n // socket peer when trust is off, the correct hop of `X-Forwarded-For`\n // when it is on. Re-parsing the header here would mean a second, weaker\n // trust model that could disagree with `request.ip` and with the plugins\n // (rate limit, proxy) that key on it.\n return this.baseRequest.ip;\n }\n\n /**\n * An alias to detectIp\n */\n public get realIp() {\n return this.detectIp();\n }\n\n /**\n * Get request ips\n */\n public get ips() {\n return this.baseRequest.ips;\n }\n\n /**\n * Get request referer\n */\n public get referer() {\n return this.baseRequest.headers.referer;\n }\n\n /**\n * Get user agent\n */\n public get userAgent() {\n return this.baseRequest.headers[\"user-agent\"];\n }\n\n /**\n * Get request headers\n */\n public get headers(): typeof this.baseRequest.headers {\n return this.baseRequest.headers;\n }\n\n /**\n * Set the given header\n */\n public setHeader(key: HeaderKeys, value: string) {\n this.baseRequest.headers[key.toLowerCase()] = value;\n\n return this;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8BA,IAAa,UAAb,MAAa,QAAiC;;iBA+BnB,CAAC;gBA4FK,CAAC;eA8DS;WAKJ;iBAejB;YAUR,OAAO,OAAO,EAAE;mBAKT,KAAK,IAAI;;;;;;;;;CA/K5B,IAAW,qBAAqD;EAC9D,OAAO,KAAK;CACd;CAEA,IAAW,mBAAmB,OAAuC;EACnE,KAAK,sBAAsB;EAC3B,KAAK,OAAO,cAAc;CAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCA,IAAW,OAAgC;EACzC,OAAO,KAAK;CACd;CAEA,IAAW,KAAK,OAAgC;EAC9C,KAAK,QAAQ;EACb,KAAK,OAAO,cAAc;CAC5B;;;;;;;;;;;;CA2CA,AAAO,mBAAyB;EAC9B,KAAK,OAAO;CACd;;;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