@warlock.js/core 5.13.0 → 5.15.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/esm/application/application-config-types.d.mts +9 -0
  3. package/esm/application/application-config-types.d.mts.map +1 -1
  4. package/esm/application/index.d.mts +2 -1
  5. package/esm/application/index.mjs +1 -0
  6. package/esm/application/public-url.d.mts +20 -0
  7. package/esm/application/public-url.d.mts.map +1 -0
  8. package/esm/application/public-url.mjs +26 -0
  9. package/esm/application/public-url.mjs.map +1 -0
  10. package/esm/cli/commands/build.command.mjs.map +1 -1
  11. package/esm/cli/commands/dev-server.command.mjs +2 -0
  12. package/esm/cli/commands/dev-server.command.mjs.map +1 -1
  13. package/esm/dev-server/files-watcher.mjs +6 -3
  14. package/esm/dev-server/files-watcher.mjs.map +1 -1
  15. package/esm/errors/esbuild-binary-missing-error.mjs +20 -0
  16. package/esm/errors/esbuild-binary-missing-error.mjs.map +1 -0
  17. package/esm/generations/features/bull-board.feature.mjs +65 -0
  18. package/esm/generations/features/bull-board.feature.mjs.map +1 -0
  19. package/esm/generations/features/index.mjs +4 -0
  20. package/esm/generations/features/index.mjs.map +1 -1
  21. package/esm/generations/features/queue.feature.mjs +4 -1
  22. package/esm/generations/features/queue.feature.mjs.map +1 -1
  23. package/esm/generations/features/shared/insert-connector-entry.mjs +68 -0
  24. package/esm/generations/features/shared/insert-connector-entry.mjs.map +1 -0
  25. package/esm/generations/features/shared/insert-queue-dashboard-block.mjs +55 -0
  26. package/esm/generations/features/shared/insert-queue-dashboard-block.mjs.map +1 -0
  27. package/esm/generations/features/sitemap.feature.mjs +74 -0
  28. package/esm/generations/features/sitemap.feature.mjs.map +1 -0
  29. package/esm/generations/features/web.feature.mjs +4 -1
  30. package/esm/generations/features/web.feature.mjs.map +1 -1
  31. package/esm/generations/stubs.mjs +4 -4
  32. package/esm/generations/stubs.mjs.map +1 -1
  33. package/esm/http/errors/errors.d.mts +16 -1
  34. package/esm/http/errors/errors.d.mts.map +1 -1
  35. package/esm/http/errors/errors.mjs +19 -1
  36. package/esm/http/errors/errors.mjs.map +1 -1
  37. package/esm/http/index.d.mts +1 -1
  38. package/esm/http/index.mjs +1 -1
  39. package/esm/http/middleware/cache-response-middleware.d.mts +12 -0
  40. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  41. package/esm/http/middleware/cache-response-middleware.mjs +15 -3
  42. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  43. package/esm/http/request.d.mts +8 -0
  44. package/esm/http/request.d.mts.map +1 -1
  45. package/esm/http/request.mjs +13 -1
  46. package/esm/http/request.mjs.map +1 -1
  47. package/esm/index.d.mts +3 -2
  48. package/esm/index.mjs +3 -2
  49. package/esm/production/esbuild-preflight.mjs +23 -13
  50. package/esm/production/esbuild-preflight.mjs.map +1 -1
  51. package/llms-full.txt +82 -6
  52. package/llms.txt +4 -4
  53. package/package.json +11 -11
  54. package/skills/configure-app/SKILL.md +29 -2
  55. package/skills/run-app/SKILL.md +6 -2
  56. package/skills/send-response/SKILL.md +15 -1
  57. package/skills/use-localization/SKILL.md +6 -0
  58. package/skills/use-middleware/SKILL.md +24 -0
  59. package/skills/write-cli-command/SKILL.md +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cache-response-middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/cache-response-middleware.ts"],"sourcesContent":["import { except } from \"@mongez/reinforcements\";\nimport { cache } from \"@warlock.js/cache\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Middleware } from \"../../router/types\";\nimport type { Request } from \"./../request\";\nimport type { Response } from \"./../response\";\n\n/**\n * Shape persisted to the cache for a cached response. Stores the status and\n * content-type alongside the body so the HIT path can replay the response\n * faithfully via {@link Response.replay} instead of re-entering `send()`.\n */\ntype CachedResponsePayload = {\n status: number;\n data: unknown;\n contentType?: string;\n};\n\n// TODO: Add option to determine whether to cache the response or not\n// TODO: add option to determine what to be cached from the response\n// TODO: add cache middleware config options for example to set the default driver, ttl, etc\n\nexport type CacheMiddlewareOptions = {\n /**\n * Cache key\n */\n cacheKey: string | ((request: Request) => string) | ((request: Request) => Promise<string>);\n /**\n * If true, then the response will be cached based on the current locale code\n * This is useful when you have a multi-language website, and you want to cache the response based on the current locale\n *\n * @default true\n */\n withLocale?: boolean;\n /**\n * List of keys from the response object to omit from the cached response\n *\n * @default ['user']\n */\n omit?: string[];\n /**\n * Expires after number of seconds\n */\n ttl?: number;\n /**\n * Cache driver\n *\n * @see config/cache.ts: drivers object\n * @default cache manager\n */\n driver?: string;\n};\n\nconst defaultCacheOptions: Partial<CacheMiddlewareOptions> = {\n withLocale: true,\n};\n\ntype ParsedCacheOptions = Required<CacheMiddlewareOptions> & {\n cacheKey: string;\n};\n\nasync function parseCacheOptions(cacheOptions: CacheMiddlewareOptions | string, request: Request) {\n if (typeof cacheOptions === \"string\") {\n cacheOptions = {\n cacheKey: cacheOptions,\n };\n }\n\n if (typeof cacheOptions.cacheKey === \"function\") {\n cacheOptions.cacheKey = await cacheOptions.cacheKey(request);\n }\n\n const finalCacheOptions = {\n ...defaultCacheOptions,\n ...cacheOptions,\n } as ParsedCacheOptions;\n\n if (finalCacheOptions.withLocale) {\n const locale = request.getLocaleCode();\n\n finalCacheOptions.cacheKey = `${finalCacheOptions.cacheKey}:${locale}`;\n }\n\n if (!finalCacheOptions.omit) {\n finalCacheOptions.omit = [\"user\", \"settings\"];\n }\n\n return finalCacheOptions;\n}\n\nexport function cacheMiddleware(responseCacheOptions: CacheMiddlewareOptions | string): Middleware {\n // The `Middleware` return annotation is load-bearing: without it, tsc never\n // checks this factory's calling convention, which is how the positional v4\n // shape survived an earlier refactor unnoticed.\n return async function ({ request, response }) {\n const { ttl, omit, cacheKey, driver } = await parseCacheOptions(responseCacheOptions, request);\n const cacheDriver = driver ? await cache.use(driver) : cache;\n\n const content = (await cacheDriver.get(cacheKey)) as CachedResponsePayload | null;\n\n if (content) {\n // Replay through the standard pipeline (status + content-type preserved)\n // instead of `baseResponse.send()`, which would re-enter Response.send()\n // on an already-sent reply, trip the double-send guard, and drop the\n // status / content-type.\n return response.replay({\n status: content.status ?? 200,\n body: content.data,\n contentType: content.contentType,\n });\n }\n\n response.onSent((response: Response) => {\n if (!response.isOk || response.request.path !== request.path) {\n return;\n }\n\n const sentContentType = response.contentType;\n\n const content: CachedResponsePayload = {\n status: response.statusCode,\n data: except(response.parsedBody, omit),\n contentType: typeof sentContentType === \"string\" ? sentContentType : undefined,\n };\n\n // `set` is fire-and-forget inside `onSent`; without a `.catch` a rejected\n // write (e.g. Redis down) would surface as an unhandledRejection.\n cacheDriver.set(cacheKey, content, ttl).catch((error: unknown) => {\n log.error(\"cache-middleware\", \"set\", error);\n });\n });\n };\n}\n"],"mappings":";;;;;AAqDA,MAAM,sBAAuD,EAC3D,YAAY,KACd;AAMA,eAAe,kBAAkB,cAA+C,SAAkB;CAChG,IAAI,OAAO,iBAAiB,UAC1B,eAAe,EACb,UAAU,aACZ;CAGF,IAAI,OAAO,aAAa,aAAa,YACnC,aAAa,WAAW,MAAM,aAAa,SAAS,OAAO;CAG7D,MAAM,oBAAoB;EACxB,GAAG;EACH,GAAG;CACL;CAEA,IAAI,kBAAkB,YAAY;EAChC,MAAM,SAAS,QAAQ,cAAc;EAErC,kBAAkB,WAAW,GAAG,kBAAkB,SAAS,GAAG;CAChE;CAEA,IAAI,CAAC,kBAAkB,MACrB,kBAAkB,OAAO,CAAC,QAAQ,UAAU;CAG9C,OAAO;AACT;AAEA,SAAgB,gBAAgB,sBAAmE;CAIjG,OAAO,eAAgB,EAAE,SAAS,YAAY;EAC5C,MAAM,EAAE,KAAK,MAAM,UAAU,WAAW,MAAM,kBAAkB,sBAAsB,OAAO;EAC7F,MAAM,cAAc,SAAS,MAAM,MAAM,IAAI,MAAM,IAAI;EAEvD,MAAM,UAAW,MAAM,YAAY,IAAI,QAAQ;EAE/C,IAAI,SAKF,OAAO,SAAS,OAAO;GACrB,QAAQ,QAAQ,UAAU;GAC1B,MAAM,QAAQ;GACd,aAAa,QAAQ;EACvB,CAAC;EAGH,SAAS,QAAQ,aAAuB;GACtC,IAAI,CAAC,SAAS,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MACtD;GAGF,MAAM,kBAAkB,SAAS;GAEjC,MAAM,UAAiC;IACrC,QAAQ,SAAS;IACjB,MAAM,OAAO,SAAS,YAAY,IAAI;IACtC,aAAa,OAAO,oBAAoB,WAAW,kBAAkB;GACvE;GAIA,YAAY,IAAI,UAAU,SAAS,GAAG,CAAC,CAAC,OAAO,UAAmB;IAChE,IAAI,MAAM,oBAAoB,OAAO,KAAK;GAC5C,CAAC;EACH,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"cache-response-middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/cache-response-middleware.ts"],"sourcesContent":["import { except } from \"@mongez/reinforcements\";\nimport { cache } from \"@warlock.js/cache\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Middleware } from \"../../router/types\";\nimport type { Request } from \"./../request\";\nimport type { Response } from \"./../response\";\n\n/**\n * Shape persisted to the cache for a cached response. Stores the status and\n * content-type alongside the body so the HIT path can replay the response\n * faithfully via {@link Response.replay} instead of re-entering `send()`.\n */\ntype CachedResponsePayload = {\n status: number;\n data: unknown;\n contentType?: string;\n};\n\n// TODO: Add option to determine whether to cache the response or not\n// TODO: add option to determine what to be cached from the response\n// TODO: add cache middleware config options for example to set the default driver, ttl, etc\n\nexport type CacheMiddlewareOptions = {\n /**\n * Cache key\n */\n cacheKey: string | ((request: Request) => string) | ((request: Request) => Promise<string>);\n /**\n * If true, then the response will be cached based on the current locale code\n * This is useful when you have a multi-language website, and you want to cache the response based on the current locale\n *\n * @default true\n */\n withLocale?: boolean;\n /**\n * List of keys from the response object to omit from the cached response\n *\n * @default ['user']\n */\n omit?: string[];\n /**\n * Expires after number of seconds\n */\n ttl?: number;\n /**\n * Cache driver\n *\n * @see config/cache.ts: drivers object\n * @default cache manager\n */\n driver?: string;\n /**\n * Tags this cached response is stored under, mirroring `route.cache.tags`\n * on `@warlock.js/web`'s page cache (`PageCacheOptIn.tags`,\n * `web/src/routing/route-identity.ts`) so the two caches share one mental\n * model: `cache.tags([...]).invalidate()` from `@warlock.js/cache` evicts\n * a tagged API response the same way it evicts a tagged page. Either a\n * static list, or a function of the request — resolved once per request,\n * right before the response is stored.\n *\n * @default undefined (untagged — behaves exactly as before this option existed)\n */\n tags?: string[] | ((request: Request) => string[]);\n};\n\nconst defaultCacheOptions: Partial<CacheMiddlewareOptions> = {\n withLocale: true,\n};\n\ntype ParsedCacheOptions = Required<Omit<CacheMiddlewareOptions, \"tags\">> & {\n cacheKey: string;\n /** Resolved, concrete tag list — see {@link resolveCacheTags}. */\n tags: string[];\n};\n\n/**\n * Resolves `CacheMiddlewareOptions.tags` — a static list or a function of\n * the request — into a concrete list at store time. Mirrors\n * `resolveCacheTags` in `@warlock.js/web`'s `create-page-route-handler.ts`,\n * the equivalent seam for `route.cache.tags`.\n */\nfunction resolveCacheTags(tags: CacheMiddlewareOptions[\"tags\"], request: Request): string[] {\n if (tags === undefined) return [];\n\n return typeof tags === \"function\" ? tags(request) : tags;\n}\n\nasync function parseCacheOptions(cacheOptions: CacheMiddlewareOptions | string, request: Request) {\n if (typeof cacheOptions === \"string\") {\n cacheOptions = {\n cacheKey: cacheOptions,\n };\n }\n\n if (typeof cacheOptions.cacheKey === \"function\") {\n cacheOptions.cacheKey = await cacheOptions.cacheKey(request);\n }\n\n const tags = resolveCacheTags(cacheOptions.tags, request);\n\n const finalCacheOptions = {\n ...defaultCacheOptions,\n ...cacheOptions,\n tags,\n } as ParsedCacheOptions;\n\n if (finalCacheOptions.withLocale) {\n const locale = request.getLocaleCode();\n\n finalCacheOptions.cacheKey = `${finalCacheOptions.cacheKey}:${locale}`;\n }\n\n if (!finalCacheOptions.omit) {\n finalCacheOptions.omit = [\"user\", \"settings\"];\n }\n\n return finalCacheOptions;\n}\n\nexport function cacheMiddleware(responseCacheOptions: CacheMiddlewareOptions | string): Middleware {\n // The `Middleware` return annotation is load-bearing: without it, tsc never\n // checks this factory's calling convention, which is how the positional v4\n // shape survived an earlier refactor unnoticed.\n return async function ({ request, response }) {\n const { ttl, omit, cacheKey, driver, tags } = await parseCacheOptions(\n responseCacheOptions,\n request,\n );\n const cacheDriver = driver ? await cache.use(driver) : cache;\n\n const content = (await cacheDriver.get(cacheKey)) as CachedResponsePayload | null;\n\n if (content) {\n // Replay through the standard pipeline (status + content-type preserved)\n // instead of `baseResponse.send()`, which would re-enter Response.send()\n // on an already-sent reply, trip the double-send guard, and drop the\n // status / content-type.\n return response.replay({\n status: content.status ?? 200,\n body: content.data,\n contentType: content.contentType,\n });\n }\n\n response.onSent((response: Response) => {\n if (!response.isOk || response.request.path !== request.path) {\n return;\n }\n\n const sentContentType = response.contentType;\n\n const content: CachedResponsePayload = {\n status: response.statusCode,\n data: except(response.parsedBody, omit),\n contentType: typeof sentContentType === \"string\" ? sentContentType : undefined,\n };\n\n // `set` is fire-and-forget inside `onSent`; without a `.catch` a rejected\n // write (e.g. Redis down) would surface as an unhandledRejection.\n //\n // Tagged and untagged writes go through separate calls rather than a\n // shared branch-free path so an untagged route's write stays byte\n // identical to what it was before `tags` existed.\n const write =\n tags.length > 0\n ? cacheDriver.tags(tags).set(cacheKey, content, ttl)\n : cacheDriver.set(cacheKey, content, ttl);\n\n write.catch((error: unknown) => {\n log.error(\"cache-middleware\", \"set\", error);\n });\n });\n };\n}\n"],"mappings":";;;;;AAiEA,MAAM,sBAAuD,EAC3D,YAAY,KACd;;;;;;;AAcA,SAAS,iBAAiB,MAAsC,SAA4B;CAC1F,IAAI,SAAS,QAAW,OAAO,CAAC;CAEhC,OAAO,OAAO,SAAS,aAAa,KAAK,OAAO,IAAI;AACtD;AAEA,eAAe,kBAAkB,cAA+C,SAAkB;CAChG,IAAI,OAAO,iBAAiB,UAC1B,eAAe,EACb,UAAU,aACZ;CAGF,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current request
