@warlock.js/core 5.34.3 → 5.35.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 (244) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/esm/cli/cli-commands.manager.mjs +1 -1
  3. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  4. package/esm/cli/commands/add.command.mjs +1 -0
  5. package/esm/cli/commands/add.command.mjs.map +1 -1
  6. package/esm/cli/commands/build.command.mjs +30 -3
  7. package/esm/cli/commands/build.command.mjs.map +1 -1
  8. package/esm/cli/commands/check/check-command.action.mjs +1 -0
  9. package/esm/cli/commands/check/check-command.action.mjs.map +1 -1
  10. package/esm/cli/commands/check.command.mjs +5 -0
  11. package/esm/cli/commands/check.command.mjs.map +1 -1
  12. package/esm/cli/commands/explain/explain-command.action.mjs +21 -0
  13. package/esm/cli/commands/explain/explain-command.action.mjs.map +1 -1
  14. package/esm/cli/commands/explain.command.mjs +14 -4
  15. package/esm/cli/commands/explain.command.mjs.map +1 -1
  16. package/esm/cli/commands/generate/generate.command.mjs +19 -1
  17. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  18. package/esm/cli/commands/generate/generators/endpoint.generator.mjs +1 -1
  19. package/esm/cli/commands/generate/generators/endpoint.generator.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generators/web.generator.mjs +169 -0
  21. package/esm/cli/commands/generate/generators/web.generator.mjs.map +1 -0
  22. package/esm/cli/commands/generate/templates/web-stubs.mjs +231 -0
  23. package/esm/cli/commands/generate/templates/web-stubs.mjs.map +1 -0
  24. package/esm/cli/commands/inspect/inspect-command.action.mjs +4 -3
  25. package/esm/cli/commands/inspect/inspect-command.action.mjs.map +1 -1
  26. package/esm/cli/commands/inspect.command.mjs +13 -8
  27. package/esm/cli/commands/inspect.command.mjs.map +1 -1
  28. package/esm/cli/commands/mcp/mcp-command.action.mjs +1 -1
  29. package/esm/cli/commands/mcp/mcp-command.action.mjs.map +1 -1
  30. package/esm/config/config-loader.d.mts.map +1 -1
  31. package/esm/config/config-loader.mjs +2 -0
  32. package/esm/config/config-loader.mjs.map +1 -1
  33. package/esm/config/load-config-files.mjs +4 -0
  34. package/esm/config/load-config-files.mjs.map +1 -1
  35. package/esm/dev-server/file-event-handler.mjs +11 -1
  36. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  37. package/esm/dev-server/file-manager.d.mts +1 -1
  38. package/esm/dev-server/file-manager.d.mts.map +1 -1
  39. package/esm/dev-server/file-manager.mjs.map +1 -1
  40. package/esm/dev-server/files-orchestrator.mjs +16 -1
  41. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  42. package/esm/dev-server/files-watcher.mjs +13 -4
  43. package/esm/dev-server/files-watcher.mjs.map +1 -1
  44. package/esm/dev-server/loader/loader-port-acks.mjs +21 -9
  45. package/esm/dev-server/loader/loader-port-acks.mjs.map +1 -1
  46. package/esm/dev-server/loader/register-loader.mjs +31 -12
  47. package/esm/dev-server/loader/register-loader.mjs.map +1 -1
  48. package/esm/dev-server/module-loader.mjs +14 -0
  49. package/esm/dev-server/module-loader.mjs.map +1 -1
  50. package/esm/dev-server/special-file-patterns.mjs +4 -1
  51. package/esm/dev-server/special-file-patterns.mjs.map +1 -1
  52. package/esm/e2e/index.d.mts +2 -2
  53. package/esm/e2e/page.d.mts +6 -1
  54. package/esm/e2e/page.d.mts.map +1 -1
  55. package/esm/e2e/page.mjs +36 -1
  56. package/esm/e2e/page.mjs.map +1 -1
  57. package/esm/e2e/types.d.mts +31 -0
  58. package/esm/e2e/types.d.mts.map +1 -1
  59. package/esm/e2e/types.mjs.map +1 -1
  60. package/esm/errors/error-codes.d.mts +48 -0
  61. package/esm/errors/error-codes.d.mts.map +1 -1
  62. package/esm/errors/error-codes.mjs +48 -0
  63. package/esm/errors/error-codes.mjs.map +1 -1
  64. package/esm/errors/index.d.mts +2 -2
  65. package/esm/errors/index.mjs +2 -2
  66. package/esm/generations/add-command.action.mjs +2 -0
  67. package/esm/generations/add-command.action.mjs.map +1 -1
  68. package/esm/generations/design-system-payload.mjs +53 -0
  69. package/esm/generations/design-system-payload.mjs.map +1 -0
  70. package/esm/generations/features/design-system.feature.mjs +38 -0
  71. package/esm/generations/features/design-system.feature.mjs.map +1 -0
  72. package/esm/generations/features/index.mjs +3 -1
  73. package/esm/generations/features/index.mjs.map +1 -1
  74. package/esm/generations/features/notifications.feature.mjs +13 -2
  75. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  76. package/esm/generations/features/test.feature.mjs +48 -13
  77. package/esm/generations/features/test.feature.mjs.map +1 -1
  78. package/esm/generations/stubs.mjs +9 -5
  79. package/esm/generations/stubs.mjs.map +1 -1
  80. package/esm/http/error-mapper.d.mts +1 -1
  81. package/esm/http/error-mapper.mjs +3 -3
  82. package/esm/http/error-mapper.mjs.map +1 -1
  83. package/esm/http/error-response.d.mts +3 -0
  84. package/esm/http/error-response.d.mts.map +1 -1
  85. package/esm/http/error-response.mjs +8 -2
  86. package/esm/http/error-response.mjs.map +1 -1
  87. package/esm/http/errors/errors.d.mts +8 -0
  88. package/esm/http/errors/errors.d.mts.map +1 -1
  89. package/esm/http/errors/errors.mjs +13 -1
  90. package/esm/http/errors/errors.mjs.map +1 -1
  91. package/esm/http/index.d.mts +3 -2
  92. package/esm/http/index.mjs +3 -2
  93. package/esm/http/list-endpoint.d.mts +35 -0
  94. package/esm/http/list-endpoint.d.mts.map +1 -0
  95. package/esm/http/list-endpoint.mjs +28 -0
  96. package/esm/http/list-endpoint.mjs.map +1 -0
  97. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  98. package/esm/http/middleware/inject-request-context.mjs +12 -2
  99. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  100. package/esm/http/server.mjs +1 -1
  101. package/esm/index.d.mts +8 -6
  102. package/esm/index.mjs +3 -2
  103. package/esm/openapi/security.mjs +12 -4
  104. package/esm/openapi/security.mjs.map +1 -1
  105. package/esm/openapi/types.d.mts +2 -0
  106. package/esm/openapi/types.d.mts.map +1 -1
  107. package/esm/production/build-budgets.d.mts +46 -0
  108. package/esm/production/build-budgets.d.mts.map +1 -0
  109. package/esm/production/build-budgets.mjs +109 -0
  110. package/esm/production/build-budgets.mjs.map +1 -0
  111. package/esm/production/production-builder.mjs +13 -1
  112. package/esm/production/production-builder.mjs.map +1 -1
  113. package/esm/production/resolve-build-config.d.mts +1 -1
  114. package/esm/production/resolve-build-config.d.mts.map +1 -1
  115. package/esm/production/resolve-build-config.mjs.map +1 -1
  116. package/esm/restful/restful.d.mts +1 -1
  117. package/esm/tests/fakes/storage-fake.d.mts +3 -1
  118. package/esm/tests/fakes/storage-fake.d.mts.map +1 -1
  119. package/esm/tests/fakes/storage-fake.mjs +3 -3
  120. package/esm/tests/fakes/storage-fake.mjs.map +1 -1
  121. package/esm/tests/fakes/test-fakes.d.mts +3 -1
  122. package/esm/tests/fakes/test-fakes.d.mts.map +1 -1
  123. package/esm/tests/fakes/test-fakes.mjs +3 -2
  124. package/esm/tests/fakes/test-fakes.mjs.map +1 -1
  125. package/esm/tests/index.d.mts +4 -2
  126. package/esm/tests/index.mjs +3 -1
  127. package/esm/tests/load-unit-config.mjs +24 -0
  128. package/esm/tests/load-unit-config.mjs.map +1 -0
  129. package/esm/tests/response-contract.d.mts +32 -0
  130. package/esm/tests/response-contract.d.mts.map +1 -0
  131. package/esm/tests/response-contract.mjs +116 -0
  132. package/esm/tests/response-contract.mjs.map +1 -0
  133. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  134. package/esm/tests/start-http-development-server.mjs +10 -2
  135. package/esm/tests/start-http-development-server.mjs.map +1 -1
  136. package/esm/tests/test-lifecycle-state.mjs.map +1 -1
  137. package/esm/tests/test-locales.mjs +33 -0
  138. package/esm/tests/test-locales.mjs.map +1 -0
  139. package/esm/tests/test-runtime-scope.d.mts +15 -0
  140. package/esm/tests/test-runtime-scope.d.mts.map +1 -0
  141. package/esm/tests/test-runtime-scope.mjs +80 -0
  142. package/esm/tests/test-runtime-scope.mjs.map +1 -0
  143. package/esm/tests/vitest-setup.d.mts +13 -3
  144. package/esm/tests/vitest-setup.d.mts.map +1 -1
  145. package/esm/tests/vitest-setup.mjs +146 -18
  146. package/esm/tests/vitest-setup.mjs.map +1 -1
  147. package/esm/tooling/check/affected-files.d.mts +5 -0
  148. package/esm/tooling/check/affected-files.d.mts.map +1 -0
  149. package/esm/tooling/check/affected-files.mjs +56 -0
  150. package/esm/tooling/check/affected-files.mjs.map +1 -0
  151. package/esm/tooling/check/changed-files.d.mts +2 -0
  152. package/esm/tooling/check/changed-files.d.mts.map +1 -1
  153. package/esm/tooling/check/changed-files.mjs +2 -2
  154. package/esm/tooling/check/changed-files.mjs.map +1 -1
  155. package/esm/tooling/check/conventions-step.d.mts +2 -1
  156. package/esm/tooling/check/conventions-step.d.mts.map +1 -1
  157. package/esm/tooling/check/conventions-step.mjs +48 -6
  158. package/esm/tooling/check/conventions-step.mjs.map +1 -1
  159. package/esm/tooling/check/fixes.d.mts +8 -0
  160. package/esm/tooling/check/fixes.d.mts.map +1 -0
  161. package/esm/tooling/check/fixes.mjs +31 -0
  162. package/esm/tooling/check/fixes.mjs.map +1 -0
  163. package/esm/tooling/check/index.d.mts +12 -0
  164. package/esm/tooling/check/index.mjs +3 -2
  165. package/esm/tooling/check/run-check.d.mts +2 -0
  166. package/esm/tooling/check/run-check.d.mts.map +1 -1
  167. package/esm/tooling/check/run-check.mjs +20 -4
  168. package/esm/tooling/check/run-check.mjs.map +1 -1
  169. package/esm/tooling/check/run-tests.mjs +1 -1
  170. package/esm/tooling/check/source-ast.d.mts +1 -0
  171. package/esm/tooling/check/web-conventions.d.mts +10 -0
  172. package/esm/tooling/check/web-conventions.d.mts.map +1 -0
  173. package/esm/tooling/check/web-conventions.mjs +126 -0
  174. package/esm/tooling/check/web-conventions.mjs.map +1 -0
  175. package/esm/tooling/index.d.mts +7 -2
  176. package/esm/tooling/index.mjs +4 -2
  177. package/esm/tooling/inspect/collect-files.mjs +172 -0
  178. package/esm/tooling/inspect/collect-files.mjs.map +1 -0
  179. package/esm/tooling/inspect/collect-pages.mjs +3 -2
  180. package/esm/tooling/inspect/collect-pages.mjs.map +1 -1
  181. package/esm/tooling/inspect/collect-routes.mjs +1 -1
  182. package/esm/tooling/inspect/collect-routes.mjs.map +1 -1
  183. package/esm/tooling/inspect/explain-file.d.mts +12 -0
  184. package/esm/tooling/inspect/explain-file.d.mts.map +1 -0
  185. package/esm/tooling/inspect/explain-file.mjs +45 -0
  186. package/esm/tooling/inspect/explain-file.mjs.map +1 -0
  187. package/esm/tooling/inspect/index.d.mts +3 -2
  188. package/esm/tooling/inspect/index.mjs +2 -1
  189. package/esm/tooling/inspect/inspect-app.d.mts.map +1 -1
  190. package/esm/tooling/inspect/inspect-app.mjs +9 -3
  191. package/esm/tooling/inspect/inspect-app.mjs.map +1 -1
  192. package/esm/tooling/inspect/inspect-report.schema.mjs +34 -1
  193. package/esm/tooling/inspect/inspect-report.schema.mjs.map +1 -1
  194. package/esm/tooling/inspect/inspect-report.types.d.mts +17 -1
  195. package/esm/tooling/inspect/inspect-report.types.d.mts.map +1 -1
  196. package/esm/tooling/inspect/inspect-report.types.mjs +2 -1
  197. package/esm/tooling/inspect/inspect-report.types.mjs.map +1 -1
  198. package/esm/tooling/mcp/mcp-tools.d.mts.map +1 -1
  199. package/esm/tooling/mcp/mcp-tools.mjs +8 -2
  200. package/esm/tooling/mcp/mcp-tools.mjs.map +1 -1
  201. package/esm/tooling/problem.d.mts +4 -0
  202. package/esm/tooling/problem.d.mts.map +1 -1
  203. package/esm/tooling/problem.mjs +1 -0
  204. package/esm/tooling/problem.mjs.map +1 -1
  205. package/esm/tooling/syntax/ast.d.mts +2 -0
  206. package/esm/tooling/typecheck/run-typecheck.mjs +5 -1
  207. package/esm/tooling/typecheck/run-typecheck.mjs.map +1 -1
  208. package/esm/vite/index.d.mts +3 -1
  209. package/esm/vite/index.mjs +3 -1
  210. package/esm/vite/test-setup-reporter.d.mts +16 -0
  211. package/esm/vite/test-setup-reporter.d.mts.map +1 -0
  212. package/esm/vite/test-setup-reporter.mjs +55 -0
  213. package/esm/vite/test-setup-reporter.mjs.map +1 -0
  214. package/esm/vite/test-workers.d.mts +5 -0
  215. package/esm/vite/test-workers.d.mts.map +1 -0
  216. package/esm/vite/test-workers.mjs +38 -0
  217. package/esm/vite/test-workers.mjs.map +1 -0
  218. package/esm/warlock-config/index.d.mts +2 -1
  219. package/esm/warlock-config/types.d.mts +3 -0
  220. package/esm/warlock-config/types.d.mts.map +1 -1
  221. package/llms-full.txt +763 -9
  222. package/llms.txt +2 -0
  223. package/package.json +15 -14
  224. package/schemas/inspect-report.schema.json +47 -1
  225. package/skills/build-budgets/SKILL.md +51 -0
  226. package/skills/build-restful/SKILL.md +56 -0
  227. package/skills/configure-app/SKILL.md +7 -0
  228. package/skills/create-module/SKILL.md +9 -0
  229. package/skills/generate-web-ui/SKILL.md +71 -0
  230. package/skills/index.md +2 -2
  231. package/skills/run-app/SKILL.md +1 -1
  232. package/skills/send-mail/SKILL.md +25 -0
  233. package/skills/send-response/SKILL.md +50 -0
  234. package/skills/test-browser/SKILL.md +53 -0
  235. package/skills/test-http/SKILL.md +91 -0
  236. package/skills/test-service/SKILL.md +161 -3
  237. package/skills/upgrade-from-5-29/SKILL.md +18 -0
  238. package/skills/use-localization/SKILL.md +21 -0
  239. package/skills/warlock-check/SKILL.md +72 -1
  240. package/skills/warlock-inspect/SKILL.md +45 -2
  241. package/skills/warlock-mcp/SKILL.md +4 -0
  242. package/skills/write-cli-command/SKILL.md +18 -0
  243. package/esm/production/build-app-production.mjs +0 -14
  244. package/esm/production/build-app-production.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { HttpError } from "./errors/errors.mjs";