249
249
  */
250
250
  get cookies(): Record<string, string | undefined>;
251
+ /**
252
+ * Assert the cookie jar exists before a by-name read. `get cookies()` stays
253
+ * lenient (returns `{}`) for the framework's own opportunistic reads, but a
254
+ * deliberate by-name read from application code must fail loudly when
255
+ * `@fastify/cookie` was never registered, rather than being indistinguishable
256
+ * from "the caller sent no such cookie".
257
+ */
258
+ private assertCookieJarAvailable;
251
259
  /**
252
260
  * Get a particular cookie value or fallback to default
253
261
  */
@@ -1 +1 @@
1
- {"version":3,"file":"request.d.mts","names":[],"sources":["../../../../../../../core/src/http/request.ts"],"mappings":";;;;;;;;;;;KAuBK,eAAA,iBAIU,mBAAA,mBAAsC,CAAA,0BAA2B,CAAA,WAAY,CAAA,GACvF,mBAAA,CAAoB,CAAA;AAAA,KAGpB,UAAA,SAAmB,eAAe;AAAA,cAE1B,OAAA;;;;;;;;;;;;;;;;;EAiBJ,WAAA,EAAc,cAAA;EAtBG;AAAA;;EA2BjB,QAAA,EAAW,QAAA;EAxBmB;AAAA;AAEvC;EA2BS,KAAA,EAAQ,KAAA;EA3BG;;;EAAA,UAgCR,OAAA;EAcuB;;;EAAA,QATzB,mBAAA;EAsHwB;;;;;;;EAAA,IA7GrB,kBAAA,IAAsB,kBAAA;EAAA,IAItB,kBAAA,CAAmB,KAAA,EAAO,kBAAA;EA0U7B;;;;;;;;;;;;;;;;;EAAA,IApTG,IAAA;EAmyBS;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA/vBb,MAAA,EAAQ,aAAA;EA8BJ;;;;EAAA,UAxBD,MAAA;EAyCsB;;;;;;;;;;;;;;;;;;;;;;EAAA,IAjBrB,KAAA;EAgKD;;;EAAA,OArJI,OAAA,EAAS,OAAA;EA+LZ;;;;EAzLJ,KAAA,EAAO,UAAA,QAAkB,KAAA;EA2MX;;;EAtMd,CAAA,EAAG,UAAA,QAAkB,KAAA;EAoNN;;;EAAA,UArMZ,OAAA;EA4MH;;;EAAA,UAvMG,aAAA,GAAgB,iBAAA;E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AA;AAAA"}
@@ -1,6 +1,6 @@
1
1
  import { config } from "../config/config-getter.mjs";
2
2
  import { LOCALE_COOKIE_NAME, resolveLocaleConfiguration } from "../config/locale-configuration.mjs";
3
- import { RequestUserMovedError } from "./errors/errors.mjs";
3
+ import { CookieJarUnavailableError, RequestUserMovedError } from "./errors/errors.mjs";
4
4
  import { deriveTraceId } from "./tracing/trace-id.mjs";
5
5
  import { buildTracingContext, dispatchPhase, isTracingEnabled } from "./tracing/tracing-dispatcher.mjs";
6
6
  import "./tracing/index.mjs";
@@ -226,9 +226,20 @@ var Request = class Request {
226
226
  return this.baseRequest.cookies || {};
227
227
  }
228
228
  /**
229
+ * Assert the cookie jar exists before a by-name read. `get cookies()` stays
230
+ * lenient (returns `{}`) for the framework's own opportunistic reads, but a
231
+ * deliberate by-name read from application code must fail loudly when
232
+ * `@fastify/cookie` was never registered, rather than being indistinguishable
233
+ * from "the caller sent no such cookie".
234
+ */
235
+ assertCookieJarAvailable(name) {
236
+ if (this.baseRequest.cookies === void 0) throw new CookieJarUnavailableError(name);
237
+ }
238
+ /**
229
239
  * Get a particular cookie value or fallback to default
230
240
  */