1
+ import { AppError, HttpError } from "./errors/errors.mjs";
2
2
  import baseConfig from "@mongez/config";
3
3
  import { log } from "@warlock.js/logger";
4
4
 
@@ -7,7 +7,7 @@ const OPAQUE_SERVER_ERROR = "Internal server error.";
7
7
  /**
8
8
  * Run the configured `http.errorMapper` and normalise its answer to an
9
9
  * `HttpError`, or return the error unchanged when there is no mapper, the
10
- * error already is an `HttpError`, or the mapper declines it.
10
+ * error already is an `HttpError` or `AppError`, or the mapper declines it.
11
11
  *
12
12
  * The mapped `HttpError` keeps the original error's name and stack (for the
13
13
  * request log) and carries it as `cause`. A mapper that throws is a bug in the
@@ -16,7 +16,7 @@ const OPAQUE_SERVER_ERROR = "Internal server error.";
16
16
  * @internal
17
17
  */
18
18
  function mapRequestError(error, request) {
19
- if (error instanceof HttpError) return error;
19
+ if (error instanceof HttpError || error instanceof AppError) return error;
20
20
  const mapper = baseConfig.get("http.errorMapper");
21
21
  if (typeof mapper !== "function") return error;
22
22
  let mapping;
@@ -1 +1 @@
1
- {"version":3,"file":"error-mapper.mjs","names":["config"],"sources":["../../../../../../../../packages/core/src/http/error-mapper.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { log } from \"@warlock.js/logger\";\nimport { HttpError } from \"./errors\";\nimport type { Request } from \"./request\";\n\n/**\n * What an {@link HttpErrorMapper} answers for an error it recognises.\n */\nexport type HttpErrorMapping = {\n /**\n * The HTTP status to answer with.\n */\n status: number;\n /**\n * The message sent as `{ error }`. Defaults to the original error's message\n * for a 4xx and to the opaque `\"Internal server error.\"` for a 5xx, so a\n * mapped server fault never echoes an internal message to the client.\n */\n message?: string;\n /**\n * Sent as `{ payload }`, like `HttpError.payload`.\n */\n payload?: unknown;\n};\n\n/**\n * `http.errorMapper`: turns an error thrown by middleware or a handler into an\n * HTTP answer. Lets domain errors that must also exist outside an HTTP process\n * (a worker, a CLI, a standalone helper) carry a status without extending\n * Core's `HttpError`.\n *\n * Called only for errors that are not already an `HttpError`. Return a\n * mapping (or an `HttpError`) to answer with it, or `undefined` to keep the\n * default handling (a model validation error keeps its configured status,\n * anything else is an opaque 500).\n *\n * @example\n * ```ts\n * errorMapper(error) {\n * if (error instanceof DomainNotFoundError) return { status: 404 };\n * if (error instanceof Error && typeof (error as any).status === \"number\") {\n * return { status: (error as any).status };\n * }\n * }\n * ```\n */\nexport type HttpErrorMapper = (\n error: unknown,\n request: Request<any>,\n) => HttpErrorMapping | HttpError | null | undefined;\n\nconst OPAQUE_SERVER_ERROR = \"Internal server error.\";\n\n/**\n * Run the configured `http.errorMapper` and normalise its answer to an\n * `HttpError`, or return the error unchanged when there is no mapper, the\n * error already is an `HttpError`, or the mapper declines it.\n *\n * The mapped `HttpError` keeps the original error's name and stack (for the\n * request log) and carries it as `cause`. A mapper that throws is a bug in the\n * app's mapper, not in the request: it is logged and the original error is\n * handled as if no mapper were configured.\n * @internal\n */\nexport function mapRequestError(error: unknown, request: Request<any>): unknown {\n if (error instanceof HttpError) {\n return error;\n }\n\n const mapper = config.get(\"http.errorMapper\") as HttpErrorMapper | undefined;\n\n if (typeof mapper !== \"function\") {\n return error;\n }\n\n let mapping: ReturnType<HttpErrorMapper>;\n\n try {\n mapping = mapper(error, request);\n } catch (mapperError) {\n log.error(\"http\", \"error-mapper\", mapperError, { requestId: request.id });\n\n return error;\n }\n\n if (!mapping) {\n return error;\n }\n\n if (mapping instanceof HttpError) {\n return mapping;\n }\n\n if (!Number.isInteger(mapping.status) || mapping.status < 400 || mapping.status > 599) {\n log.error(\n \"http\",\n \"error-mapper\",\n new Error(`http.errorMapper returned an invalid status: ${String(mapping.status)}`),\n { requestId: request.id },\n );\n\n return error;\n }\n\n const original = error instanceof Error ? error : undefined;\n const message =\n mapping.message ?? (mapping.status < 500 && original ? original.message : OPAQUE_SERVER_ERROR);\n\n const mapped = new HttpError(mapping.status, message, mapping.payload);\n\n if (original) {\n mapped.name = original.name;\n mapped.stack = original.stack;\n mapped.cause = original;\n }\n\n return mapped;\n}\n"],"mappings":";;;;;AAmDA,MAAM,sBAAsB;;;;;;;;;;;;AAa5B,SAAgB,gBAAgB,OAAgB,SAAgC;CAC9E,IAAI,iBAAiB,WACnB,OAAO;CAGT,MAAM,SAASA,WAAO,IAAI,kBAAkB;CAE5C,IAAI,OAAO,WAAW,YACpB,OAAO;CAGT,IAAI;CAEJ,IAAI;EACF,UAAU,OAAO,OAAO,OAAO;CACjC,SAAS,aAAa;EACpB,IAAI,MAAM,QAAQ,gBAAgB,aAAa,EAAE,WAAW,QAAQ,GAAG,CAAC;EAExE,OAAO;CACT;CAEA,IAAI,CAAC,SACH,OAAO;CAGT,IAAI,mBAAmB,WACrB,OAAO;CAGT,IAAI,CAAC,OAAO,UAAU,QAAQ,MAAM,KAAK,QAAQ,SAAS,OAAO,QAAQ,SAAS,KAAK;EACrF,IAAI,MACF,QACA,gCACA,IAAI,MAAM,gDAAgD,OAAO,QAAQ,MAAM,GAAG,GAClF,EAAE,WAAW,QAAQ,GAAG,CAC1B;EAEA,OAAO;CACT;CAEA,MAAM,WAAW,iBAAiB,QAAQ,QAAQ;CAClD,MAAM,UACJ,QAAQ,YAAY,QAAQ,SAAS,OAAO,WAAW,SAAS,UAAU;CAE5E,MAAM,SAAS,IAAI,UAAU,QAAQ,QAAQ,SAAS,QAAQ,OAAO;CAErE,IAAI,UAAU;EACZ,OAAO,OAAO,SAAS;EACvB,OAAO,QAAQ,SAAS;EACxB,OAAO,QAAQ;CACjB;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"error-mapper.mjs","names":["config"],"sources":["../../../../../../../../packages/core/src/http/error-mapper.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { log } from \"@warlock.js/logger\";\nimport { AppError, HttpError } from \"./errors\";\nimport type { Request } from \"./request\";\n\n/**\n * What an {@link HttpErrorMapper} answers for an error it recognises.\n */\nexport type HttpErrorMapping = {\n /**\n * The HTTP status to answer with.\n */\n status: number;\n /**\n * The message sent as `{ error }`. Defaults to the original error's message\n * for a 4xx and to the opaque `\"Internal server error.\"` for a 5xx, so a\n * mapped server fault never echoes an internal message to the client.\n */\n message?: string;\n /**\n * Sent as `{ payload }`, like `HttpError.payload`.\n */\n payload?: unknown;\n};\n\n/**\n * `http.errorMapper`: turns an error thrown by middleware or a handler into an\n * HTTP answer. Lets domain errors that must also exist outside an HTTP process\n * (a worker, a CLI, a standalone helper) carry a status without extending\n * Core's `HttpError`.\n *\n * Called only for errors that are not already an `HttpError` or `AppError`. Return a\n * mapping (or an `HttpError`) to answer with it, or `undefined` to keep the\n * default handling (a model validation error keeps its configured status,\n * anything else is an opaque 500).\n *\n * @example\n * ```ts\n * errorMapper(error) {\n * if (error instanceof DomainNotFoundError) return { status: 404 };\n * if (error instanceof Error && typeof (error as any).status === \"number\") {\n * return { status: (error as any).status };\n * }\n * }\n * ```\n */\nexport type HttpErrorMapper = (\n error: unknown,\n request: Request<any>,\n) => HttpErrorMapping | HttpError | null | undefined;\n\nconst OPAQUE_SERVER_ERROR = \"Internal server error.\";\n\n/**\n * Run the configured `http.errorMapper` and normalise its answer to an\n * `HttpError`, or return the error unchanged when there is no mapper, the\n * error already is an `HttpError` or `AppError`, or the mapper declines it.\n *\n * The mapped `HttpError` keeps the original error's name and stack (for the\n * request log) and carries it as `cause`. A mapper that throws is a bug in the\n * app's mapper, not in the request: it is logged and the original error is\n * handled as if no mapper were configured.\n * @internal\n */\nexport function mapRequestError(error: unknown, request: Request<any>): unknown {\n if (error instanceof HttpError || error instanceof AppError) {\n return error;\n }\n\n const mapper = config.get(\"http.errorMapper\") as HttpErrorMapper | undefined;\n\n if (typeof mapper !== \"function\") {\n return error;\n }\n\n let mapping: ReturnType<HttpErrorMapper>;\n\n try {\n mapping = mapper(error, request);\n } catch (mapperError) {\n log.error(\"http\", \"error-mapper\", mapperError, { requestId: request.id });\n\n return error;\n }\n\n if (!mapping) {\n return error;\n }\n\n if (mapping instanceof HttpError) {\n return mapping;\n }\n\n if (!Number.isInteger(mapping.status) || mapping.status < 400 || mapping.status > 599) {\n log.error(\n \"http\",\n \"error-mapper\",\n new Error(`http.errorMapper returned an invalid status: ${String(mapping.status)}`),\n { requestId: request.id },\n );\n\n return error;\n }\n\n const original = error instanceof Error ? error : undefined;\n const message =\n mapping.message ?? (mapping.status < 500 && original ? original.message : OPAQUE_SERVER_ERROR);\n\n const mapped = new HttpError(mapping.status, message, mapping.payload);\n\n if (original) {\n mapped.name = original.name;\n mapped.stack = original.stack;\n mapped.cause = original;\n }\n\n return mapped;\n}\n"],"mappings":";;;;;AAmDA,MAAM,sBAAsB;;;;;;;;;;;;AAa5B,SAAgB,gBAAgB,OAAgB,SAAgC;CAC9E,IAAI,iBAAiB,aAAa,iBAAiB,UACjD,OAAO;CAGT,MAAM,SAASA,WAAO,IAAI,kBAAkB;CAE5C,IAAI,OAAO,WAAW,YACpB,OAAO;CAGT,IAAI;CAEJ,IAAI;EACF,UAAU,OAAO,OAAO,OAAO;CACjC,SAAS,aAAa;EACpB,IAAI,MAAM,QAAQ,gBAAgB,aAAa,EAAE,WAAW,QAAQ,GAAG,CAAC;EAExE,OAAO;CACT;CAEA,IAAI,CAAC,SACH,OAAO;CAGT,IAAI,mBAAmB,WACrB,OAAO;CAGT,IAAI,CAAC,OAAO,UAAU,QAAQ,MAAM,KAAK,QAAQ,SAAS,OAAO,QAAQ,SAAS,KAAK;EACrF,IAAI,MACF,QACA,gCACA,IAAI,MAAM,gDAAgD,OAAO,QAAQ,MAAM,GAAG,GAClF,EAAE,WAAW,QAAQ,GAAG,CAC1B;EAEA,OAAO;CACT;CAEA,MAAM,WAAW,iBAAiB,QAAQ,QAAQ;CAClD,MAAM,UACJ,QAAQ,YAAY,QAAQ,SAAS,OAAO,WAAW,SAAS,UAAU;CAE5E,MAAM,SAAS,IAAI,UAAU,QAAQ,QAAQ,SAAS,QAAQ,OAAO;CAErE,IAAI,UAAU;EACZ,OAAO,OAAO,SAAS;EACvB,OAAO,QAAQ,SAAS;EACxB,OAAO,QAAQ;CACjB;CAEA,OAAO;AACT"}
@@ -1,7 +1,10 @@
1
+ import { AppError } from "./errors/errors.mjs";
1
2
  import "./server.mjs";