231
241
  cookie(name, defaultValue) {
242
+ this.assertCookieJarAvailable(name);
232
243
  const value = this.cookies[name] ?? defaultValue;
233
244
  try {
234
245
  return JSON.parse(value);
@@ -240,6 +251,7 @@ var Request = class Request {
240
251
  * Determine if the request has the specified cookie
241
252
  */
242
253
  hasCookie(name) {
254
+ this.assertCookieJarAvailable(name);
243
255
  return this.cookies[name] !== void 0;
244
256
  }
245
257
  /**
@@ -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 { Application } from \"../application/application\";\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 { RequestUserMovedError } from \"./errors\";\nimport { createRequestStore } from \"./middleware/inject-request-context\";\nimport { Response } from \"./response\";\nimport { buildTracingContext, deriveTraceId, dispatchPhase, isTracingEnabled } from \"./tracing\";\nimport type { DecodedAccessToken, RequestEvent, RequestLocals } 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.locals.user` (set by `@warlock.js/auth`), `request.detectIp()`,\n * 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 * REMOVED in 5.12.0 — the authenticated user now lives at\n * `request.locals.user`, a key `@warlock.js/auth` declares via module\n * augmentation on `RequestLocals` and writes from its middleware after a\n * successful token resolution. `RequestUser` moved out of core to\n * `@warlock.js/auth` alongside it.\n *\n * This getter is a development-time diagnostic only, kept for one release\n * so a call site that still reads `request.user` fails loudly at runtime\n * instead of silently reading `undefined`. It is typed `never` so it\n * cannot reintroduce an auth-shaped type into core, and it throws\n * unconditionally outside production so the failure is impossible to miss\n * in local dev — see `RequestUserMovedError`.\n *\n * There is no setter: nothing in core or downstream packages should ever\n * assign to `request.user` again.\n */\n public get user(): never {\n if (Application.isDevelopment) {\n throw new RequestUserMovedError();\n }\n\n return undefined as never;\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 * 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 * Trace id. The inbound `traceparent` header's trace id\n * when valid, otherwise `id`. Resolved once in `setRequest`, alongside\n * `id` itself — see `resolveTraceId`.\n */\n public traceId = \"\";\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.resolveTraceId();\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 * Derive `traceId`: the inbound\n * `traceparent` header's trace id when it is a valid W3C traceparent,\n * otherwise `id`. Always runs — unlike request-id inheritance this has no\n * `enabled: false` escape hatch, since `traceId` is only ever read when\n * tracing hooks are enabled (see `./tracing`).\n */\n protected resolveTraceId() {\n const header = this.baseRequest.headers.traceparent;\n const traceparent = Array.isArray(header) ? header[0] : header;\n\n this.traceId = deriveTraceId(traceparent, this.id);\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 — timed as\n // the \"validation\" tracing phase when tracing is\n // enabled; a single boolean check and zero allocation otherwise.\n const tracingEnabled = isTracingEnabled();\n const validationStartedAt = tracingEnabled ? performance.now() : 0;\n\n const validationOutput = await validateAll(handler.validation, this, this.response);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"validation\",\n durationMs: performance.now() - validationStartedAt,\n });\n }\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 const tracingEnabled = isTracingEnabled();\n\n for (const [index, middleware] of middlewares.entries()) {\n this.log(\"Executing middleware \" + colors.yellowBright(middleware.name));\n\n const middlewareStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await middleware({\n request: this,\n response: this.response,\n });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"middleware\",\n durationMs: performance.now() - middlewareStartedAt,\n attrs: { name: middleware.name, index },\n });\n }\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":";;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,UAAb,MAAa,QAAiC;;iBAgCnB,CAAC;gBA4EK,CAAC;eA+CS;WAKJ;iBAejB;YAUR,OAAO,OAAO,EAAE;iBAOX;mBAKE,KAAK,IAAI;;;;;;;;;CAvJ5B,IAAW,qBAAqD;EAC9D,OAAO,KAAK;CACd;CAEA,IAAW,mBAAmB,OAAuC;EACnE,KAAK,sBAAsB;EAC3B,KAAK,OAAO,cAAc;CAC5B;;;;;;;;;;;;;;;;;;CAmBA,IAAW,OAAc;EACvB,IAAI,YAAY,eACd,MAAM,IAAI,sBAAsB;CAIpC;;;;;;;;;;;;;;;;;;;;;;;CA4DA,IAAW,QAAgB;EACzB,IAAI,CAAC,KAAK,QACR,KAAK,SAAS,YAAY,EAAE,CAAC,CAAC,SAAS,QAAQ;EAGjD,OAAO,KAAK;CACd;;;;CA+DA,AAAO,WAAW,SAAyB;EACzC,KAAK,cAAc;EAEnB,KAAK,iBAAiB;EAEtB,KAAK,eAAe;EAEpB,KAAK,aAAa;EAOlB,KAAK,QAAQ,KAAK,KAAK,SAAiB,iBACtC,UAAU,KAAK,cAAc,GAAG,SAAS,YAAY;EAEvD,OAAO;CACT;;;;;;;;;;CAWA,AAAU,mBAAmB;EAC3B,MAAM,kBAAkB,OAAO,IAAI,gBAAgB,KAAK,CAAC;EAEzD,IAAI,gBAAgB,YAAY,OAAO;EAEvC,MAAM,cAAc,gBAAgB,UAAU,eAAc,CAAE,YAAY;EAC1E,MAAM,WAAW,KAAK,YAAY,QAAQ;E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,KAAa,eAAuB,IAAY;EAC5D,MAAM,QAAQ,KAAK,MAAM,KAAK,YAAY;EAE1C,OAAO,OAAO,KAAK;CACrB;;;;CAKA,AAAO,MAAM,KAAa,eAAuB,GAAW;EAC1D,MAAM,QAAQ,KAAK,MAAM,KAAK,YAAY;EAE1C,OAAO,WAAW,KAAK,KAAK;CAC9B;;;;CAKA,AAAO,OAAO,KAAa,eAAuB,GAAW;EAC3D,MAAM,QAAQ,OAAO,KAAK,MAAM,KAAK,YAAY,CAAC;EAElD,OAAO,MAAM,KAAK,IAAI,eAAe;CACvC;;;;;;;;;;CAWA,IAAW,KAAK;EACd,OAAO,KAAK,YAAY;CAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCA,AAAO,WAAW;EAUhB,IAF4B,OAAO,IAAI,mBAAmB,KAE7C,MAAM,MAAM;GACvB,MAAM,SAAS,KAAK,OAAO,WAAW;GAEtC,IAAI,QAAQ;IAMV,MAAM,WAAW,OAAO,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,GAAE,CAAE,KAAK;IAE1D,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 { Application } from \"../application/application\";\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 { CookieJarUnavailableError, RequestUserMovedError } from \"./errors\";\nimport { createRequestStore } from \"./middleware/inject-request-context\";\nimport { Response } from \"./response\";\nimport { buildTracingContext, deriveTraceId, dispatchPhase, isTracingEnabled } from \"./tracing\";\nimport type { DecodedAccessToken, RequestEvent, RequestLocals } 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.locals.user` (set by `@warlock.js/auth`), `request.detectIp()`,\n * 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 * REMOVED in 5.12.0 — the authenticated user now lives at\n * `request.locals.user`, a key `@warlock.js/auth` declares via module\n * augmentation on `RequestLocals` and writes from its middleware after a\n * successful token resolution. `RequestUser` moved out of core to\n * `@warlock.js/auth` alongside it.\n *\n * This getter is a development-time diagnostic only, kept for one release\n * so a call site that still reads `request.user` fails loudly at runtime\n * instead of silently reading `undefined`. It is typed `never` so it\n * cannot reintroduce an auth-shaped type into core, and it throws\n * unconditionally outside production so the failure is impossible to miss\n * in local dev — see `RequestUserMovedError`.\n *\n * There is no setter: nothing in core or downstream packages should ever\n * assign to `request.user` again.\n */\n public get user(): never {\n if (Application.isDevelopment) {\n throw new RequestUserMovedError();\n }\n\n return undefined as never;\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 * 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 * Trace id. The inbound `traceparent` header's trace id\n * when valid, otherwise `id`. Resolved once in `setRequest`, alongside\n * `id` itself — see `resolveTraceId`.\n */\n public traceId = \"\";\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.resolveTraceId();\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 * Derive `traceId`: the inbound\n * `traceparent` header's trace id when it is a valid W3C traceparent,\n * otherwise `id`. Always runs — unlike request-id inheritance this has no\n * `enabled: false` escape hatch, since `traceId` is only ever read when\n * tracing hooks are enabled (see `./tracing`).\n */\n protected resolveTraceId() {\n const header = this.baseRequest.headers.traceparent;\n const traceparent = Array.isArray(header) ? header[0] : header;\n\n this.traceId = deriveTraceId(traceparent, this.id);\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 * Assert the cookie jar exists before a by-name read. `get cookies()` stays\n * lenient (returns `{}`) for the framework's own opportunistic reads, but a\n * deliberate by-name read from application code must fail loudly when\n * `@fastify/cookie` was never registered, rather than being indistinguishable\n * from \"the caller sent no such cookie\".\n */\n private assertCookieJarAvailable(name: string): void {\n if (this.baseRequest.cookies === undefined) {\n throw new CookieJarUnavailableError(name);\n }\n }\n\n /**\n * Get a particular cookie value or fallback to default\n */\n public cookie(name: string, defaultValue?: any): string | any {\n this.assertCookieJarAvailable(name);\n\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 this.assertCookieJarAvailable(name);\n\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 — timed as\n // the \"validation\" tracing phase when tracing is\n // enabled; a single boolean check and zero allocation otherwise.\n const tracingEnabled = isTracingEnabled();\n const validationStartedAt = tracingEnabled ? performance.now() : 0;\n\n const validationOutput = await validateAll(handler.validation, this, this.response);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"validation\",\n durationMs: performance.now() - validationStartedAt,\n });\n }\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 const tracingEnabled = isTracingEnabled();\n\n for (const [index, middleware] of middlewares.entries()) {\n this.log(\"Executing middleware \" + colors.yellowBright(middleware.name));\n\n const middlewareStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await middleware({\n request: this,\n response: this.response,\n });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"middleware\",\n durationMs: performance.now() - middlewareStartedAt,\n attrs: { name: middleware.name, index },\n });\n }\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":";;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,UAAb,MAAa,QAAiC;;iBAgCnB,CAAC;gBA4EK,CAAC;eA+CS;WAKJ;iBAejB;YAUR,OAAO,OAAO,EAAE;iBAOX;mBAKE,KAAK,IAAI;;;;;;;;;CAvJ5B,IAAW,qBAAqD;EAC9D,OAAO,KAAK;CACd;CAEA,IAAW,mBAAmB,OAAuC;EACnE,KAAK,sBAAsB;EAC3B,KAAK,OAAO,cAAc;CAC5B;;;;;;;;;;;;;;;;;;CAmBA,IAAW,OAAc;EACvB,IAAI,YAAY,eACd,MAAM,IAAI,sBAAsB;CAIpC;;;;;;;;;;;;;;;;;;;;;;;CA4DA,IAAW,QAAgB;EACzB,IAAI,CAAC,KAAK,QACR,KAAK,SAAS,YAAY,EAAE,CAAC,CAAC,SA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,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,GAAE,CAAE,KAAK;IAE1D,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"}
package/esm/index.d.mts CHANGED
@@ -32,7 +32,7 @@ import { logResponse, wrapResponseInDataKey } from "./http/events.mjs";
32
32
  import { HealthCheck, HealthStatus, health } from "./http/health.mjs";
33
33
  import { RequestController } from "./http/request-controller.mjs";
34
34
  import { UPLOADS_DEFAULTS, uploadsConfig } from "./http/uploads-config.mjs";
35
- import { BadRequestError, ConflictError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
35
+ import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
36
36
  import { CacheMiddlewareOptions } from "./http/middleware/cache-response-middleware.mjs";
37
37
  import { ConcurrencyLimitOptions } from "./http/middleware/concurrency-limit.middleware.mjs";
38
38
  import { IdempotencyOptions } from "./http/middleware/idempotency.middleware.mjs";
@@ -67,6 +67,7 @@ import { Environment, RuntimeStrategy, environment, setEnvironment } from "./uti
67
67
  import { Application, BootContext, BootListener, BootValidator, ShutdownListener } from "./application/application.mjs";
68
68
  import { BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BootSignal, BootSignalType, isBootSignal, sendBootSignal } from "./application/boot-signal.mjs";
69
69
  import { AppConfigurations } from "./application/application-config-types.mjs";
70
+ import { getPublicUrl } from "./application/public-url.mjs";
70
71
  import { BenchmarkSnapshots } from "./benchmark/benchmark-snapshots.mjs";
71
72
  import { BenchmarkProfiler } from "./benchmark/profiler.mjs";
72
73
  import { BenchmarkChannel, BenchmarkConfigurations, BenchmarkErrorResult, BenchmarkOptions, BenchmarkProfilerOptions, BenchmarkResult, BenchmarkSnapshotsOptions, BenchmarkStats, BenchmarkSuccessResult } from "./benchmark/types.mjs";
@@ -166,7 +167,7 @@ import { WarlockConfigManager, isUnknownTsExtensionError, warlockConfigManager }
166
167
  import { env } from "@mongez/dotenv";
167
168
  import { colors } from "@mongez/copper";
168
169
  export * from "@mongez/localization";
169
- export { $registerUseCase, $unregisterUseCase, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieOptions, CspConfig, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, HttpTracingConfig, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, InvalidCspDirectiveError, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, Middleware, MiddlewareResponse, MimeTypes, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, PaginationMode, PaginationResult, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestMethod, RequestUserMovedError, type ResolvedCLICommandOption, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, ServerError, ShutdownListener, SocketConnector, SocketOptions, Storage, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadsConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, WarlockConfig, WarlockConfigManager, WatermarkConfig, WhereOperator, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
170
+ export { $registerUseCase, $unregisterUseCase, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, HttpTracingConfig, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, InvalidCspDirectiveError, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, Middleware, MiddlewareResponse, MimeTypes, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, PaginationMode, PaginationResult, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestMethod, RequestUserMovedError, type ResolvedCLICommandOption, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, ServerError, ShutdownListener, SocketConnector, SocketOptions, Storage, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadsConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, WarlockConfig, WarlockConfigManager, WatermarkConfig, WhereOperator, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
170
171
  import "./config/types.mjs";
171
172
  import "./http/request.mjs";
172
173
  import "./http/types.mjs";
package/esm/index.mjs CHANGED
@@ -21,7 +21,7 @@ import { assetsUrl, publicUrl, setBaseUrl, uploadsUrl, url } from "./utils/urls.
21
21
  import { isNewerVersion } from "./utils/version-compare.mjs";
22
22
  import "./utils/index.mjs";
23
23
  import { DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, buildCspHeaderValue, mergeCspDirectives, resolveCspConfig, serializeCspDirectives, validateCspConfigAtBoot, validateCspDirectives } from "./http/csp.mjs";
24
- import { BadRequestError, ConflictError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
24
+ import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
25
25
  import { deriveTraceId, parseTraceparentTraceId } from "./http/tracing/trace-id.mjs";
26
26
  import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
27
27
  import { createRequestStore, t } from "./http/middleware/inject-request-context.mjs";
@@ -66,6 +66,7 @@ import { RequestLog } from "./http/database/RequestLog.mjs";
66
66
  import { HttpErrorCodes } from "./http/error-codes.mjs";
67
67
  import { logResponse, wrapResponseInDataKey } from "./http/events.mjs";
68
68
  import { app } from "./application/app.mjs";
69
+ import { getPublicUrl } from "./application/public-url.mjs";
69
70
  import "./application/index.mjs";
70
71
  import { health } from "./http/health.mjs";
71
72
  import { RequestController } from "./http/request-controller.mjs";
@@ -163,4 +164,4 @@ import { colors } from "@mongez/copper";
163
164
 
164
165
  export * from "@mongez/localization"
165
166
 
166
- export { $registerUseCase, $unregisterUseCase, AccessConnector, AiConnector, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, InvalidCspDirectiveError, LocalDriver, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, RequestUserMovedError, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageConnector, StorageError, StorageFile, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
167
+ export { $registerUseCase, $unregisterUseCase, AccessConnector, AiConnector, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, InvalidCspDirectiveError, LocalDriver, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, RequestUserMovedError, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageConnector, StorageError, StorageFile, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
@@ -1,3 +1,4 @@
1
+ import { EsbuildBinaryMissingError } from "../errors/esbuild-binary-missing-error.mjs";
1
2
  import esbuild from "esbuild";
2
3
 
3
4
  //#region ../core/src/production/esbuild-preflight.ts
@@ -13,24 +14,33 @@ import esbuild from "esbuild";
13
14
  */
14
15
  const UNLINKED_BINARY_SIGNATURE = "could not be found, and is needed by esbuild";
15
16
  /**
16
- * Fail fast, before bundling, when esbuild's native binary is not linked.
17
+ * The default probe: a trivial `transformSync` call. Trivial input keeps the
18
+ * cost negligible while still forcing esbuild to resolve and run its native
19
+ * binary, which is the only way an unlinked binary actually surfaces.
20
+ */
21
+ function runDefaultProbe() {
22
+ esbuild.transformSync("", { loader: "js" });
23
+ }
24
+ /**
25
+ * Fail fast, before dev or build does any other work, when esbuild's native
26
+ * binary is not linked.
17
27
  *
18
- * Runs a single trivial `transformSync` call the cheapest operation that
19
- * forces esbuild to resolve its platform binary so it adds no measurable
20
- * delay to `warlock build`. Only called from the production build path;
21
- * never from `warlock dev`.
28
+ * A healthy esbuild install is a no-op. A binary genuinely missing — because
29
+ * a platform package was never installed, or a package manager blocked its
30
+ * postinstall script is turned into {@link EsbuildBinaryMissingError}, a
31
+ * message that names the cause and the fix. Any other failure (a real syntax
32
+ * error, an unrelated platform mismatch, …) is rethrown unchanged — this
33
+ * preflight only owns the one known failure mode.
22
34
  *
23
- * A healthy esbuild install is a no-op. A binary genuinely missing because
24
- * pnpm blocked its postinstall script is turned into a message that names
25
- * the cause and the fix. Any other failure (a real syntax error, a platform
26
- * mismatch, …) is rethrown unchanged — this preflight only owns the one
27
- * known failure mode.
35
+ * @param probe Overrides the default `esbuild.transformSync` invocation.
36
+ * Intended for tests only.
37
+ * @throws {EsbuildBinaryMissingError} when the platform binary is missing or unlinked.
28
38
  */
29
- function assertEsbuildBinaryIsLinked() {
39
+ function assertEsbuildBinaryIsLinked(probe = runDefaultProbe) {
30
40
  try {
31
- esbuild.transformSync("", { loader: "js" });
41
+ probe();
32
42
  } catch (error) {
33
- if (isUnlinkedBinaryError(error)) throw new Error("esbuild's native binary is not installed for this platform, so `warlock build` cannot bundle.\n\nThis usually happens when pnpm's build-script approval gate blocked esbuild's postinstall script, so the platform binary was never linked. Fix it with:\n\n pnpm approve-builds\n\nthen reinstall, or reinstall dependencies with build scripts enabled if esbuild was excluded on purpose.");
43
+ if (isUnlinkedBinaryError(error)) throw new EsbuildBinaryMissingError({ cause: error });
34
44
  throw error;
35
45
  }
36
46
  }
@@ -1 +1 @@
1
- {"version":3,"file":"esbuild-preflight.mjs","names":[],"sources":["../../../../../../../core/src/production/esbuild-preflight.ts"],"sourcesContent":["import esbuild from \"esbuild\";\n\n/**\n * The exact substring esbuild's own loader throws when the platform-specific\n * binary package (e.g. `@esbuild/win32-x64`) never got installed. This is\n * the signature pnpm's build-script approval gate leaves behind: it blocks\n * esbuild's postinstall script, so the binary is never linked into place,\n * and any later call into esbuild dies with this message instead of a\n * project-shaped one.\n *\n * Source: `pkgAndSubpathForCurrentPlatform` in esbuild's `lib/main.js`.\n */\nconst UNLINKED_BINARY_SIGNATURE = \"could not be found, and is needed by esbuild\";\n\n/**\n * Fail fast, before bundling, when esbuild's native binary is not linked.\n *\n * Runs a single trivial `transformSync` call the cheapest operation that\n * forces esbuild to resolve its platform binary so it adds no measurable\n * delay to `warlock build`. Only called from the production build path;\n * never from `warlock dev`.\n *\n * A healthy esbuild install is a no-op. A binary genuinely missing because\n * pnpm blocked its postinstall script is turned into a message that names\n * the cause and the fix. Any other failure (a real syntax error, a platform\n * mismatch, …) is rethrown unchanged — this preflight only owns the one\n * known failure mode.\n */\nexport function assertEsbuildBinaryIsLinked(): void {\n try {\n esbuild.transformSync(\"\", { loader: \"js\" });\n } catch (error) {\n if (isUnlinkedBinaryError(error)) {\n throw new Error(\n \"esbuild's native binary is not installed for this platform, so \" +\n \"`warlock build` cannot bundle.\\n\\n\" +\n \"This usually happens when pnpm's build-script approval gate \" +\n \"blocked esbuild's postinstall script, so the platform binary \" +\n \"was never linked. Fix it with:\\n\\n\" +\n \" pnpm approve-builds\\n\\n\" +\n \"then reinstall, or reinstall dependencies with build scripts \" +\n \"enabled if esbuild was excluded on purpose.\",\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Narrow an unknown thrown value down to esbuild's known \"binary not\n * linked\" failure, identified by the fixed substring esbuild itself throws.\n */\nfunction isUnlinkedBinaryError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(UNLINKED_BINARY_SIGNATURE);\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,4BAA4B;;;;;;;;;;;;;;;AAgBlC,SAAgB,8BAAoC;CAClD,IAAI;EACF,QAAQ,cAAc,IAAI,EAAE,QAAQ,KAAK,CAAC;CAC5C,SAAS,OAAO;EACd,IAAI,sBAAsB,KAAK,GAC7B,MAAM,IAAI,MACR,+XAQF;EAGF,MAAM;CACR;AACF;;;;;AAMA,SAAS,sBAAsB,OAAyB;CACtD,OAAO,iBAAiB,SAAS,MAAM,QAAQ,SAAS,yBAAyB;AACnF"}
1
+ {"version":3,"file":"esbuild-preflight.mjs","names":[],"sources":["../../../../../../../core/src/production/esbuild-preflight.ts"],"sourcesContent":["import esbuild from \"esbuild\";\nimport { EsbuildBinaryMissingError } from \"../errors/esbuild-binary-missing-error\";\n\nexport { EsbuildBinaryMissingError };\n\n/**\n * The exact substring esbuild's own loader throws when the platform-specific\n * binary package (e.g. `@esbuild/win32-x64`) never got installed. This is\n * the signature pnpm's build-script approval gate leaves behind: it blocks\n * esbuild's postinstall script, so the binary is never linked into place,\n * and any later call into esbuild dies with this message instead of a\n * project-shaped one.\n *\n * Source: `pkgAndSubpathForCurrentPlatform` in esbuild's `lib/main.js`.\n */\nconst UNLINKED_BINARY_SIGNATURE = \"could not be found, and is needed by esbuild\";\n\n/**\n * A cheap operation that forces esbuild to resolve and invoke its platform\n * binary. Injectable so tests can simulate a missing binary without deleting\n * anything from a real install.\n */\nexport type EsbuildProbe = () => void;\n\n/**\n * The default probe: a trivial `transformSync` call. Trivial input keeps the\n * cost negligible while still forcing esbuild to resolve and run its native\n * binary, which is the only way an unlinked binary actually surfaces.\n */\nfunction runDefaultProbe(): void {\n esbuild.transformSync(\"\", { loader: \"js\" });\n}\n\n/**\n * Fail fast, before dev or build does any other work, when esbuild's native\n * binary is not linked.\n *\n * A healthy esbuild install is a no-op. A binary genuinely missing because\n * a platform package was never installed, or a package manager blocked its\n * postinstall script is turned into {@link EsbuildBinaryMissingError}, a\n * message that names the cause and the fix. Any other failure (a real syntax\n * error, an unrelated platform mismatch, …) is rethrown unchanged — this\n * preflight only owns the one known failure mode.\n *\n * @param probe Overrides the default `esbuild.transformSync` invocation.\n * Intended for tests only.\n * @throws {EsbuildBinaryMissingError} when the platform binary is missing or unlinked.\n */\nexport function assertEsbuildBinaryIsLinked(probe: EsbuildProbe = runDefaultProbe): void {\n try {\n probe();\n } catch (error) {\n if (isUnlinkedBinaryError(error)) {\n throw new EsbuildBinaryMissingError({ cause: error });\n }\n\n throw error;\n }\n}\n\n/**\n * Narrow an unknown thrown value down to esbuild's known \"binary not\n * linked\" failure, identified by the fixed substring esbuild itself throws.\n */\nfunction isUnlinkedBinaryError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(UNLINKED_BINARY_SIGNATURE);\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAM,4BAA4B;;;;;;AAclC,SAAS,kBAAwB;CAC/B,QAAQ,cAAc,IAAI,EAAE,QAAQ,KAAK,CAAC;AAC5C;;;;;;;;;;;;;;;;AAiBA,SAAgB,4BAA4B,QAAsB,iBAAuB;CACvF,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,IAAI,sBAAsB,KAAK,GAC7B,MAAM,IAAI,0BAA0B,EAAE,OAAO,MAAM,CAAC;EAGtD,MAAM;CACR;AACF;;;;;AAMA,SAAS,sBAAsB,OAAyB;CACtD,OAAO,iBAAiB,SAAS,MAAM,QAAQ,SAAS,yBAAyB;AACnF"}