3
+ import { FastifyReply } from "fastify";
2
4
  //#region ../../packages/core/src/http/error-response.d.ts
3
5
  /** JSON error body and correlation data available at the transport boundary. */
4
6
  export type HttpErrorResponseContext = {
7
+ appError?: AppError;
5
8
  status: number;
6
9
  body: unknown;
7
10
  requestId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"error-response.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/http/error-response.ts"],"mappings":";;;YAMY;EACV;EACA;EACA;;;YAIU,8BACV,SAAS,6BACN"}
1
+ {"version":3,"file":"error-response.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/http/error-response.ts"],"mappings":";;;;;YAcY;EACV,WAAW;EACX;EACA;EACA;;;YAIU,8BACV,SAAS,6BACN"}
@@ -2,6 +2,11 @@ import baseConfig from "@mongez/config";
2
2
  import { log } from "@warlock.js/logger";
3
3
 
4
4
  //#region ../../packages/core/src/http/error-response.ts
5
+ const appErrors = /* @__PURE__ */ new WeakMap();
6
+ /** @internal Preserve the typed domain failure until the JSON formatter runs. */
7
+ function setResponseAppError(reply, error) {
8
+ appErrors.set(reply, error);
9
+ }
5
10
  /**
6
11
  * Format JSON errors from both Warlock and Fastify, including early rejections.
7
12
  * HTML, files, and streams retain their own response contracts.
@@ -20,7 +25,8 @@ function registerErrorResponseFormatter(server) {
20
25
  const formatted = formatter({
21
26
  status: reply.statusCode,
22
27
  body,
23
- requestId
28
+ requestId,
29
+ appError: appErrors.get(reply)
24
30
  });
25
31
  if (formatted === void 0) return payload;
26
32
  const serialized = JSON.stringify(formatted);
@@ -37,5 +43,5 @@ function registerErrorResponseFormatter(server) {
37
43
  }
38
44
 
39
45
  //#endregion
40
- export { registerErrorResponseFormatter };
46
+ export { registerErrorResponseFormatter, setResponseAppError };
41
47
  //# sourceMappingURL=error-response.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-response.mjs","names":["config"],"sources":["../../../../../../../../packages/core/src/http/error-response.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport type { FastifyInstance } from \"./server\";\n\n/** JSON error body and correlation data available at the transport boundary. */\nexport type HttpErrorResponseContext = {\n status: number;\n body: unknown;\n requestId: string;\n};\n\n/** Return a JSON object, or undefined to retain the original response. */\nexport type HttpErrorResponseFormatter = (\n context: HttpErrorResponseContext,\n) => Record<string, unknown> | undefined;\n\n/**\n * Format JSON errors from both Warlock and Fastify, including early rejections.\n * HTML, files, and streams retain their own response contracts.\n * @internal\n */\nexport function registerErrorResponseFormatter(server: FastifyInstance): void {\n const formatter = config.get(\"http.errorResponse\") as HttpErrorResponseFormatter | undefined;\n\n if (typeof formatter !== \"function\") {\n return;\n }\n\n server.addHook(\n \"onSend\",\n async (request: FastifyRequest, reply: FastifyReply, payload: unknown) => {\n const contentType = String(reply.getHeader(\"content-type\") ?? \"\");\n\n if (\n reply.statusCode < 400 ||\n reply.statusCode > 599 ||\n !/^application\\/(?:[\\w.-]+\\+)?json(?:\\s*;|$)/i.test(contentType) ||\n (typeof payload !== \"string\" && !Buffer.isBuffer(payload))\n ) {\n return payload;\n }\n\n const headerName = config.get(\"http.requestId.header\", \"X-Request-Id\");\n // Warlock stamps its Request.id on routed responses. Before a Warlock\n // Request exists (e.g. parsing, global rate limiting, unmatched routes),\n // use Fastify's request.id and echo that same value for correlation.\n const requestId = String(reply.getHeader(headerName) ?? request.id);\n\n try {\n const body: unknown = JSON.parse(payload.toString());\n const formatted = formatter({ status: reply.statusCode, body, requestId });\n\n if (formatted === undefined) {\n return payload;\n }\n\n const serialized = JSON.stringify(formatted);\n\n if (serialized === undefined) {\n return payload;\n }\n\n if (config.get(\"http.requestId.enabled\", true) !== false) {\n reply.header(headerName, requestId);\n }\n\n reply.header(\"Cache-Control\", \"private, no-store\");\n reply.removeHeader(\"content-length\");\n\n return serialized;\n } catch (error) {\n log.error(\"http\", \"error-response\", error, { requestId });\n\n return payload;\n }\n },\n );\n}\n"],"mappings":";;;;;;;;;AAsBA,SAAgB,+BAA+B,QAA+B;CAC5E,MAAM,YAAYA,WAAO,IAAI,oBAAoB;CAEjD,IAAI,OAAO,cAAc,YACvB;CAGF,OAAO,QACL,UACA,OAAO,SAAyB,OAAqB,YAAqB;EACxE,MAAM,cAAc,OAAO,MAAM,UAAU,cAAc,KAAK,EAAE;EAEhE,IACE,MAAM,aAAa,OACnB,MAAM,aAAa,OACnB,CAAC,8CAA8C,KAAK,WAAW,KAC9D,OAAO,YAAY,YAAY,CAAC,OAAO,SAAS,OAAO,GAExD,OAAO;EAGT,MAAM,aAAaA,WAAO,IAAI,yBAAyB,cAAc;EAIrE,MAAM,YAAY,OAAO,MAAM,UAAU,UAAU,KAAK,QAAQ,EAAE;EAElE,IAAI;GACF,MAAM,OAAgB,KAAK,MAAM,QAAQ,SAAS,CAAC;GACnD,MAAM,YAAY,UAAU;IAAE,QAAQ,MAAM;IAAY;IAAM;GAAU,CAAC;GAEzE,IAAI,cAAc,QAChB,OAAO;GAGT,MAAM,aAAa,KAAK,UAAU,SAAS;GAE3C,IAAI,eAAe,QACjB,OAAO;GAGT,IAAIA,WAAO,IAAI,0BAA0B,IAAI,MAAM,OACjD,MAAM,OAAO,YAAY,SAAS;GAGpC,MAAM,OAAO,iBAAiB,mBAAmB;GACjD,MAAM,aAAa,gBAAgB;GAEnC,OAAO;EACT,SAAS,OAAO;GACd,IAAI,MAAM,QAAQ,kBAAkB,OAAO,EAAE,UAAU,CAAC;GAExD,OAAO;EACT;CACF,CACF;AACF"}
1
+ {"version":3,"file":"error-response.mjs","names":["config"],"sources":["../../../../../../../../packages/core/src/http/error-response.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport type { AppError } from \"./errors\";\nimport type { FastifyInstance } from \"./server\";\n\nconst appErrors = new WeakMap<FastifyReply, AppError>();\n\n/** @internal Preserve the typed domain failure until the JSON formatter runs. */\nexport function setResponseAppError(reply: FastifyReply, error: AppError): void {\n appErrors.set(reply, error);\n}\n\n/** JSON error body and correlation data available at the transport boundary. */\nexport type HttpErrorResponseContext = {\n appError?: AppError;\n status: number;\n body: unknown;\n requestId: string;\n};\n\n/** Return a JSON object, or undefined to retain the original response. */\nexport type HttpErrorResponseFormatter = (\n context: HttpErrorResponseContext,\n) => Record<string, unknown> | undefined;\n\n/**\n * Format JSON errors from both Warlock and Fastify, including early rejections.\n * HTML, files, and streams retain their own response contracts.\n * @internal\n */\nexport function registerErrorResponseFormatter(server: FastifyInstance): void {\n const formatter = config.get(\"http.errorResponse\") as HttpErrorResponseFormatter | undefined;\n\n if (typeof formatter !== \"function\") {\n return;\n }\n\n server.addHook(\n \"onSend\",\n async (request: FastifyRequest, reply: FastifyReply, payload: unknown) => {\n const contentType = String(reply.getHeader(\"content-type\") ?? \"\");\n\n if (\n reply.statusCode < 400 ||\n reply.statusCode > 599 ||\n !/^application\\/(?:[\\w.-]+\\+)?json(?:\\s*;|$)/i.test(contentType) ||\n (typeof payload !== \"string\" && !Buffer.isBuffer(payload))\n ) {\n return payload;\n }\n\n const headerName = config.get(\"http.requestId.header\", \"X-Request-Id\");\n // Warlock stamps its Request.id on routed responses. Before a Warlock\n // Request exists (e.g. parsing, global rate limiting, unmatched routes),\n // use Fastify's request.id and echo that same value for correlation.\n const requestId = String(reply.getHeader(headerName) ?? request.id);\n\n try {\n const body: unknown = JSON.parse(payload.toString());\n const formatted = formatter({\n status: reply.statusCode,\n body,\n requestId,\n appError: appErrors.get(reply),\n });\n\n if (formatted === undefined) {\n return payload;\n }\n\n const serialized = JSON.stringify(formatted);\n\n if (serialized === undefined) {\n return payload;\n }\n\n if (config.get(\"http.requestId.enabled\", true) !== false) {\n reply.header(headerName, requestId);\n }\n\n reply.header(\"Cache-Control\", \"private, no-store\");\n reply.removeHeader(\"content-length\");\n\n return serialized;\n } catch (error) {\n log.error(\"http\", \"error-response\", error, { requestId });\n\n return payload;\n }\n },\n );\n}\n"],"mappings":";;;;AAMA,MAAM,4BAAY,IAAI,QAAgC;;AAGtD,SAAgB,oBAAoB,OAAqB,OAAuB;CAC9E,UAAU,IAAI,OAAO,KAAK;AAC5B;;;;;;AAoBA,SAAgB,+BAA+B,QAA+B;CAC5E,MAAM,YAAYA,WAAO,IAAI,oBAAoB;CAEjD,IAAI,OAAO,cAAc,YACvB;CAGF,OAAO,QACL,UACA,OAAO,SAAyB,OAAqB,YAAqB;EACxE,MAAM,cAAc,OAAO,MAAM,UAAU,cAAc,KAAK,EAAE;EAEhE,IACE,MAAM,aAAa,OACnB,MAAM,aAAa,OACnB,CAAC,8CAA8C,KAAK,WAAW,KAC9D,OAAO,YAAY,YAAY,CAAC,OAAO,SAAS,OAAO,GAExD,OAAO;EAGT,MAAM,aAAaA,WAAO,IAAI,yBAAyB,cAAc;EAIrE,MAAM,YAAY,OAAO,MAAM,UAAU,UAAU,KAAK,QAAQ,EAAE;EAElE,IAAI;GACF,MAAM,OAAgB,KAAK,MAAM,QAAQ,SAAS,CAAC;GACnD,MAAM,YAAY,UAAU;IAC1B,QAAQ,MAAM;IACd;IACA;IACA,UAAU,UAAU,IAAI,KAAK;GAC/B,CAAC;GAED,IAAI,cAAc,QAChB,OAAO;GAGT,MAAM,aAAa,KAAK,UAAU,SAAS;GAE3C,IAAI,eAAe,QACjB,OAAO;GAGT,IAAIA,WAAO,IAAI,0BAA0B,IAAI,MAAM,OACjD,MAAM,OAAO,YAAY,SAAS;GAGpC,MAAM,OAAO,iBAAiB,mBAAmB;GACjD,MAAM,aAAa,gBAAgB;GAEnC,OAAO;EACT,SAAS,OAAO;GACd,IAAI,MAAM,QAAQ,kBAAkB,OAAO,EAAE,UAAU,CAAC;GAExD,OAAO;EACT;CACF,CACF;AACF"}
@@ -1,4 +1,12 @@
1
1
  //#region ../../packages/core/src/http/errors/errors.d.ts
2
+ /** A domain failure whose message and details are explicitly safe for clients. */
3
+ export declare class AppError<Details = unknown, Code extends string = string> extends Error {
4
+ readonly code: Code;
5
+ readonly status: number;
6
+ readonly publicMessage: string;
7
+ readonly details?: Details | undefined;
8
+ constructor(code: Code, status: number, publicMessage: string, details?: Details | undefined);
9
+ }
2
10
  export declare class HttpError extends Error {
3
11
  status: number;
4
12
  message: string;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/http/errors/errors.ts"],"mappings":";qBAAa,kBAAkB;EAEpB;EACA;EACA;EAHT,YACS,gBACA,iBACA;;qBAOE,8BAA8B;EAGhC;EAFT,YACE,iBACO;;qBAOE,0BAA0B;EAG5B;EAFT,YACE,iBACO;;qBAOE,uBAAuB;EAGzB;EAFT,YACE,iBACO;;qBAOE,wBAAwB;EAG1B;EAFT,YACE,iBACO;;qBAOE,oBAAoB;EAGtB;EAFT,YACE,iBACO;;qBAOE,sBAAsB;EAGxB;EAFT,YACE,iBACO;;qBAOE,2BAA2B;EAG7B;EAFT,YACE,iBACO;;qBAOE,wBAAwB;EAG1B;EAFT,YACE,iBACO;;;;;;;;;;;;;;qBAmBE,kCAAkC;;WAE7B;EAEhB,YAAmB"}
1
+ {"version":3,"file":"errors.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/http/errors/errors.ts"],"mappings":";;qBACa,SAAS,mBAAmB,sCAAsC;WAE3D,MAAM;WACN;WACA;WACA,UAAU;EAJ5B,YACkB,MAAM,MACN,gBACA,uBACA,UAAU;;qBAUjB,kBAAkB;EAEpB;EACA;EACA;EAHT,YACS,gBACA,iBACA;;qBAOE,8BAA8B;EAGhC;EAFT,YACE,iBACO;;qBAOE,0BAA0B;EAG5B;EAFT,YACE,iBACO;;qBAOE,uBAAuB;EAGzB;EAFT,YACE,iBACO;;qBAOE,wBAAwB;EAG1B;EAFT,YACE,iBACO;;qBAOE,oBAAoB;EAGtB;EAFT,YACE,iBACO;;qBAOE,sBAAsB;EAGxB;EAFT,YACE,iBACO;;qBAOE,2BAA2B;EAG7B;EAFT,YACE,iBACO;;qBAOE,wBAAwB;EAG1B;EAFT,YACE,iBACO;;;;;;;;;;;;;;qBAmBE,kCAAkC;;WAE7B;EAEhB,YAAmB"}
@@ -1,4 +1,16 @@
1
1
  //#region ../../packages/core/src/http/errors/errors.ts
2
+ /** A domain failure whose message and details are explicitly safe for clients. */
3
+ var AppError = class extends Error {
4
+ constructor(code, status, publicMessage, details) {
5
+ super(publicMessage);
6
+ this.code = code;
7
+ this.status = status;
8
+ this.publicMessage = publicMessage;
9
+ this.details = details;
10
+ if (!Number.isInteger(status) || status < 400 || status > 599) throw new RangeError("AppError status must be an integer between 400 and 599.");
11
+ this.name = "AppError";
12
+ }
13
+ };
2
14
  var HttpError = class extends Error {
3
15
  constructor(status, message, payload) {
4
16
  super(message);
@@ -85,5 +97,5 @@ var CookieJarUnavailableError = class extends Error {
85
97
  };
86
98
 
87
99
  //#endregion
88
- export { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError };
100
+ export { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError };
89
101
  //# sourceMappingURL=errors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/http/errors/errors.ts"],"sourcesContent":["export class HttpError extends Error {\n public constructor(\n public status: number,\n public message: string,\n public payload?: any,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\nexport class ResourceNotFoundError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(404, message, payload);\n this.name = \"ResourceNotFoundError\";\n }\n}\n\nexport class UnAuthorizedError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(401, message, payload);\n this.name = \"UnAuthorizedError\";\n }\n}\n\nexport class ForbiddenError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(403, message, payload);\n this.name = \"ForbiddenError\";\n }\n}\n\nexport class BadRequestError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(400, message, payload);\n this.name = \"BadRequestError\";\n }\n}\n\nexport class ServerError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(500, message, payload);\n this.name = \"ServerError\";\n }\n}\n\nexport class ConflictError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(409, message, payload);\n this.name = \"ConflictError\";\n }\n}\n\nexport class NotAcceptableError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(406, message, payload);\n this.name = \"NotAcceptableError\";\n }\n}\n\nexport class NotAllowedError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(405, message, payload);\n this.name = \"NotAllowedError\";\n }\n}\n\n/**\n * Thrown by `Request.prototype.cookie` / `Request.prototype.hasCookie` when\n * `@fastify/cookie` was never registered on this Fastify instance, so\n * `baseRequest.cookies` is `undefined` rather than an (possibly empty) object.\n *\n * A by-name cookie read is a deliberate assertion by the caller — \"this\n * cookie should be readable here\" — so an unavailable jar is a configuration\n * fault, not an absent cookie, and must not be swallowed into a default\n * value or a silent `false`. Contrast `Request.prototype.cookies`, which\n * stays lenient because the framework's own opportunistic reads (e.g.\n * locale resolution) must not throw on a request that simply has no jar.\n */\nexport class CookieJarUnavailableError extends Error {\n /** Stable Warlock error code; `warlock explain WL5001` prints the fix. */\n public readonly code = \"WL5001\";\n\n public constructor(cookieName: string) {\n super(\n `Cannot read cookie \"${cookieName}\": the cookie jar is unavailable because ` +\n \"@fastify/cookie is not registered on this Fastify instance. \" +\n \"Register the plugin (see core's http/plugins.ts) before reading cookies by name.\",\n );\n\n this.name = \"CookieJarUnavailableError\";\n }\n}\n"],"mappings":";AAAA,IAAa,YAAb,cAA+B,MAAM;CACnC,AAAO,YACL,AAAO,QACP,AAAO,SACP,AAAO,SACP;EACA,MAAM,OAAO;EAJN;EACA;EACA;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,wBAAb,cAA2C,UAAU;CACnD,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,oBAAb,cAAuC,UAAU;CAC/C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,iBAAb,cAAoC,UAAU;CAC5C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,kBAAb,cAAqC,UAAU;CAC7C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,cAAb,cAAiC,UAAU;CACzC,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,gBAAb,cAAmC,UAAU;CAC3C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,qBAAb,cAAwC,UAAU;CAChD,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,kBAAb,cAAqC,UAAU;CAC7C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;AAcA,IAAa,4BAAb,cAA+C,MAAM;CAInD,AAAO,YAAY,YAAoB;EACrC,MACE,uBAAuB,WAAW,sLAGpC;cAPqB;EASrB,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/http/errors/errors.ts"],"sourcesContent":["/** A domain failure whose message and details are explicitly safe for clients. */\nexport class AppError<Details = unknown, Code extends string = string> extends Error {\n public constructor(\n public readonly code: Code,\n public readonly status: number,\n public readonly publicMessage: string,\n public readonly details?: Details,\n ) {\n super(publicMessage);\n if (!Number.isInteger(status) || status < 400 || status > 599) {\n throw new RangeError(\"AppError status must be an integer between 400 and 599.\");\n }\n this.name = \"AppError\";\n }\n}\n\nexport class HttpError extends Error {\n public constructor(\n public status: number,\n public message: string,\n public payload?: any,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\nexport class ResourceNotFoundError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(404, message, payload);\n this.name = \"ResourceNotFoundError\";\n }\n}\n\nexport class UnAuthorizedError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(401, message, payload);\n this.name = \"UnAuthorizedError\";\n }\n}\n\nexport class ForbiddenError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(403, message, payload);\n this.name = \"ForbiddenError\";\n }\n}\n\nexport class BadRequestError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(400, message, payload);\n this.name = \"BadRequestError\";\n }\n}\n\nexport class ServerError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(500, message, payload);\n this.name = \"ServerError\";\n }\n}\n\nexport class ConflictError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(409, message, payload);\n this.name = \"ConflictError\";\n }\n}\n\nexport class NotAcceptableError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(406, message, payload);\n this.name = \"NotAcceptableError\";\n }\n}\n\nexport class NotAllowedError extends HttpError {\n public constructor(\n message: string,\n public payload?: any,\n ) {\n super(405, message, payload);\n this.name = \"NotAllowedError\";\n }\n}\n\n/**\n * Thrown by `Request.prototype.cookie` / `Request.prototype.hasCookie` when\n * `@fastify/cookie` was never registered on this Fastify instance, so\n * `baseRequest.cookies` is `undefined` rather than an (possibly empty) object.\n *\n * A by-name cookie read is a deliberate assertion by the caller — \"this\n * cookie should be readable here\" — so an unavailable jar is a configuration\n * fault, not an absent cookie, and must not be swallowed into a default\n * value or a silent `false`. Contrast `Request.prototype.cookies`, which\n * stays lenient because the framework's own opportunistic reads (e.g.\n * locale resolution) must not throw on a request that simply has no jar.\n */\nexport class CookieJarUnavailableError extends Error {\n /** Stable Warlock error code; `warlock explain WL5001` prints the fix. */\n public readonly code = \"WL5001\";\n\n public constructor(cookieName: string) {\n super(\n `Cannot read cookie \"${cookieName}\": the cookie jar is unavailable because ` +\n \"@fastify/cookie is not registered on this Fastify instance. \" +\n \"Register the plugin (see core's http/plugins.ts) before reading cookies by name.\",\n );\n\n this.name = \"CookieJarUnavailableError\";\n }\n}\n"],"mappings":";;AACA,IAAa,WAAb,cAA+E,MAAM;CACnF,AAAO,YACL,AAAgB,MAChB,AAAgB,QAChB,AAAgB,eAChB,AAAgB,SAChB;EACA,MAAM,aAAa;EALH;EACA;EACA;EACA;EAGhB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,OAAO,SAAS,KACxD,MAAM,IAAI,WAAW,yDAAyD;EAEhF,KAAK,OAAO;CACd;AACF;AAEA,IAAa,YAAb,cAA+B,MAAM;CACnC,AAAO,YACL,AAAO,QACP,AAAO,SACP,AAAO,SACP;EACA,MAAM,OAAO;EAJN;EACA;EACA;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,wBAAb,cAA2C,UAAU;CACnD,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,oBAAb,cAAuC,UAAU;CAC/C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,iBAAb,cAAoC,UAAU;CAC5C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,kBAAb,cAAqC,UAAU;CAC7C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,cAAb,cAAiC,UAAU;CACzC,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,gBAAb,cAAmC,UAAU;CAC3C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,qBAAb,cAAwC,UAAU;CAChD,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;AAEA,IAAa,kBAAb,cAAqC,UAAU;CAC7C,AAAO,YACL,SACA,AAAO,SACP;EACA,MAAM,KAAK,SAAS,OAAO;EAFpB;EAGP,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;AAcA,IAAa,4BAAb,cAA+C,MAAM;CAInD,AAAO,YAAY,YAAoB;EACrC,MACE,uBAAuB,WAAW,sLAGpC;cAPqB;EASrB,KAAK,OAAO;CACd;AACF"}
@@ -1,4 +1,4 @@
1
- import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
1
+ import { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
2
2
  import { ConditionalRequestInput, ConditionalRequestOutcome, EntityTag, evaluateConditionalRequest, matchesIfMatch, matchesIfNoneMatch, parseEntityTag, parseEntityTagList, strongEntityTagMatch, weakEntityTagMatch } from "./conditional-request.mjs";
3
3
  import { HttpLoggingConfig, PrivateRequestLoggingRule, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, URL_CREDENTIAL_PARAMS, buildRequestLogSnapshot, redactQueryCredentials, redactUrlCredentials, resolveRequestLoggingOptions } from "./request-log-snapshot.mjs";
4
4
  import { PipeableReactStream, StreamReactResponseOptions, streamReactResponse } from "./stream-react-response.mjs";
@@ -54,4 +54,5 @@ import { TracingContextSource, buildTracingContext, dispatchPhase, dispatchReque
54
54
  import { RequestContextStore, requestContext, useCurrentUser, useRequest, useRequestStore } from "./context/request-context.mjs";
55
55
  import { requestMemo } from "./context/request-memo.mjs";
56
56
  import { ModelResourceRegistry, Serialized, SerializedWire } from "./serialized.mjs";
57
- export { BadRequestError, type CacheMiddlewareOptions, ClosableServer, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConflictError, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, DEFAULT_CSP_DIRECTIVES, DecodedAccessToken, DetectedImageFormat, EntityTag, FastifyInstance, FileNamingStrategy, FileValidationOptions, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, HealthCheck, HealthStatus, HttpConfigurations, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, type HttpErrorResponseContext, type HttpErrorResponseFormatter, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, ImageTransformCallback, ImageTransformConfig, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidCspDirectiveError, type IpFilterOptions, type MaintenanceOptions, ModelResourceRegistry, NotAcceptableError, NotAllowedError, PartialMiddleware, PipeableReactStream, PortInUseError, PrefixConfig, PrefixOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, type RateLimitOptions, Request, RequestContextStore, RequestController, RequestEvent, RequestLocals, RequestLog, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestTranslator, ResolveImageVariantInput, ResolvedImageVariant, ResolvedImageVariantsConfig, ResourceNotFoundError, Response, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseStatus, ResponseStreamController, ResponseStreamOptions, ReturnedResponse, SafeRedirectOptions, SaveAsOptions, SaveOptions, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, StreamReactResponseOptions, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, VariantOutputFormat, VariantSourceFormat, XMLable, anyMatch, applyCspHeader, assertConfiguredHttpPortIsFree, assertPortIsAvailable, beginHttpDrain, buildCspHeaderValue, buildIdempotencyCacheKey, buildRequestLogSnapshot, buildTracingContext, closeServerWithTimeout, createHttpApplication, createRequestStore, createUploadedFileController, defaultHttpConfigurations, deriveTraceId, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, escapeHeaderValue, evaluateConditionalRequest, generateImageVariants, getHttpReadyReport, getHttpServer, hashBody, health, httpConfig, ipMatches, isAllowedCsrfOrigin, isPortAvailable, isSafeRedirect, isTracingEnabled, isValidIdempotencyKey, logResponse, matchesIfMatch, matchesIfNoneMatch, mergeCspDirectives, middleware, normalizeOrigin, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseSize, parseTraceparentTraceId, preflightConfiguredHttpPort, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerHttpPlugins, registerTracingHooks, remedyLines, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, runDefaultCsrfGuard, safeRedirect, serializeCspDirectives, setHttpReadyReport, shouldPreflightHttpPort, startHttpServer, stopHttpApplication, streamReactResponse, strongEntityTagMatch, t, toSingleLineSseField, trackConnectionsForDrain, uploadedFileController, uploadsConfig, useCurrentUser, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, weakEntityTagMatch, wrapResponseInDataKey };
57
+ import { ListEndpointBody, ListEndpointOptions, ListEndpointRepositoryOptions, ListQuery, listEndpoint } from "./list-endpoint.mjs";
58
+ export { AppError, BadRequestError, type CacheMiddlewareOptions, ClosableServer, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConflictError, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, DEFAULT_CSP_DIRECTIVES, DecodedAccessToken, DetectedImageFormat, EntityTag, FastifyInstance, FileNamingStrategy, FileValidationOptions, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, HealthCheck, HealthStatus, HttpConfigurations, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, type HttpErrorResponseContext, type HttpErrorResponseFormatter, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, ImageTransformCallback, ImageTransformConfig, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidCspDirectiveError, type IpFilterOptions, ListEndpointBody, ListEndpointOptions, ListEndpointRepositoryOptions, ListQuery, type MaintenanceOptions, ModelResourceRegistry, NotAcceptableError, NotAllowedError, PartialMiddleware, PipeableReactStream, PortInUseError, PrefixConfig, PrefixOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, type RateLimitOptions, Request, RequestContextStore, RequestController, RequestEvent, RequestLocals, RequestLog, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestTranslator, ResolveImageVariantInput, ResolvedImageVariant, ResolvedImageVariantsConfig, ResourceNotFoundError, Response, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseStatus, ResponseStreamController, ResponseStreamOptions, ReturnedResponse, SafeRedirectOptions, SaveAsOptions, SaveOptions, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, StreamReactResponseOptions, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, VariantOutputFormat, VariantSourceFormat, XMLable, anyMatch, applyCspHeader, assertConfiguredHttpPortIsFree, assertPortIsAvailable, beginHttpDrain, buildCspHeaderValue, buildIdempotencyCacheKey, buildRequestLogSnapshot, buildTracingContext, closeServerWithTimeout, createHttpApplication, createRequestStore, createUploadedFileController, defaultHttpConfigurations, deriveTraceId, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, escapeHeaderValue, evaluateConditionalRequest, generateImageVariants, getHttpReadyReport, getHttpServer, hashBody, health, httpConfig, ipMatches, isAllowedCsrfOrigin, isPortAvailable, isSafeRedirect, isTracingEnabled, isValidIdempotencyKey, listEndpoint, logResponse, matchesIfMatch, matchesIfNoneMatch, mergeCspDirectives, middleware, normalizeOrigin, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseSize, parseTraceparentTraceId, preflightConfiguredHttpPort, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerHttpPlugins, registerTracingHooks, remedyLines, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, runDefaultCsrfGuard, safeRedirect, serializeCspDirectives, setHttpReadyReport, shouldPreflightHttpPort, startHttpServer, stopHttpApplication, streamReactResponse, strongEntityTagMatch, t, toSingleLineSseField, trackConnectionsForDrain, uploadedFileController, uploadsConfig, useCurrentUser, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, weakEntityTagMatch, wrapResponseInDataKey };
@@ -3,7 +3,7 @@ import { DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, build
3
3
  import { HttpErrorCodes } from "./error-codes.mjs";
4
4
  import { isAllowedCsrfOrigin, normalizeOrigin, originOf, ownOrigin, resolveCsrfOriginVerdict } from "./csrf-origin-policy.mjs";
5
5
  import { requiresDefaultCsrfGuard, runDefaultCsrfGuard } from "./csrf-default-guard.mjs";
6
- import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
6
+ import { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
7
7
  import { deriveTraceId, parseTraceparentTraceId } from "./tracing/trace-id.mjs";
8
8
  import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, registerTracingHooks, resetTracingConfigForTests, resolveTracingConfig } from "./tracing/tracing-dispatcher.mjs";
9
9
  import "./tracing/index.mjs";
@@ -41,5 +41,6 @@ import { notifyHttpServerRebuilt, onHttpServerRebuilt } from "./server-rebuilt.m
41
41
  import { escapeHeaderValue } from "./escape-header-value.mjs";
42
42
  import { isSafeRedirect, safeRedirect } from "./safe-redirect.mjs";
43
43
  import { requestMemo } from "./context/request-memo.mjs";
44
+ import { listEndpoint } from "./list-endpoint.mjs";
44
45
 
45
- export { BadRequestError, ConflictError, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, ForbiddenError, HttpError, HttpErrorCodes, ImageVariantsConfigError, InvalidCspDirectiveError, NotAcceptableError, NotAllowedError, PortInUseError, Request, RequestController, RequestLog, ResourceNotFoundError, Response, ResponseStatus, ServerError, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UploadedFile, anyMatch, applyCspHeader, assertConfiguredHttpPortIsFree, assertPortIsAvailable, beginHttpDrain, buildCspHeaderValue, buildIdempotencyCacheKey, buildRequestLogSnapshot, buildTracingContext, closeServerWithTimeout, createHttpApplication, createRequestStore, createUploadedFileController, defaultHttpConfigurations, deriveTraceId, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, escapeHeaderValue, evaluateConditionalRequest, generateImageVariants, getHttpReadyReport, getHttpServer, hashBody, health, httpConfig, ipMatches, isAllowedCsrfOrigin, isPortAvailable, isSafeRedirect, isTracingEnabled, isValidIdempotencyKey, logResponse, matchesIfMatch, matchesIfNoneMatch, mergeCspDirectives, middleware, normalizeOrigin, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseSize, parseTraceparentTraceId, preflightConfiguredHttpPort, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerHttpPlugins, registerTracingHooks, remedyLines, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, runDefaultCsrfGuard, safeRedirect, serializeCspDirectives, setHttpReadyReport, shouldPreflightHttpPort, startHttpServer, stopHttpApplication, streamReactResponse, strongEntityTagMatch, t, toSingleLineSseField, trackConnectionsForDrain, uploadedFileController, uploadsConfig, useCurrentUser, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, weakEntityTagMatch, wrapResponseInDataKey };
46
+ export { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, ForbiddenError, HttpError, HttpErrorCodes, ImageVariantsConfigError, InvalidCspDirectiveError, NotAcceptableError, NotAllowedError, PortInUseError, Request, RequestController, RequestLog, ResourceNotFoundError, Response, ResponseStatus, ServerError, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UploadedFile, anyMatch, applyCspHeader, assertConfiguredHttpPortIsFree, assertPortIsAvailable, beginHttpDrain, buildCspHeaderValue, buildIdempotencyCacheKey, buildRequestLogSnapshot, buildTracingContext, closeServerWithTimeout, createHttpApplication, createRequestStore, createUploadedFileController, defaultHttpConfigurations, deriveTraceId, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, escapeHeaderValue, evaluateConditionalRequest, generateImageVariants, getHttpReadyReport, getHttpServer, hashBody, health, httpConfig, ipMatches, isAllowedCsrfOrigin, isPortAvailable, isSafeRedirect, isTracingEnabled, isValidIdempotencyKey, listEndpoint, logResponse, matchesIfMatch, matchesIfNoneMatch, mergeCspDirectives, middleware, normalizeOrigin, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseSize, parseTraceparentTraceId, preflightConfiguredHttpPort, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerHttpPlugins, registerTracingHooks, remedyLines, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, runDefaultCsrfGuard, safeRedirect, serializeCspDirectives, setHttpReadyReport, shouldPreflightHttpPort, startHttpServer, stopHttpApplication, streamReactResponse, strongEntityTagMatch, t, toSingleLineSseField, trackConnectionsForDrain, uploadedFileController, uploadsConfig, useCurrentUser, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, weakEntityTagMatch, wrapResponseInDataKey };
@@ -0,0 +1,35 @@
1
+ import { Request } from "./request.mjs";
2
+ import { PaginationResult, RepositoryOptions } from "../repositories/contracts/types.mjs";
3
+ import "../repositories/contracts/index.mjs";
4
+ //#region ../../packages/core/src/http/list-endpoint.d.ts
5
+ export type ListQuery = {
6
+ page?: number;
7
+ limit?: number;
8
+ orderBy?: string;
9
+ orderDir?: "asc" | "desc";
10
+ };
11
+ export type ListEndpointOptions<Key extends string, Query extends ListQuery> = {
12
+ pluralKey: Key & (Key extends "pagination" ? never : unknown);
13
+ /** Indexed columns clients may sort on. */
14
+ orderBy: readonly string[];
15
+ /** Only these validated query fields reach repository filters. */
16
+ filters?: readonly Exclude<keyof Query & string, keyof ListQuery>[];
17
+ defaultLimit?: number;
18
+ maxLimit?: number;
19
+ };
20
+ export type ListEndpointRepositoryOptions<Query extends ListQuery> = RepositoryOptions & Partial<Omit<Query, keyof ListQuery>> & {
21
+ page: number;
22
+ limit: number;
23
+ paginate: true;
24
+ paginationMode: "pages";
25
+ };
26
+ export type ListEndpointBody<Key extends string, Item> = Record<Key, Item[]> & {
27
+ pagination: PaginationResult<Item>["pagination"];
28
+ };
29
+ /** Build a bounded, page-based list body from validated query values only. */
30
+ export declare function listEndpoint<Key extends string, Query extends ListQuery, Item>(request: Request<Query>, list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>, options: ListEndpointOptions<Key, Query>): Promise<ListEndpointBody<Key, Item>>;
31
+ export declare function listEndpoint<Key extends string, Query extends ListQuery, Item>(request: {
32
+ validated(): Query;
33
+ }, list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>, options: ListEndpointOptions<Key, Query>): Promise<ListEndpointBody<Key, Item>>;
34
+ //#endregion
35
+ //# sourceMappingURL=list-endpoint.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-endpoint.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/http/list-endpoint.ts"],"mappings":";;;;YAIY;EACV;EACA;EACA;EACA;;YAGU,oBAAoB,oBAAoB,cAAc;EAChE,WAAW,OAAO;;EAElB;;EAEA,mBAAmB,cAAc,sBAAsB;EACvD;EACA;;YAGU,8BAA8B,cAAc,aAAa,oBACnE,QAAQ,KAAK,aAAa;EACxB;EACA;EACA;EACA;;YAGQ,iBAAiB,oBAAoB,QAAQ,OAAO,KAAK;EACnE,YAAY,iBAAiB;;;wBAIf,aAAa,oBAAoB,cAAc,WAAW,MACxE,SAAS,QAAQ,QACjB,OAAO,SAAS,8BAA8B,WAAW,QAAQ,iBAAiB,QAClF,SAAS,oBAAoB,KAAK,SACjC,QAAQ,iBAAiB,KAAK;wBACjB,aAAa,oBAAoB,cAAc,WAAW,MACxE;EAAW,aAAa;GACxB,OAAO,SAAS,8BAA8B,WAAW,QAAQ,iBAAiB,QAClF,SAAS,oBAAoB,KAAK,SACjC,QAAQ,iBAAiB,KAAK"}
@@ -0,0 +1,28 @@
1
+ import { AppError } from "./errors/errors.mjs";
2
+
3
+ //#region ../../packages/core/src/http/list-endpoint.ts
4
+ async function listEndpoint(request, list, options) {
5
+ const maxLimit = options.maxLimit ?? 100;
6
+ const defaultLimit = options.defaultLimit ?? 20;
7
+ if (!Number.isSafeInteger(maxLimit) || maxLimit < 1 || !Number.isSafeInteger(defaultLimit) || defaultLimit < 1 || options.pluralKey === "pagination" || !options.pluralKey) throw new TypeError("Invalid listEndpoint configuration.");
8
+ const query = request.validated();
9
+ const page = query.page ?? 1;
10
+ const requestedLimit = query.limit ?? defaultLimit;
11
+ if (!Number.isSafeInteger(page) || page < 1 || !Number.isSafeInteger(requestedLimit) || requestedLimit < 1 || query.orderBy !== void 0 && !options.orderBy.includes(query.orderBy) || query.orderDir !== void 0 && query.orderDir !== "asc" && query.orderDir !== "desc") throw new AppError("invalidListQuery", 422, "Invalid list query.");
12
+ const result = await list({
13
+ ...Object.fromEntries((options.filters ?? []).filter((key) => query[key] !== void 0).map((key) => [key, query[key]])),
14
+ page,
15
+ limit: Math.min(requestedLimit, maxLimit),
16
+ paginate: true,
17
+ paginationMode: "pages",
18
+ ...query.orderBy === void 0 ? {} : { orderBy: [query.orderBy, query.orderDir ?? "asc"] }
19
+ });
20
+ return {
21
+ [options.pluralKey]: result.data,
22
+ pagination: result.pagination
23
+ };
24
+ }
25
+
26
+ //#endregion
27
+ export { listEndpoint };
28
+ //# sourceMappingURL=list-endpoint.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-endpoint.mjs","names":[],"sources":["../../../../../../../../packages/core/src/http/list-endpoint.ts"],"sourcesContent":["import type { PaginationResult, RepositoryOptions } from \"../repositories/contracts\";\nimport type { Request } from \"./request\";\nimport { AppError } from \"./errors\";\n\nexport type ListQuery = {\n page?: number;\n limit?: number;\n orderBy?: string;\n orderDir?: \"asc\" | \"desc\";\n};\n\nexport type ListEndpointOptions<Key extends string, Query extends ListQuery> = {\n pluralKey: Key & (Key extends \"pagination\" ? never : unknown);\n /** Indexed columns clients may sort on. */\n orderBy: readonly string[];\n /** Only these validated query fields reach repository filters. */\n filters?: readonly Exclude<keyof Query & string, keyof ListQuery>[];\n defaultLimit?: number;\n maxLimit?: number;\n};\n\nexport type ListEndpointRepositoryOptions<Query extends ListQuery> = RepositoryOptions &\n Partial<Omit<Query, keyof ListQuery>> & {\n page: number;\n limit: number;\n paginate: true;\n paginationMode: \"pages\";\n };\n\nexport type ListEndpointBody<Key extends string, Item> = Record<Key, Item[]> & {\n pagination: PaginationResult<Item>[\"pagination\"];\n};\n\n/** Build a bounded, page-based list body from validated query values only. */\nexport function listEndpoint<Key extends string, Query extends ListQuery, Item>(\n request: Request<Query>,\n list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>,\n options: ListEndpointOptions<Key, Query>,\n): Promise<ListEndpointBody<Key, Item>>;\nexport function listEndpoint<Key extends string, Query extends ListQuery, Item>(\n request: { validated(): Query },\n list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>,\n options: ListEndpointOptions<Key, Query>,\n): Promise<ListEndpointBody<Key, Item>>;\nexport async function listEndpoint<Key extends string, Query extends ListQuery, Item>(\n request: { validated(): Query },\n list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>,\n options: ListEndpointOptions<Key, Query>,\n): Promise<ListEndpointBody<Key, Item>> {\n const maxLimit = options.maxLimit ?? 100;\n const defaultLimit = options.defaultLimit ?? 20;\n if (\n !Number.isSafeInteger(maxLimit) ||\n maxLimit < 1 ||\n !Number.isSafeInteger(defaultLimit) ||\n defaultLimit < 1 ||\n options.pluralKey === \"pagination\" ||\n !options.pluralKey\n ) {\n throw new TypeError(\"Invalid listEndpoint configuration.\");\n }\n const query = request.validated();\n const page = query.page ?? 1;\n const requestedLimit = query.limit ?? defaultLimit;\n if (\n !Number.isSafeInteger(page) ||\n page < 1 ||\n !Number.isSafeInteger(requestedLimit) ||\n requestedLimit < 1 ||\n (query.orderBy !== undefined && !options.orderBy.includes(query.orderBy)) ||\n (query.orderDir !== undefined && query.orderDir !== \"asc\" && query.orderDir !== \"desc\")\n ) {\n throw new AppError(\"invalidListQuery\", 422, \"Invalid list query.\");\n }\n const filters = Object.fromEntries(\n (options.filters ?? [])\n .filter((key) => query[key] !== undefined)\n .map((key) => [key, query[key]]),\n ) as Partial<Omit<Query, keyof ListQuery>>;\n const result = await list({\n ...filters,\n page,\n limit: Math.min(requestedLimit, maxLimit),\n paginate: true,\n paginationMode: \"pages\",\n ...(query.orderBy === undefined\n ? {}\n : {\n orderBy: [query.orderBy, query.orderDir ?? \"asc\"] as [string, \"asc\" | \"desc\"],\n }),\n });\n return { [options.pluralKey]: result.data, pagination: result.pagination } as Record<\n Key,\n Item[]\n > & { pagination: PaginationResult<Item>[\"pagination\"] };\n}\n"],"mappings":";;;AA4CA,eAAsB,aACpB,SACA,MACA,SACsC;CACtC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,IACE,CAAC,OAAO,cAAc,QAAQ,KAC9B,WAAW,KACX,CAAC,OAAO,cAAc,YAAY,KAClC,eAAe,KACf,QAAQ,cAAc,gBACtB,CAAC,QAAQ,WAET,MAAM,IAAI,UAAU,qCAAqC;CAE3D,MAAM,QAAQ,QAAQ,UAAU;CAChC,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,iBAAiB,MAAM,SAAS;CACtC,IACE,CAAC,OAAO,cAAc,IAAI,KAC1B,OAAO,KACP,CAAC,OAAO,cAAc,cAAc,KACpC,iBAAiB,KAChB,MAAM,YAAY,UAAa,CAAC,QAAQ,QAAQ,SAAS,MAAM,OAAO,KACtE,MAAM,aAAa,UAAa,MAAM,aAAa,SAAS,MAAM,aAAa,QAEhF,MAAM,IAAI,SAAS,oBAAoB,KAAK,qBAAqB;CAOnE,MAAM,SAAS,MAAM,KAAK;EACxB,GANc,OAAO,aACpB,QAAQ,WAAW,CAAC,EAAC,CACnB,QAAQ,QAAQ,MAAM,SAAS,MAAS,CAAC,CACzC,KAAK,QAAQ,CAAC,KAAK,MAAM,IAAI,CAAC,CAGxB;EACT;EACA,OAAO,KAAK,IAAI,gBAAgB,QAAQ;EACxC,UAAU;EACV,gBAAgB;EAChB,GAAI,MAAM,YAAY,SAClB,CAAC,IACD,EACE,SAAS,CAAC,MAAM,SAAS,MAAM,YAAY,KAAK,EAClD;CACN,CAAC;CACD,OAAO;GAAG,QAAQ,YAAY,OAAO;EAAM,YAAY,OAAO;CAAW;AAI3E"}
@@ -1 +1 @@
1
- {"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;;;wBA+CgB,mBACd,SAAS,cACT,UAAU,WACT,QAAQ;;;;wBAuNK,EAAE,iBAAiB,eAAe"}
1
+ {"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;;;wBAgDgB,mBACd,SAAS,cACT,UAAU,WACT,QAAQ;;;;wBAqOK,EAAE,iBAAiB,eAAe"}
@@ -3,7 +3,8 @@ import { requestContext } from "../context/request-context.mjs";
3
3
  import "../../utils/index.mjs";
4
4
  import { applyCspHeader } from "../csp.mjs";
5
5
  import { runDefaultCsrfGuard } from "../csrf-default-guard.mjs";
6
- import { HttpError } from "../errors/errors.mjs";
6
+ import { setResponseAppError } from "../error-response.mjs";
7
+ import { AppError, HttpError } from "../errors/errors.mjs";
7
8
  import { mapRequestError } from "../error-mapper.mjs";
8
9
  import { buildTracingContext, dispatchPhase, isTracingEnabled } from "../tracing/tracing-dispatcher.mjs";
9
10
  import "../tracing/index.mjs";
@@ -85,7 +86,7 @@ function createRequestStore(request, response) {
85
86
  * @internal
86
87
  */
87
88
  function resolveRequestErrorStatus(error) {
88
- if (error instanceof HttpError) return error.status;
89
+ if (error instanceof HttpError || error instanceof AppError) return error.status;
89
90
  if (error instanceof DatabaseWriterValidationError) return baseConfig.get("http.modelValidationErrorStatus", 500);
90
91
  }
91
92
  /**
@@ -118,6 +119,15 @@ function reportUnhandledRequestError(error, request) {
118
119
  */
119
120
  function handleRequestError(error, response, request) {
120
121
  response.header("Cache-Control", "private, no-store");
122
+ if (error instanceof AppError) {
123
+ if (error.status >= 500) log.error("http", "request-error", error, { requestId: request.id });
124
+ setResponseAppError(response.baseResponse, error);
125
+ return response.setStatusCode(error.status).send({ error: {
126
+ code: error.code,
127
+ message: error.publicMessage,
128
+ ...error.details === void 0 ? {} : { details: error.details }
129
+ } });
130
+ }
121
131
  if (error instanceof HttpError) {
122
132
  if (error.status >= 500) log.error("http", "request-error", error, { requestId: request.id });
123
133
  const payload = { error: error.message };
@@ -1 +1 @@
1
- {"version":3,"file":"inject-request-context.mjs","names":["config","requestContextInstance"],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { mapRequestError } from \"../error-mapper\";\nimport { HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (thrown) {\n const error = mapRequestError(thrown, request);\n\n logRequestError(error, request);\n return handleRequestError(error, response, request);\n }\n });\n}\n\n/**\n * The HTTP status an error will be answered with, or `undefined` when it is not\n * one of the known HTTP-answerable shapes (those fall through to the opaque 500).\n *\n * Single source for `handleRequestError` and the request logger, so the rule\n * that decides the response status is the same rule that decides the log level.\n * @internal\n */\nfunction resolveRequestErrorStatus(error: unknown): number | undefined {\n if (error instanceof HttpError) {\n return error.status;\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n return config.get(\"http.modelValidationErrorStatus\", 500);\n }\n\n return undefined;\n}\n\n/**\n * Log a request error at the right severity. An error answered with a 4xx is an\n * expected client error (a thrown 404/409/422): one `warn` line, no stack.\n * Everything else (5xx, unknown errors) keeps the error-level entry with its stack.\n * @internal\n */\nfunction logRequestError(error: unknown, request: Request<any>) {\n const status = resolveRequestErrorStatus(error);\n\n if (status !== undefined && status < 500 && error instanceof Error) {\n request.log(`${error.name}: ${error.message} (${status})`, \"warn\");\n\n return;\n }\n\n request.log(error, \"error\");\n}\n\n/**\n * Unconditional floor for an unhandled request error (canon 8d3c13a8): route it\n * through the logger, and when no logger channel is configured (nothing would\n * record it) fall back to `console.error` so the only copy is never lost.\n * @internal\n */\nfunction reportUnhandledRequestError(error: unknown, request: Request<any>) {\n log.error(\"http\", \"unhandled-request-error\", error, { requestId: request.id });\n\n if (log.channels.length === 0) {\n console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);\n }\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(\n error: unknown,\n response: Response,\n request: Request<any>,\n): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof HttpError) {\n // 5xx HttpErrors (e.g. `ServerError`) are server faults: send them to the\n // logger channels too, tagged with the request id.\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n const status = resolveRequestErrorStatus(error) as number;\n\n // A 4xx is an expected client error, already logged as a one-line warn by\n // `logRequestError`; only a 5xx gets the error-level entry with its stack.\n if (status >= 500) {\n log.error(\"http\", \"model-write-validation-error\", error, {\n requestId: request.id,\n errors: error.errors,\n });\n }\n\n // A 4xx status means the app treats this as the client's fault, so the\n // field errors are useful to it; a 5xx stays opaque.\n if (status < 500) {\n return response.setStatusCode(status).send({\n errors: error.errors,\n });\n }\n\n return response.setStatusCode(status).send({\n error: \"Internal server error.\",\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n reportUnhandledRequestError(error, request);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: Record<string, unknown>): string {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAS,qBAAqB,SAAkB,UAAoB;CAClE,MAAM,kBAAkBA,WAAO,IAAI,kBAAkB,CAAC,CAAwB;CAE9E,IAAI,gBAAgB,YAAY,OAAO;CAEvC,MAAM,aAAa,gBAAgB,UAAU;CAE7C,SAAS,OAAO,YAAY,QAAQ,EAAE;AACxC;;;;;;AAOA,SAAgB,mBACd,SACA,UAC2B;CAC3B,qBAAqB,SAAS,QAAQ;CAOtC,eAAe,SAAS,QAAQ;CAIhC,MAAM,mBAAmB,eAAe,YAAY;EAAE;EAAS;CAAS,CAAC;CAGzE,OAAO,eAAe,OAAO,kBAAkB,YAAY;EACzD,IAAI;GAOF,MAAM,oBAAoB,MAAM,oBAAoB,SAAS,UAAU,IAAI,WAAW;IACpF,IAAI,MACF,QACA,sCACA,IAAI,MAAM,8CAA8C,QAAQ,CAClE;GACF,CAAC;GAED,IAAI,mBACF,OAAO;GAIT,MAAM,SAAS,MAAM,QAAQ,cAAc;GAE3C,IAAI,QACF,OAAO;GAIT,QAAQ,QAAQ,mBAAmB,QAAQ,KAAK;GAEhD,MAAM,UAAU,QAAQ,WAAW;GAEnC,QAAQ,IAAI,qBAAqB,MAAM;GAEvC,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,mBAAmB,iBAAiB,YAAY,IAAI,IAAI;GAE9D,MAAM,SAAS,MAAM,QAAQ;IAAE;IAAS;GAAS,CAAC;GAElD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;GAClC,CAAC;GAGH,QAAQ,IAAI,iCAAiC,SAAS;GAEtD,QAAQ,QAAQ,kBAAkB,QAAQ,KAAK;GAE/C,OAAO;EACT,SAAS,QAAQ;GACf,MAAM,QAAQ,gBAAgB,QAAQ,OAAO;GAE7C,gBAAgB,OAAO,OAAO;GAC9B,OAAO,mBAAmB,OAAO,UAAU,OAAO;EACpD;CACF,CAAC;AACH;;;;;;;;;AAUA,SAAS,0BAA0B,OAAoC;CACrE,IAAI,iBAAiB,WACnB,OAAO,MAAM;CAGf,IAAI,iBAAiB,+BACnB,OAAOA,WAAO,IAAI,mCAAmC,GAAG;AAI5D;;;;;;;AAQA,SAAS,gBAAgB,OAAgB,SAAuB;CAC9D,MAAM,SAAS,0BAA0B,KAAK;CAE9C,IAAI,WAAW,UAAa,SAAS,OAAO,iBAAiB,OAAO;EAClE,QAAQ,IAAI,GAAG,MAAM,KAAK,IAAI,MAAM,QAAQ,IAAI,OAAO,IAAI,MAAM;EAEjE;CACF;CAEA,QAAQ,IAAI,OAAO,OAAO;AAC5B;;;;;;;AAQA,SAAS,4BAA4B,OAAgB,SAAuB;CAC1E,IAAI,MAAM,QAAQ,2BAA2B,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;CAE7E,IAAI,IAAI,SAAS,WAAW,GAC1B,QAAQ,MAAM,8CAA8C,QAAQ,GAAG,IAAI,KAAK;AAEpF;;;;;AAMA,SAAS,mBACP,OACA,UACA,SACkB;CAiBlB,SAAS,OAAO,iBAAiB,mBAAmB;CAEpD,IAAI,iBAAiB,WAAW;EAG9B,IAAI,MAAM,UAAU,KAClB,IAAI,MAAM,QAAQ,iBAAiB,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;EAGrE,MAAM,UAAyB,EAC7B,OAAO,MAAM,QACf;EACA,IAAI,MAAM,SACR,QAAQ,UAAU,MAAM;EAG1B,IAAI,YAAY,MAAM,eACpB,QAAQ,QAAQ,MAAM;EAGxB,OAAO,SAAS,cAAc,MAAM,MAAM,CAAC,CAAC,KAAK,OAAO;CAC1D;CAEA,IAAI,iBAAiB,+BAA+B;EAClD,MAAM,SAAS,0BAA0B,KAAK;EAI9C,IAAI,UAAU,KACZ,IAAI,MAAM,QAAQ,gCAAgC,OAAO;GACvD,WAAW,QAAQ;GACnB,QAAQ,MAAM;EAChB,CAAC;EAKH,IAAI,SAAS,KACX,OAAO,SAAS,cAAc,MAAM,CAAC,CAAC,KAAK,EACzC,QAAQ,MAAM,OAChB,CAAC;EAGH,OAAO,SAAS,cAAc,MAAM,CAAC,CAAC,KAAK,EACzC,OAAO,yBACT,CAAC;CACH;CAOA,4BAA4B,OAAO,OAAO;CAE1C,OAAO,SAAS,YAAY,EAC1B,OAAO,yBACT,CAAC;AACH;;;;AAKA,SAAgB,EAAE,SAAiB,cAAgD;CACjF,OACEC,eAAuB,WAAW,CAAC,EAAE,MAAM,SAAS,YAAY,KAChE,MAAM,SAAS,YAAY;AAE/B"}
1
+ {"version":3,"file":"inject-request-context.mjs","names":["config","requestContextInstance"],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { setResponseAppError } from \"../error-response\";\nimport { mapRequestError } from \"../error-mapper\";\nimport { AppError, HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (thrown) {\n const error = mapRequestError(thrown, request);\n\n logRequestError(error, request);\n return handleRequestError(error, response, request);\n }\n });\n}\n\n/**\n * The HTTP status an error will be answered with, or `undefined` when it is not\n * one of the known HTTP-answerable shapes (those fall through to the opaque 500).\n *\n * Single source for `handleRequestError` and the request logger, so the rule\n * that decides the response status is the same rule that decides the log level.\n * @internal\n */\nfunction resolveRequestErrorStatus(error: unknown): number | undefined {\n if (error instanceof HttpError || error instanceof AppError) {\n return error.status;\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n return config.get(\"http.modelValidationErrorStatus\", 500);\n }\n\n return undefined;\n}\n\n/**\n * Log a request error at the right severity. An error answered with a 4xx is an\n * expected client error (a thrown 404/409/422): one `warn` line, no stack.\n * Everything else (5xx, unknown errors) keeps the error-level entry with its stack.\n * @internal\n */\nfunction logRequestError(error: unknown, request: Request<any>) {\n const status = resolveRequestErrorStatus(error);\n\n if (status !== undefined && status < 500 && error instanceof Error) {\n request.log(`${error.name}: ${error.message} (${status})`, \"warn\");\n\n return;\n }\n\n request.log(error, \"error\");\n}\n\n/**\n * Unconditional floor for an unhandled request error (canon 8d3c13a8): route it\n * through the logger, and when no logger channel is configured (nothing would\n * record it) fall back to `console.error` so the only copy is never lost.\n * @internal\n */\nfunction reportUnhandledRequestError(error: unknown, request: Request<any>) {\n log.error(\"http\", \"unhandled-request-error\", error, { requestId: request.id });\n\n if (log.channels.length === 0) {\n console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);\n }\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(\n error: unknown,\n response: Response,\n request: Request<any>,\n): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof AppError) {\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n setResponseAppError(response.baseResponse, error);\n return response.setStatusCode(error.status).send({\n error: {\n code: error.code,\n message: error.publicMessage,\n ...(error.details === undefined ? {} : { details: error.details }),\n },\n });\n }\n\n if (error instanceof HttpError) {\n // 5xx HttpErrors (e.g. `ServerError`) are server faults: send them to the\n // logger channels too, tagged with the request id.\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n const status = resolveRequestErrorStatus(error) as number;\n\n // A 4xx is an expected client error, already logged as a one-line warn by\n // `logRequestError`; only a 5xx gets the error-level entry with its stack.\n if (status >= 500) {\n log.error(\"http\", \"model-write-validation-error\", error, {\n requestId: request.id,\n errors: error.errors,\n });\n }\n\n // A 4xx status means the app treats this as the client's fault, so the\n // field errors are useful to it; a 5xx stays opaque.\n if (status < 500) {\n return response.setStatusCode(status).send({\n errors: error.errors,\n });\n }\n\n return response.setStatusCode(status).send({\n error: \"Internal server error.\",\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n reportUnhandledRequestError(error, request);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: Record<string, unknown>): string {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,qBAAqB,SAAkB,UAAoB;CAClE,MAAM,kBAAkBA,WAAO,IAAI,kBAAkB,CAAC,CAAwB;CAE9E,IAAI,gBAAgB,YAAY,OAAO;CAEvC,MAAM,aAAa,gBAAgB,UAAU;CAE7C,SAAS,OAAO,YAAY,QAAQ,EAAE;AACxC;;;;;;AAOA,SAAgB,mBACd,SACA,UAC2B;CAC3B,qBAAqB,SAAS,QAAQ;CAOtC,eAAe,SAAS,QAAQ;CAIhC,MAAM,mBAAmB,eAAe,YAAY;EAAE;EAAS;CAAS,CAAC;CAGzE,OAAO,eAAe,OAAO,kBAAkB,YAAY;EACzD,IAAI;GAOF,MAAM,oBAAoB,MAAM,oBAAoB,SAAS,UAAU,IAAI,WAAW;IACpF,IAAI,MACF,QACA,sCACA,IAAI,MAAM,8CAA8C,QAAQ,CAClE;GACF,CAAC;GAED,IAAI,mBACF,OAAO;GAIT,MAAM,SAAS,MAAM,QAAQ,cAAc;GAE3C,IAAI,QACF,OAAO;GAIT,QAAQ,QAAQ,mBAAmB,QAAQ,KAAK;GAEhD,MAAM,UAAU,QAAQ,WAAW;GAEnC,QAAQ,IAAI,qBAAqB,MAAM;GAEvC,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,mBAAmB,iBAAiB,YAAY,IAAI,IAAI;GAE9D,MAAM,SAAS,MAAM,QAAQ;IAAE;IAAS;GAAS,CAAC;GAElD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;GAClC,CAAC;GAGH,QAAQ,IAAI,iCAAiC,SAAS;GAEtD,QAAQ,QAAQ,kBAAkB,QAAQ,KAAK;GAE/C,OAAO;EACT,SAAS,QAAQ;GACf,MAAM,QAAQ,gBAAgB,QAAQ,OAAO;GAE7C,gBAAgB,OAAO,OAAO;GAC9B,OAAO,mBAAmB,OAAO,UAAU,OAAO;EACpD;CACF,CAAC;AACH;;;;;;;;;AAUA,SAAS,0BAA0B,OAAoC;CACrE,IAAI,iBAAiB,aAAa,iBAAiB,UACjD,OAAO,MAAM;CAGf,IAAI,iBAAiB,+BACnB,OAAOA,WAAO,IAAI,mCAAmC,GAAG;AAI5D;;;;;;;AAQA,SAAS,gBAAgB,OAAgB,SAAuB;CAC9D,MAAM,SAAS,0BAA0B,KAAK;CAE9C,IAAI,WAAW,UAAa,SAAS,OAAO,iBAAiB,OAAO;EAClE,QAAQ,IAAI,GAAG,MAAM,KAAK,IAAI,MAAM,QAAQ,IAAI,OAAO,IAAI,MAAM;EAEjE;CACF;CAEA,QAAQ,IAAI,OAAO,OAAO;AAC5B;;;;;;;AAQA,SAAS,4BAA4B,OAAgB,SAAuB;CAC1E,IAAI,MAAM,QAAQ,2BAA2B,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;CAE7E,IAAI,IAAI,SAAS,WAAW,GAC1B,QAAQ,MAAM,8CAA8C,QAAQ,GAAG,IAAI,KAAK;AAEpF;;;;;AAMA,SAAS,mBACP,OACA,UACA,SACkB;CAiBlB,SAAS,OAAO,iBAAiB,mBAAmB;CAEpD,IAAI,iBAAiB,UAAU;EAC7B,IAAI,MAAM,UAAU,KAClB,IAAI,MAAM,QAAQ,iBAAiB,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;EAErE,oBAAoB,SAAS,cAAc,KAAK;EAChD,OAAO,SAAS,cAAc,MAAM,MAAM,CAAC,CAAC,KAAK,EAC/C,OAAO;GACL,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,GAAI,MAAM,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;EAClE,EACF,CAAC;CACH;CAEA,IAAI,iBAAiB,WAAW;EAG9B,IAAI,MAAM,UAAU,KAClB,IAAI,MAAM,QAAQ,iBAAiB,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;EAGrE,MAAM,UAAyB,EAC7B,OAAO,MAAM,QACf;EACA,IAAI,MAAM,SACR,QAAQ,UAAU,MAAM;EAG1B,IAAI,YAAY,MAAM,eACpB,QAAQ,QAAQ,MAAM;EAGxB,OAAO,SAAS,cAAc,MAAM,MAAM,CAAC,CAAC,KAAK,OAAO;CAC1D;CAEA,IAAI,iBAAiB,+BAA+B;EAClD,MAAM,SAAS,0BAA0B,KAAK;EAI9C,IAAI,UAAU,KACZ,IAAI,MAAM,QAAQ,gCAAgC,OAAO;GACvD,WAAW,QAAQ;GACnB,QAAQ,MAAM;EAChB,CAAC;EAKH,IAAI,SAAS,KACX,OAAO,SAAS,cAAc,MAAM,CAAC,CAAC,KAAK,EACzC,QAAQ,MAAM,OAChB,CAAC;EAGH,OAAO,SAAS,cAAc,MAAM,CAAC,CAAC,KAAK,EACzC,OAAO,yBACT,CAAC;CACH;CAOA,4BAA4B,OAAO,OAAO;CAE1C,OAAO,SAAS,YAAY,EAC1B,OAAO,yBACT,CAAC;AACH;;;;AAKA,SAAgB,EAAE,SAAiB,cAAgD;CACjF,OACEC,eAAuB,WAAW,CAAC,EAAE,MAAM,SAAS,YAAY,KAChE,MAAM,SAAS,YAAY;AAE/B"}
@@ -1,5 +1,5 @@
1
- import { normalizeRequestPath } from "../router/normalize-request-path.mjs";
2
1
  import { registerErrorResponseFormatter } from "./error-response.mjs";
2
+ import { normalizeRequestPath } from "../router/normalize-request-path.mjs";
3
3
  import baseConfig from "@mongez/config";
4
4
  import Fastify from "fastify";
5
5
 
package/esm/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
1
+ import { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
2
2
  import { ERROR_CODES, ERROR_CODES_DOCS_URL, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, WarlockErrorCode, errorCodeDocsUrl, errorCodeOf, explainErrorCode, isWarlockErrorCode } from "./errors/error-codes.mjs";
3
3
  import { WarlockError } from "./errors/warlock-error.mjs";
4
4
  import { normalizeRoutePath } from "./router/normalize-route-path.mjs";
@@ -77,6 +77,11 @@ import { TracingContextSource, buildTracingContext, dispatchPhase, dispatchReque
77
77
  import { RequestContextStore, requestContext, useCurrentUser, useRequest, useRequestStore } from "./http/context/request-context.mjs";
78
78
  import { requestMemo } from "./http/context/request-memo.mjs";
79
79
  import { ModelResourceRegistry, Serialized, SerializedWire } from "./http/serialized.mjs";
80
+ import { RepositoryManager } from "./repositories/repository.manager.mjs";
81
+ import { RepositoryAdapterContract } from "./repositories/contracts/repository-adapter.contract.mjs";
82
+ import { AllRepositoryOptions, CachedRepositoryOptions, ChunkCallback, CursorPaginationOptions, CursorPaginationResult, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, PaginationMode, PaginationResult, RepositoryConfigurations, RepositoryEvent, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, SaveMode, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, WhereOperator } from "./repositories/contracts/types.mjs";
83
+ import { AggregateExpressionInput, AggregateExpressions, GroupByFields, QueryBuilderContract } from "./repositories/contracts/query-builder.contract.mjs";
84
+ import { ListEndpointBody, ListEndpointOptions, ListEndpointRepositoryOptions, ListQuery, listEndpoint } from "./http/list-endpoint.mjs";
80
85
  import "./http/index.mjs";
81
86
  import { LocalizedObject, getLocalized } from "./utils/get-localized.mjs";
82
87
  import { ResourceFieldBuilder } from "./resource/resource-field-builder.mjs";
@@ -116,6 +121,7 @@ import { ConfigIssue, ConfigModuleEntry, ConfigOf, ConfigSchema, ConfigSchemaOpt
116
121
  import { setConfig } from "./config/config-setter.mjs";
117
122
  import { ConfigSpecialHandlers, configSpecialHandlers } from "./config/config-special-handlers.mjs";
118
123
  import "./config/index.mjs";
124
+ import { BudgetPage, BudgetViolation, BuildBudgetReport, BuildBudgets, PageBudget } from "./production/build-budgets.mjs";
119
125
  import { WarlockConfig } from "./warlock-config/types.mjs";
120
126
  import { Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority } from "./connectors/types.mjs";
121
127
  import { BaseConnector } from "./connectors/base-connector.mjs";
@@ -179,10 +185,6 @@ import { exampleFromSchema } from "./openapi/postman/example-from-schema.mjs";
179
185
  import { DEFAULT_POSTMAN_BASE_URL, POSTMAN_COLLECTION_SCHEMA, openApiToPostmanCollection } from "./openapi/postman/openapi-to-postman-collection.mjs";
180
186
  import "./openapi/index.mjs";
181
187
  import { renderReact } from "./react/index.mjs";
182
- import { RepositoryManager } from "./repositories/repository.manager.mjs";
183
- import { RepositoryAdapterContract } from "./repositories/contracts/repository-adapter.contract.mjs";
184
- import { AllRepositoryOptions, CachedRepositoryOptions, ChunkCallback, CursorPaginationOptions, CursorPaginationResult, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, PaginationMode, PaginationResult, RepositoryConfigurations, RepositoryEvent, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, SaveMode, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, WhereOperator } from "./repositories/contracts/types.mjs";
185
- import { AggregateExpressionInput, AggregateExpressions, GroupByFields, QueryBuilderContract } from "./repositories/contracts/query-builder.contract.mjs";
186
188
  import { CascadeAdapter, UPDATE_MANY_BATCH_SIZE } from "./repositories/adapters/cascade/cascade-adapter.mjs";
187
189
  import { CascadeQueryBuilder } from "./repositories/adapters/cascade/cascade-query-builder.mjs";
188
190
  import "./repositories/index.mjs";
@@ -233,7 +235,7 @@ import "./warlock-config/index.mjs";
233
235
  import { env } from "@mongez/dotenv";
234
236
  import { colors } from "@mongez/copper";
235
237
  export * from "@mongez/localization";
236
- export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, 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, CastOutput, ChunkCallback, ClockSource, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConfigIssue, ConfigKey, ConfigKeyRegistry, ConfigModuleEntry, ConfigName, ConfigOf, ConfigRegistry, ConfigSchema, ConfigSchemaOptions, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentAppModuleEntry, type DevelopmentAppModules, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, ERROR_CODES, ERROR_CODES_DOCS_URL, EncryptionConfigurations, EncryptionPasswordConfigurations, EntityTag, Environment, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, type HttpErrorResponseContext, type HttpErrorResponseFormatter, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, IdsSource, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, type IpFilterOptions, JavaScriptRuntime, JavaScriptRuntimeName, ListOptions, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, 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, MemorySecretBackend, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NULLABLE_RESOURCE, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, NullableResource, NullableResourceTarget, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, 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, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestMethod, RequestTranslator, ResolveImageVariantInput, type ResolvedCLICommandOption, ResolvedImageVariant, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, ResponseStreamOptions, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SUPPORTED_RUNTIMES_DOCS_URL, SafeFetchOptions, SafeFetchResult, SafeRedirectOptions, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, type SecretBackend, type SecretBackendType, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, StaticMountOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, ValidationResponseConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarlockError, WarlockErrorCode, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
238
+ export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppError, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, 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, type BudgetPage, type BudgetViolation, type BuildBudgetReport, type BuildBudgets, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, CastOutput, ChunkCallback, ClockSource, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConfigIssue, ConfigKey, ConfigKeyRegistry, ConfigModuleEntry, ConfigName, ConfigOf, ConfigRegistry, ConfigSchema, ConfigSchemaOptions, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentAppModuleEntry, type DevelopmentAppModules, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, ERROR_CODES, ERROR_CODES_DOCS_URL, EncryptionConfigurations, EncryptionPasswordConfigurations, EntityTag, Environment, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, type HttpErrorResponseContext, type HttpErrorResponseFormatter, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, IdsSource, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, type IpFilterOptions, JavaScriptRuntime, JavaScriptRuntimeName, ListEndpointBody, ListEndpointOptions, ListEndpointRepositoryOptions, ListOptions, ListQuery, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, 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, MemorySecretBackend, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NULLABLE_RESOURCE, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, NullableResource, NullableResourceTarget, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, type PageBudget, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, 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, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestMethod, RequestTranslator, ResolveImageVariantInput, type ResolvedCLICommandOption, ResolvedImageVariant, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, ResponseStreamOptions, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SUPPORTED_RUNTIMES_DOCS_URL, SafeFetchOptions, SafeFetchResult, SafeRedirectOptions, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, type SecretBackend, type SecretBackendType, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, StaticMountOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, ValidationResponseConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarlockError, WarlockErrorCode, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listEndpoint, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
237
239
  import "./config/types.mjs";
238
240
  import "./http/request.mjs";
239
241
  import "./http/serialized.mjs";