@warlock.js/core 5.34.3 → 5.36.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 (281) hide show
  1. package/CHANGELOG.md +69 -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 +15 -1
  49. package/esm/dev-server/module-loader.mjs.map +1 -1
  50. package/esm/dev-server/parse-imports.mjs +1 -1
  51. package/esm/dev-server/special-file-patterns.mjs +4 -1
  52. package/esm/dev-server/special-file-patterns.mjs.map +1 -1
  53. package/esm/dev-server/type-generator.mjs +1 -1
  54. package/esm/e2e/cdp.d.mts.map +1 -1
  55. package/esm/e2e/cdp.mjs +9 -2
  56. package/esm/e2e/cdp.mjs.map +1 -1
  57. package/esm/e2e/index.d.mts +2 -2
  58. package/esm/e2e/page.d.mts +14 -1
  59. package/esm/e2e/page.d.mts.map +1 -1
  60. package/esm/e2e/page.mjs +81 -8
  61. package/esm/e2e/page.mjs.map +1 -1
  62. package/esm/e2e/types.d.mts +49 -0
  63. package/esm/e2e/types.d.mts.map +1 -1
  64. package/esm/e2e/types.mjs.map +1 -1
  65. package/esm/errors/error-codes.d.mts +72 -0
  66. package/esm/errors/error-codes.d.mts.map +1 -1
  67. package/esm/errors/error-codes.mjs +72 -0
  68. package/esm/errors/error-codes.mjs.map +1 -1
  69. package/esm/errors/index.d.mts +2 -2
  70. package/esm/errors/index.mjs +2 -2
  71. package/esm/generations/add-command.action.mjs +2 -0
  72. package/esm/generations/add-command.action.mjs.map +1 -1
  73. package/esm/generations/design-system-payload.mjs +53 -0
  74. package/esm/generations/design-system-payload.mjs.map +1 -0
  75. package/esm/generations/features/design-system.feature.mjs +38 -0
  76. package/esm/generations/features/design-system.feature.mjs.map +1 -0
  77. package/esm/generations/features/index.mjs +3 -1
  78. package/esm/generations/features/index.mjs.map +1 -1
  79. package/esm/generations/features/notifications.feature.mjs +13 -2
  80. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  81. package/esm/generations/features/test.feature.mjs +48 -13
  82. package/esm/generations/features/test.feature.mjs.map +1 -1
  83. package/esm/generations/features/web.feature.mjs +3 -3
  84. package/esm/generations/features/web.feature.mjs.map +1 -1
  85. package/esm/generations/stubs.mjs +9 -5
  86. package/esm/generations/stubs.mjs.map +1 -1
  87. package/esm/http/error-mapper.d.mts +1 -1
  88. package/esm/http/error-mapper.mjs +3 -3
  89. package/esm/http/error-mapper.mjs.map +1 -1
  90. package/esm/http/error-response.d.mts +3 -0
  91. package/esm/http/error-response.d.mts.map +1 -1
  92. package/esm/http/error-response.mjs +8 -2
  93. package/esm/http/error-response.mjs.map +1 -1
  94. package/esm/http/errors/errors.d.mts +8 -0
  95. package/esm/http/errors/errors.d.mts.map +1 -1
  96. package/esm/http/errors/errors.mjs +13 -1
  97. package/esm/http/errors/errors.mjs.map +1 -1
  98. package/esm/http/index.d.mts +3 -2
  99. package/esm/http/index.mjs +3 -2
  100. package/esm/http/list-endpoint.d.mts +35 -0
  101. package/esm/http/list-endpoint.d.mts.map +1 -0
  102. package/esm/http/list-endpoint.mjs +28 -0
  103. package/esm/http/list-endpoint.mjs.map +1 -0
  104. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  105. package/esm/http/middleware/inject-request-context.mjs +12 -2
  106. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  107. package/esm/http/server.mjs +1 -1
  108. package/esm/index.d.mts +10 -6
  109. package/esm/index.mjs +5 -2
  110. package/esm/localization/index.mjs +3 -1
  111. package/esm/localization/translation-usage-graph.d.mts +49 -0
  112. package/esm/localization/translation-usage-graph.d.mts.map +1 -0
  113. package/esm/localization/translation-usage-graph.mjs +128 -0
  114. package/esm/localization/translation-usage-graph.mjs.map +1 -0
  115. package/esm/localization/translation-usage.d.mts +85 -0
  116. package/esm/localization/translation-usage.d.mts.map +1 -0
  117. package/esm/localization/translation-usage.mjs +307 -0
  118. package/esm/localization/translation-usage.mjs.map +1 -0
  119. package/esm/openapi/security.mjs +12 -4
  120. package/esm/openapi/security.mjs.map +1 -1
  121. package/esm/openapi/types.d.mts +2 -0
  122. package/esm/openapi/types.d.mts.map +1 -1
  123. package/esm/production/build-budgets.d.mts +64 -0
  124. package/esm/production/build-budgets.d.mts.map +1 -0
  125. package/esm/production/build-budgets.mjs +109 -0
  126. package/esm/production/build-budgets.mjs.map +1 -0
  127. package/esm/production/production-builder.mjs +13 -1
  128. package/esm/production/production-builder.mjs.map +1 -1
  129. package/esm/production/resolve-build-config.d.mts +1 -1
  130. package/esm/production/resolve-build-config.d.mts.map +1 -1
  131. package/esm/production/resolve-build-config.mjs.map +1 -1
  132. package/esm/production/route-registration-snapshot.mjs +5 -3
  133. package/esm/production/route-registration-snapshot.mjs.map +1 -1
  134. package/esm/restful/restful.d.mts +1 -1
  135. package/esm/router/router.d.mts +2 -0
  136. package/esm/router/router.d.mts.map +1 -1
  137. package/esm/router/router.mjs +4 -1
  138. package/esm/router/router.mjs.map +1 -1
  139. package/esm/router/types.d.mts +19 -0
  140. package/esm/router/types.d.mts.map +1 -1
  141. package/esm/tests/fakes/storage-fake.d.mts +3 -1
  142. package/esm/tests/fakes/storage-fake.d.mts.map +1 -1
  143. package/esm/tests/fakes/storage-fake.mjs +3 -3
  144. package/esm/tests/fakes/storage-fake.mjs.map +1 -1
  145. package/esm/tests/fakes/test-fakes.d.mts +3 -1
  146. package/esm/tests/fakes/test-fakes.d.mts.map +1 -1
  147. package/esm/tests/fakes/test-fakes.mjs +3 -2
  148. package/esm/tests/fakes/test-fakes.mjs.map +1 -1
  149. package/esm/tests/index.d.mts +4 -2
  150. package/esm/tests/index.mjs +3 -1
  151. package/esm/tests/load-unit-config.mjs +24 -0
  152. package/esm/tests/load-unit-config.mjs.map +1 -0
  153. package/esm/tests/response-contract.d.mts +32 -0
  154. package/esm/tests/response-contract.d.mts.map +1 -0
  155. package/esm/tests/response-contract.mjs +116 -0
  156. package/esm/tests/response-contract.mjs.map +1 -0
  157. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  158. package/esm/tests/start-http-development-server.mjs +10 -2
  159. package/esm/tests/start-http-development-server.mjs.map +1 -1
  160. package/esm/tests/test-lifecycle-state.mjs.map +1 -1
  161. package/esm/tests/test-locales.mjs +33 -0
  162. package/esm/tests/test-locales.mjs.map +1 -0
  163. package/esm/tests/test-runtime-scope.d.mts +15 -0
  164. package/esm/tests/test-runtime-scope.d.mts.map +1 -0
  165. package/esm/tests/test-runtime-scope.mjs +80 -0
  166. package/esm/tests/test-runtime-scope.mjs.map +1 -0
  167. package/esm/tests/vitest-setup.d.mts +13 -3
  168. package/esm/tests/vitest-setup.d.mts.map +1 -1
  169. package/esm/tests/vitest-setup.mjs +146 -18
  170. package/esm/tests/vitest-setup.mjs.map +1 -1
  171. package/esm/tooling/check/affected-files.d.mts +5 -0
  172. package/esm/tooling/check/affected-files.d.mts.map +1 -0
  173. package/esm/tooling/check/affected-files.mjs +56 -0
  174. package/esm/tooling/check/affected-files.mjs.map +1 -0
  175. package/esm/tooling/check/api-route-references.d.mts +16 -0
  176. package/esm/tooling/check/api-route-references.d.mts.map +1 -0
  177. package/esm/tooling/check/api-route-references.mjs +146 -0
  178. package/esm/tooling/check/api-route-references.mjs.map +1 -0
  179. package/esm/tooling/check/changed-files.d.mts +2 -0
  180. package/esm/tooling/check/changed-files.d.mts.map +1 -1
  181. package/esm/tooling/check/changed-files.mjs +2 -2
  182. package/esm/tooling/check/changed-files.mjs.map +1 -1
  183. package/esm/tooling/check/conventions-step.d.mts +7 -3
  184. package/esm/tooling/check/conventions-step.d.mts.map +1 -1
  185. package/esm/tooling/check/conventions-step.mjs +59 -8
  186. package/esm/tooling/check/conventions-step.mjs.map +1 -1
  187. package/esm/tooling/check/fixes.d.mts +8 -0
  188. package/esm/tooling/check/fixes.d.mts.map +1 -0
  189. package/esm/tooling/check/fixes.mjs +31 -0
  190. package/esm/tooling/check/fixes.mjs.map +1 -0
  191. package/esm/tooling/check/index.d.mts +12 -0
  192. package/esm/tooling/check/index.mjs +3 -2
  193. package/esm/tooling/check/run-check.d.mts +2 -0
  194. package/esm/tooling/check/run-check.d.mts.map +1 -1
  195. package/esm/tooling/check/run-check.mjs +23 -5
  196. package/esm/tooling/check/run-check.mjs.map +1 -1
  197. package/esm/tooling/check/run-tests.mjs +1 -1
  198. package/esm/tooling/check/source-ast.d.mts +1 -0
  199. package/esm/tooling/check/translation-conventions.mjs +32 -0
  200. package/esm/tooling/check/translation-conventions.mjs.map +1 -0
  201. package/esm/tooling/check/web-conventions.d.mts +10 -0
  202. package/esm/tooling/check/web-conventions.d.mts.map +1 -0
  203. package/esm/tooling/check/web-conventions.mjs +126 -0
  204. package/esm/tooling/check/web-conventions.mjs.map +1 -0
  205. package/esm/tooling/index.d.mts +7 -2
  206. package/esm/tooling/index.mjs +4 -2
  207. package/esm/tooling/inspect/collect-files.mjs +172 -0
  208. package/esm/tooling/inspect/collect-files.mjs.map +1 -0
  209. package/esm/tooling/inspect/collect-pages.mjs +3 -2
  210. package/esm/tooling/inspect/collect-pages.mjs.map +1 -1
  211. package/esm/tooling/inspect/collect-routes.mjs +1 -1
  212. package/esm/tooling/inspect/collect-routes.mjs.map +1 -1
  213. package/esm/tooling/inspect/explain-file.d.mts +12 -0
  214. package/esm/tooling/inspect/explain-file.d.mts.map +1 -0
  215. package/esm/tooling/inspect/explain-file.mjs +45 -0
  216. package/esm/tooling/inspect/explain-file.mjs.map +1 -0
  217. package/esm/tooling/inspect/index.d.mts +3 -2
  218. package/esm/tooling/inspect/index.mjs +2 -1
  219. package/esm/tooling/inspect/inspect-app.d.mts.map +1 -1
  220. package/esm/tooling/inspect/inspect-app.mjs +9 -3
  221. package/esm/tooling/inspect/inspect-app.mjs.map +1 -1
  222. package/esm/tooling/inspect/inspect-report.schema.mjs +34 -1
  223. package/esm/tooling/inspect/inspect-report.schema.mjs.map +1 -1
  224. package/esm/tooling/inspect/inspect-report.types.d.mts +17 -1
  225. package/esm/tooling/inspect/inspect-report.types.d.mts.map +1 -1
  226. package/esm/tooling/inspect/inspect-report.types.mjs +2 -1
  227. package/esm/tooling/inspect/inspect-report.types.mjs.map +1 -1
  228. package/esm/tooling/mcp/mcp-tools.d.mts.map +1 -1
  229. package/esm/tooling/mcp/mcp-tools.mjs +8 -2
  230. package/esm/tooling/mcp/mcp-tools.mjs.map +1 -1
  231. package/esm/tooling/problem.d.mts +4 -0
  232. package/esm/tooling/problem.d.mts.map +1 -1
  233. package/esm/tooling/problem.mjs +1 -0
  234. package/esm/tooling/problem.mjs.map +1 -1
  235. package/esm/tooling/syntax/ast.d.mts +2 -0
  236. package/esm/tooling/typecheck/run-typecheck.mjs +5 -1
  237. package/esm/tooling/typecheck/run-typecheck.mjs.map +1 -1
  238. package/esm/upgrade/codemods/index.mjs +2 -0
  239. package/esm/upgrade/codemods/index.mjs.map +1 -1
  240. package/esm/upgrade/codemods/vite-vitest.mjs +170 -0
  241. package/esm/upgrade/codemods/vite-vitest.mjs.map +1 -0
  242. package/esm/upgrade/notes.mjs +4 -0
  243. package/esm/upgrade/notes.mjs.map +1 -1
  244. package/esm/vite/index.d.mts +3 -1
  245. package/esm/vite/index.mjs +3 -1
  246. package/esm/vite/test-setup-reporter.d.mts +16 -0
  247. package/esm/vite/test-setup-reporter.d.mts.map +1 -0
  248. package/esm/vite/test-setup-reporter.mjs +55 -0
  249. package/esm/vite/test-setup-reporter.mjs.map +1 -0
  250. package/esm/vite/test-workers.d.mts +5 -0
  251. package/esm/vite/test-workers.d.mts.map +1 -0
  252. package/esm/vite/test-workers.mjs +38 -0
  253. package/esm/vite/test-workers.mjs.map +1 -0
  254. package/esm/warlock-config/index.d.mts +2 -1
  255. package/esm/warlock-config/types.d.mts +3 -0
  256. package/esm/warlock-config/types.d.mts.map +1 -1
  257. package/llms-full.txt +874 -9
  258. package/llms.txt +2 -0
  259. package/package.json +15 -14
  260. package/schemas/inspect-report.schema.json +47 -1
  261. package/skills/build-budgets/SKILL.md +51 -0
  262. package/skills/build-restful/SKILL.md +56 -0
  263. package/skills/configure-app/SKILL.md +7 -0
  264. package/skills/create-module/SKILL.md +9 -0
  265. package/skills/generate-web-ui/SKILL.md +71 -0
  266. package/skills/index.md +2 -2
  267. package/skills/register-route/SKILL.md +13 -0
  268. package/skills/run-app/SKILL.md +1 -1
  269. package/skills/send-mail/SKILL.md +25 -0
  270. package/skills/send-response/SKILL.md +50 -0
  271. package/skills/test-browser/SKILL.md +53 -0
  272. package/skills/test-http/SKILL.md +91 -0
  273. package/skills/test-service/SKILL.md +161 -3
  274. package/skills/upgrade-from-5-29/SKILL.md +109 -0
  275. package/skills/use-localization/SKILL.md +25 -0
  276. package/skills/warlock-check/SKILL.md +75 -1
  277. package/skills/warlock-inspect/SKILL.md +45 -2
  278. package/skills/warlock-mcp/SKILL.md +4 -0
  279. package/skills/write-cli-command/SKILL.md +18 -0
  280. package/esm/production/build-app-production.mjs +0 -14
  281. package/esm/production/build-app-production.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"web.feature.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/generations/features/web.feature.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n putFileAsync,\n} from \"../generation-fs\";\nimport type { CommandActionData } from \"../../commands/types\";\nimport { rootPath, srcPath } from \"../../utils\";\nimport { insertConnectorEntry } from \"./shared/insert-connector-entry\";\nimport { relocateConflictingHomeRoute } from \"./shared/relocate-conflicting-home-route\";\nimport { resolveContactScaffold } from \"./shared/resolve-contact-scaffold\";\nimport {\n webContactControllerStub,\n webContactRoutesStub,\n webHomePageStub,\n webHomeSetupStub,\n webRootStub,\n webRootSetupStub,\n} from \"../stubs\";\nimport { type FeatureDefinition, INSTALLED_WARLOCK_VERSION } from \"./types\";\n\n/** The one vite range shared by every feature (web's peer range is `>=7.3.5 <8`). */\nexport const VITE_RANGE = \"^7.3.5\";\n\n/**\n * Register the WebConnector in `warlock.config.ts`, and ONLY there.\n *\n * It belongs to the config array or to app code, never both. Both halves are\n * registered before app code loads — the CLI preloader in dev, the generated\n * entry in production — so also calling `connectorsManager.register(...)` in\n * `src/app/main.ts` boots the connector twice and installs every page route\n * twice. That surfaces at PRODUCTION boot as `Route name \"...\" is already\n * taken`, because pages and API routes share one route-name namespace.\n *\n * The config array is the half to prefer: `warlock build` reads the same array\n * to drain each connector's build contribution, so \"built for\" and \"boots with\"\n * cannot drift.\n *\n * String surgery rather than a TypeScript parse: `warlock.config.ts` is an\n * app-owned file that may carry any formatting, and a parse-and-print would\n * reformat the parts we did not come to change.\n */\nasync function registerWebConnector(): Promise<void> {\n const configPath = rootPath(\"warlock.config.ts\");\n\n if (!(await fileExistsAsync(configPath))) {\n console.log(\n `${colors.yellowBright(\"warlock.config.ts\")} not found — add this yourself:\\n` +\n ` import { webConnector } from \"@warlock.js/web/connector\";\\n` +\n ` export default defineConfig({ connectors: [webConnector()] });`,\n );\n\n return;\n }\n\n const current = await getFileAsync(configPath);\n\n if (current.includes(\"webConnector\")) {\n console.log(`${colors.yellowBright(\"webConnector\")} already registered, skipping...`);\n\n return;\n }\n\n const importLine = 'import { webConnector } from \"@warlock.js/web/connector\";';\n let next = current.includes(importLine) ? current : `${importLine}\\n${current}`;\n\n // An existing `connectors: [` gains one entry; otherwise the key is added to\n // the object `defineConfig` receives.\n const insertion = insertConnectorEntry(next, \"webConnector()\");\n\n if (insertion.status === \"already-present\") {\n return;\n }\n\n if (insertion.status === \"added\") {\n next = insertion.next;\n } else if (next.includes(\"defineConfig({\")) {\n next = next.replace(\"defineConfig({\", \"defineConfig({\\n connectors: [webConnector()],\");\n } else {\n console.log(\n `${colors.yellowBright(\"warlock.config.ts\")} has no recognisable defineConfig({...}) — ` +\n \"add `connectors: [webConnector()]` yourself.\",\n );\n\n return;\n }\n\n await putFileAsync(configPath, next);\n console.log(`${colors.green(\"✓\")} Registered webConnector in warlock.config.ts`);\n}\n\n/**\n * Scaffold the smallest page layer that renders, and register the connector.\n *\n * `src/web/root.tsx` is the sentinel for \"already scaffolded\" — the framework\n * ships a default root, so its presence means a human has been here.\n */\nasync function completeWebInstallation(_options: CommandActionData) {\n const rootFile = srcPath(\"web/root.tsx\");\n\n if (await fileExistsAsync(rootFile)) {\n console.log(`${colors.yellowBright(\"src/web\")} already scaffolded, skipping...`);\n } else {\n await ensureDirectoryAsync(srcPath(\"web\"));\n await putFileAsync(rootFile, webRootStub);\n const rootSetupFile = srcPath(\"web/root.setup.ts\");\n if (!(await fileExistsAsync(rootSetupFile))) {\n await putFileAsync(rootSetupFile, webRootSetupStub);\n }\n console.log(`${colors.green(\"✓\")} Created src/web/root.tsx`);\n\n const collision = await relocateConflictingHomeRoute();\n\n if (collision.outcome === \"relocated\") {\n console.log(\n `${colors.green(\"✓\")} Moved the existing ${colors.yellowBright('GET \"/\"')} route to ` +\n `${colors.yellowBright('\"/welcome\"')} in ${colors.yellowBright(`src/${collision.relativePath}`)} — ` +\n \"the new page owns `/` now, and the JSON welcome route still answers at /welcome.\",\n );\n }\n\n // The page is written ONLY when `/` is provably free. Writing it while\n // another handler holds `/` produces a homepage that 500s on first request,\n // which is precisely the outcome a scaffolder must never hand back.\n if (collision.outcome === \"conflict\" || collision.outcome === \"failed\") {\n const verb =\n collision.outcome === \"failed\" ? colors.redBright(\"✗\") : colors.yellowBright(\"!\");\n\n console.log(\n `${verb} Did not create src/web/index.page.tsx: ${collision.reason}.\\n` +\n ` The page setup declares ${colors.yellowBright('route.path = \"/\"')}, and two handlers on one ` +\n \"path is a 500 at request time, not a startup error.\\n\" +\n ` Free up ${colors.yellowBright('GET \"/\"')} under src/app — move it to a path of its own, ` +\n \"or remove it — then create src/web/index.page.tsx yourself. Giving the setup file a `config.route` other \" +\n \"than `/` works too.\",\n );\n\n // Non-zero on BOTH branches. The page layer this command exists to\n // scaffold was not scaffolded, and a 0 here is the exact \"looked like it\n // worked\" signal that put `/` in this state to begin with — a conflict we\n // declined to guess at is still an incomplete install, not a success.\n //\n // `exitCode` rather than `exit(1)`: the connector below still has to be\n // registered, and any other feature in the same `warlock add` invocation\n // still has to install, or the project is left half-wired on top of this.\n process.exitCode = 1;\n } else {\n await putFileAsync(srcPath(\"web/index.page.tsx\"), webHomePageStub);\n const homeSetupFile = srcPath(\"web/index.setup.ts\");\n if (!(await fileExistsAsync(homeSetupFile))) {\n await putFileAsync(homeSetupFile, webHomeSetupStub);\n }\n\n // Unlike root.tsx above, the contact controller and its routes file are\n // ordinary application files a project can already have — independently\n // of ever having run `warlock add web`. Each is guarded on its OWN\n // existence, not on the (already-consumed) root.tsx sentinel, so an\n // existing `contact` module is skipped rather than clobbered. See\n // resolveContactScaffold's doc comment for why.\n const contactPlan = resolveContactScaffold({\n controllerExists: await fileExistsAsync(\n srcPath(\"app/contact/controllers/contact.controller.ts\"),\n ),\n routesExists: await fileExistsAsync(srcPath(\"app/contact/routes.ts\")),\n });\n\n if (contactPlan.writeController) {\n await ensureDirectoryAsync(srcPath(\"app/contact/controllers\"));\n await putFileAsync(\n srcPath(\"app/contact/controllers/contact.controller.ts\"),\n webContactControllerStub,\n );\n }\n\n if (contactPlan.writeRoutes) {\n await ensureDirectoryAsync(srcPath(\"app/contact\"));\n await putFileAsync(srcPath(\"app/contact/routes.ts\"), webContactRoutesStub);\n }\n\n console.log(`${colors.green(\"✓\")} Created src/web/index.page.tsx`);\n\n for (const message of contactPlan.messages) {\n console.log(message);\n }\n }\n }\n\n await registerWebConnector();\n}\n\nexport const webFeature: FeatureDefinition = {\n description:\n \"Installs @warlock.js/web — SSR React pages served by the Warlock HTTP server. Scaffolds src/web (root.tsx + a home page) and registers the WebConnector in warlock.config.ts. Pages are opt-in: a Warlock app is an API until you add this.\",\n dependencies: {\n \"@warlock.js/web\": INSTALLED_WARLOCK_VERSION,\n \"@mongez/http\": \"^3.5.0\",\n \"@mongez/react-form\": \"^4.0.0\",\n \"@mongez/react-localization\": \"^3.4.7\",\n react: \"^19.2.3\",\n \"react-dom\": \"^19.2.3\",\n },\n devDependencies: {\n \"@types/react\": \"^19.2.7\",\n \"@types/react-dom\": \"^19.2.3\",\n // Loaded through `await import()` by the dev server only, so both are\n // optional peers of `web` rather than hard dependencies.\n vite: VITE_RANGE,\n \"@vitejs/plugin-react\": \"^5.2.0\",\n },\n onExecuting: completeWebInstallation,\n};\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAa,aAAa;;;;;;;;;;;;;;;;;;;AAoB1B,eAAe,uBAAsC;CACnD,MAAM,aAAa,SAAS,mBAAmB;CAE/C,IAAI,CAAE,MAAM,gBAAgB,UAAU,GAAI;EACxC,QAAQ,IACN,GAAG,OAAO,aAAa,mBAAmB,EAAE,+JAG9C;EAEA;CACF;CAEA,MAAM,UAAU,MAAM,aAAa,UAAU;CAE7C,IAAI,QAAQ,SAAS,cAAc,GAAG;EACpC,QAAQ,IAAI,GAAG,OAAO,aAAa,cAAc,EAAE,iCAAiC;EAEpF;CACF;CAEA,MAAM,aAAa;CACnB,IAAI,OAAO,QAAQ,SAAS,UAAU,IAAI,UAAU,GAAG,WAAW,IAAI;CAItE,MAAM,YAAY,qBAAqB,MAAM,gBAAgB;CAE7D,IAAI,UAAU,WAAW,mBACvB;CAGF,IAAI,UAAU,WAAW,SACvB,OAAO,UAAU;MACZ,IAAI,KAAK,SAAS,gBAAgB,GACvC,OAAO,KAAK,QAAQ,kBAAkB,iDAAiD;MAClF;EACL,QAAQ,IACN,GAAG,OAAO,aAAa,mBAAmB,EAAE,0FAE9C;EAEA;CACF;CAEA,MAAM,aAAa,YAAY,IAAI;CACnC,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG,EAAE,8CAA8C;AACjF;;;;;;;AAQA,eAAe,wBAAwB,UAA6B;CAClE,MAAM,WAAW,QAAQ,cAAc;CAEvC,IAAI,MAAM,gBAAgB,QAAQ,GAChC,QAAQ,IAAI,GAAG,OAAO,aAAa,SAAS,EAAE,iCAAiC;MAC1E;EACL,MAAM,qBAAqB,QAAQ,KAAK,CAAC;EACzC,MAAM,aAAa,UAAU,WAAW;EACxC,MAAM,gBAAgB,QAAQ,mBAAmB;EACjD,IAAI,CAAE,MAAM,gBAAgB,aAAa,GACvC,MAAM,aAAa,eAAe,gBAAgB;EAEpD,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG,EAAE,0BAA0B;EAE3D,MAAM,YAAY,MAAM,6BAA6B;EAErD,IAAI,UAAU,YAAY,aACxB,QAAQ,IACN,GAAG,OAAO,MAAM,GAAG,EAAE,sBAAsB,OAAO,aAAa,WAAS,EAAE,YACrE,OAAO,aAAa,cAAY,EAAE,MAAM,OAAO,aAAa,OAAO,UAAU,cAAc,EAAE,sFAEpG;EAMF,IAAI,UAAU,YAAY,cAAc,UAAU,YAAY,UAAU;GACtE,MAAM,OACJ,UAAU,YAAY,WAAW,OAAO,UAAU,GAAG,IAAI,OAAO,aAAa,GAAG;GAElF,QAAQ,IACN,GAAG,KAAK,0CAA0C,UAAU,OAAO,+BACpC,OAAO,aAAa,oBAAkB,EAAE;YAExD,OAAO,aAAa,WAAS,EAAE,gLAGhD;GAUA,QAAQ,WAAW;EACrB,OAAO;GACL,MAAM,aAAa,QAAQ,oBAAoB,GAAG,eAAe;GACjE,MAAM,gBAAgB,QAAQ,oBAAoB;GAClD,IAAI,CAAE,MAAM,gBAAgB,aAAa,GACvC,MAAM,aAAa,eAAe,gBAAgB;GASpD,MAAM,cAAc,uBAAuB;IACzC,kBAAkB,MAAM,gBACtB,QAAQ,+CAA+C,CACzD;IACA,cAAc,MAAM,gBAAgB,QAAQ,uBAAuB,CAAC;GACtE,CAAC;GAED,IAAI,YAAY,iBAAiB;IAC/B,MAAM,qBAAqB,QAAQ,yBAAyB,CAAC;IAC7D,MAAM,aACJ,QAAQ,+CAA+C,GACvD,wBACF;GACF;GAEA,IAAI,YAAY,aAAa;IAC3B,MAAM,qBAAqB,QAAQ,aAAa,CAAC;IACjD,MAAM,aAAa,QAAQ,uBAAuB,GAAG,oBAAoB;GAC3E;GAEA,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG,EAAE,gCAAgC;GAEjE,KAAK,MAAM,WAAW,YAAY,UAChC,QAAQ,IAAI,OAAO;EAEvB;CACF;CAEA,MAAM,qBAAqB;AAC7B;AAEA,MAAa,aAAgC;CAC3C,aACE;CACF,cAAc;EACZ,mBAAmB;EACnB,gBAAgB;EAChB,sBAAsB;EACtB,8BAA8B;EAC9B,OAAO;EACP,aAAa;CACf;CACA,iBAAiB;EACf,gBAAgB;EAChB,oBAAoB;EAGpB,MAAM;EACN,wBAAwB;CAC1B;CACA,aAAa;AACf"}
1
+ {"version":3,"file":"web.feature.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/generations/features/web.feature.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n putFileAsync,\n} from \"../generation-fs\";\nimport type { CommandActionData } from \"../../commands/types\";\nimport { rootPath, srcPath } from \"../../utils\";\nimport { insertConnectorEntry } from \"./shared/insert-connector-entry\";\nimport { relocateConflictingHomeRoute } from \"./shared/relocate-conflicting-home-route\";\nimport { resolveContactScaffold } from \"./shared/resolve-contact-scaffold\";\nimport {\n webContactControllerStub,\n webContactRoutesStub,\n webHomePageStub,\n webHomeSetupStub,\n webRootStub,\n webRootSetupStub,\n} from \"../stubs\";\nimport { type FeatureDefinition, INSTALLED_WARLOCK_VERSION } from \"./types\";\n\n/** The one vite range shared by every feature (web's peer range is `^8.0.0`). */\nexport const VITE_RANGE = \"^8.3.3\";\n\n/**\n * Register the WebConnector in `warlock.config.ts`, and ONLY there.\n *\n * It belongs to the config array or to app code, never both. Both halves are\n * registered before app code loads — the CLI preloader in dev, the generated\n * entry in production — so also calling `connectorsManager.register(...)` in\n * `src/app/main.ts` boots the connector twice and installs every page route\n * twice. That surfaces at PRODUCTION boot as `Route name \"...\" is already\n * taken`, because pages and API routes share one route-name namespace.\n *\n * The config array is the half to prefer: `warlock build` reads the same array\n * to drain each connector's build contribution, so \"built for\" and \"boots with\"\n * cannot drift.\n *\n * String surgery rather than a TypeScript parse: `warlock.config.ts` is an\n * app-owned file that may carry any formatting, and a parse-and-print would\n * reformat the parts we did not come to change.\n */\nasync function registerWebConnector(): Promise<void> {\n const configPath = rootPath(\"warlock.config.ts\");\n\n if (!(await fileExistsAsync(configPath))) {\n console.log(\n `${colors.yellowBright(\"warlock.config.ts\")} not found — add this yourself:\\n` +\n ` import { webConnector } from \"@warlock.js/web/connector\";\\n` +\n ` export default defineConfig({ connectors: [webConnector()] });`,\n );\n\n return;\n }\n\n const current = await getFileAsync(configPath);\n\n if (current.includes(\"webConnector\")) {\n console.log(`${colors.yellowBright(\"webConnector\")} already registered, skipping...`);\n\n return;\n }\n\n const importLine = 'import { webConnector } from \"@warlock.js/web/connector\";';\n let next = current.includes(importLine) ? current : `${importLine}\\n${current}`;\n\n // An existing `connectors: [` gains one entry; otherwise the key is added to\n // the object `defineConfig` receives.\n const insertion = insertConnectorEntry(next, \"webConnector()\");\n\n if (insertion.status === \"already-present\") {\n return;\n }\n\n if (insertion.status === \"added\") {\n next = insertion.next;\n } else if (next.includes(\"defineConfig({\")) {\n next = next.replace(\"defineConfig({\", \"defineConfig({\\n connectors: [webConnector()],\");\n } else {\n console.log(\n `${colors.yellowBright(\"warlock.config.ts\")} has no recognisable defineConfig({...}) — ` +\n \"add `connectors: [webConnector()]` yourself.\",\n );\n\n return;\n }\n\n await putFileAsync(configPath, next);\n console.log(`${colors.green(\"✓\")} Registered webConnector in warlock.config.ts`);\n}\n\n/**\n * Scaffold the smallest page layer that renders, and register the connector.\n *\n * `src/web/root.tsx` is the sentinel for \"already scaffolded\" — the framework\n * ships a default root, so its presence means a human has been here.\n */\nasync function completeWebInstallation(_options: CommandActionData) {\n const rootFile = srcPath(\"web/root.tsx\");\n\n if (await fileExistsAsync(rootFile)) {\n console.log(`${colors.yellowBright(\"src/web\")} already scaffolded, skipping...`);\n } else {\n await ensureDirectoryAsync(srcPath(\"web\"));\n await putFileAsync(rootFile, webRootStub);\n const rootSetupFile = srcPath(\"web/root.setup.ts\");\n if (!(await fileExistsAsync(rootSetupFile))) {\n await putFileAsync(rootSetupFile, webRootSetupStub);\n }\n console.log(`${colors.green(\"✓\")} Created src/web/root.tsx`);\n\n const collision = await relocateConflictingHomeRoute();\n\n if (collision.outcome === \"relocated\") {\n console.log(\n `${colors.green(\"✓\")} Moved the existing ${colors.yellowBright('GET \"/\"')} route to ` +\n `${colors.yellowBright('\"/welcome\"')} in ${colors.yellowBright(`src/${collision.relativePath}`)} — ` +\n \"the new page owns `/` now, and the JSON welcome route still answers at /welcome.\",\n );\n }\n\n // The page is written ONLY when `/` is provably free. Writing it while\n // another handler holds `/` produces a homepage that 500s on first request,\n // which is precisely the outcome a scaffolder must never hand back.\n if (collision.outcome === \"conflict\" || collision.outcome === \"failed\") {\n const verb =\n collision.outcome === \"failed\" ? colors.redBright(\"✗\") : colors.yellowBright(\"!\");\n\n console.log(\n `${verb} Did not create src/web/index.page.tsx: ${collision.reason}.\\n` +\n ` The page setup declares ${colors.yellowBright('route.path = \"/\"')}, and two handlers on one ` +\n \"path is a 500 at request time, not a startup error.\\n\" +\n ` Free up ${colors.yellowBright('GET \"/\"')} under src/app — move it to a path of its own, ` +\n \"or remove it — then create src/web/index.page.tsx yourself. Giving the setup file a `config.route` other \" +\n \"than `/` works too.\",\n );\n\n // Non-zero on BOTH branches. The page layer this command exists to\n // scaffold was not scaffolded, and a 0 here is the exact \"looked like it\n // worked\" signal that put `/` in this state to begin with — a conflict we\n // declined to guess at is still an incomplete install, not a success.\n //\n // `exitCode` rather than `exit(1)`: the connector below still has to be\n // registered, and any other feature in the same `warlock add` invocation\n // still has to install, or the project is left half-wired on top of this.\n process.exitCode = 1;\n } else {\n await putFileAsync(srcPath(\"web/index.page.tsx\"), webHomePageStub);\n const homeSetupFile = srcPath(\"web/index.setup.ts\");\n if (!(await fileExistsAsync(homeSetupFile))) {\n await putFileAsync(homeSetupFile, webHomeSetupStub);\n }\n\n // Unlike root.tsx above, the contact controller and its routes file are\n // ordinary application files a project can already have — independently\n // of ever having run `warlock add web`. Each is guarded on its OWN\n // existence, not on the (already-consumed) root.tsx sentinel, so an\n // existing `contact` module is skipped rather than clobbered. See\n // resolveContactScaffold's doc comment for why.\n const contactPlan = resolveContactScaffold({\n controllerExists: await fileExistsAsync(\n srcPath(\"app/contact/controllers/contact.controller.ts\"),\n ),\n routesExists: await fileExistsAsync(srcPath(\"app/contact/routes.ts\")),\n });\n\n if (contactPlan.writeController) {\n await ensureDirectoryAsync(srcPath(\"app/contact/controllers\"));\n await putFileAsync(\n srcPath(\"app/contact/controllers/contact.controller.ts\"),\n webContactControllerStub,\n );\n }\n\n if (contactPlan.writeRoutes) {\n await ensureDirectoryAsync(srcPath(\"app/contact\"));\n await putFileAsync(srcPath(\"app/contact/routes.ts\"), webContactRoutesStub);\n }\n\n console.log(`${colors.green(\"✓\")} Created src/web/index.page.tsx`);\n\n for (const message of contactPlan.messages) {\n console.log(message);\n }\n }\n }\n\n await registerWebConnector();\n}\n\nexport const webFeature: FeatureDefinition = {\n description:\n \"Installs @warlock.js/web — SSR React pages served by the Warlock HTTP server. Scaffolds src/web (root.tsx + a home page) and registers the WebConnector in warlock.config.ts. Pages are opt-in: a Warlock app is an API until you add this.\",\n dependencies: {\n \"@warlock.js/web\": INSTALLED_WARLOCK_VERSION,\n \"@mongez/http\": \"^3.5.0\",\n \"@mongez/react-form\": \"^4.0.0\",\n \"@mongez/react-localization\": \"^3.4.7\",\n react: \"^19.2.3\",\n \"react-dom\": \"^19.2.3\",\n },\n devDependencies: {\n \"@types/react\": \"^19.2.7\",\n \"@types/react-dom\": \"^19.2.3\",\n // Loaded through `await import()` by the dev server only, so both are\n // optional peers of `web` rather than hard dependencies.\n vite: VITE_RANGE,\n \"@vitejs/plugin-react\": \"^6.1.2\",\n },\n onExecuting: completeWebInstallation,\n};\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAa,aAAa;;;;;;;;;;;;;;;;;;;AAoB1B,eAAe,uBAAsC;CACnD,MAAM,aAAa,SAAS,mBAAmB;CAE/C,IAAI,CAAE,MAAM,gBAAgB,UAAU,GAAI;EACxC,QAAQ,IACN,GAAG,OAAO,aAAa,mBAAmB,EAAE,+JAG9C;EAEA;CACF;CAEA,MAAM,UAAU,MAAM,aAAa,UAAU;CAE7C,IAAI,QAAQ,SAAS,cAAc,GAAG;EACpC,QAAQ,IAAI,GAAG,OAAO,aAAa,cAAc,EAAE,iCAAiC;EAEpF;CACF;CAEA,MAAM,aAAa;CACnB,IAAI,OAAO,QAAQ,SAAS,UAAU,IAAI,UAAU,GAAG,WAAW,IAAI;CAItE,MAAM,YAAY,qBAAqB,MAAM,gBAAgB;CAE7D,IAAI,UAAU,WAAW,mBACvB;CAGF,IAAI,UAAU,WAAW,SACvB,OAAO,UAAU;MACZ,IAAI,KAAK,SAAS,gBAAgB,GACvC,OAAO,KAAK,QAAQ,kBAAkB,iDAAiD;MAClF;EACL,QAAQ,IACN,GAAG,OAAO,aAAa,mBAAmB,EAAE,0FAE9C;EAEA;CACF;CAEA,MAAM,aAAa,YAAY,IAAI;CACnC,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG,EAAE,8CAA8C;AACjF;;;;;;;AAQA,eAAe,wBAAwB,UAA6B;CAClE,MAAM,WAAW,QAAQ,cAAc;CAEvC,IAAI,MAAM,gBAAgB,QAAQ,GAChC,QAAQ,IAAI,GAAG,OAAO,aAAa,SAAS,EAAE,iCAAiC;MAC1E;EACL,MAAM,qBAAqB,QAAQ,KAAK,CAAC;EACzC,MAAM,aAAa,UAAU,WAAW;EACxC,MAAM,gBAAgB,QAAQ,mBAAmB;EACjD,IAAI,CAAE,MAAM,gBAAgB,aAAa,GACvC,MAAM,aAAa,eAAe,gBAAgB;EAEpD,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG,EAAE,0BAA0B;EAE3D,MAAM,YAAY,MAAM,6BAA6B;EAErD,IAAI,UAAU,YAAY,aACxB,QAAQ,IACN,GAAG,OAAO,MAAM,GAAG,EAAE,sBAAsB,OAAO,aAAa,WAAS,EAAE,YACrE,OAAO,aAAa,cAAY,EAAE,MAAM,OAAO,aAAa,OAAO,UAAU,cAAc,EAAE,sFAEpG;EAMF,IAAI,UAAU,YAAY,cAAc,UAAU,YAAY,UAAU;GACtE,MAAM,OACJ,UAAU,YAAY,WAAW,OAAO,UAAU,GAAG,IAAI,OAAO,aAAa,GAAG;GAElF,QAAQ,IACN,GAAG,KAAK,0CAA0C,UAAU,OAAO,+BACpC,OAAO,aAAa,oBAAkB,EAAE;YAExD,OAAO,aAAa,WAAS,EAAE,gLAGhD;GAUA,QAAQ,WAAW;EACrB,OAAO;GACL,MAAM,aAAa,QAAQ,oBAAoB,GAAG,eAAe;GACjE,MAAM,gBAAgB,QAAQ,oBAAoB;GAClD,IAAI,CAAE,MAAM,gBAAgB,aAAa,GACvC,MAAM,aAAa,eAAe,gBAAgB;GASpD,MAAM,cAAc,uBAAuB;IACzC,kBAAkB,MAAM,gBACtB,QAAQ,+CAA+C,CACzD;IACA,cAAc,MAAM,gBAAgB,QAAQ,uBAAuB,CAAC;GACtE,CAAC;GAED,IAAI,YAAY,iBAAiB;IAC/B,MAAM,qBAAqB,QAAQ,yBAAyB,CAAC;IAC7D,MAAM,aACJ,QAAQ,+CAA+C,GACvD,wBACF;GACF;GAEA,IAAI,YAAY,aAAa;IAC3B,MAAM,qBAAqB,QAAQ,aAAa,CAAC;IACjD,MAAM,aAAa,QAAQ,uBAAuB,GAAG,oBAAoB;GAC3E;GAEA,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG,EAAE,gCAAgC;GAEjE,KAAK,MAAM,WAAW,YAAY,UAChC,QAAQ,IAAI,OAAO;EAEvB;CACF;CAEA,MAAM,qBAAqB;AAC7B;AAEA,MAAa,aAAgC;CAC3C,aACE;CACF,cAAc;EACZ,mBAAmB;EACnB,gBAAgB;EAChB,sBAAsB;EACtB,8BAA8B;EAC9B,OAAO;EACP,aAAa;CACf;CACA,iBAAiB;EACf,gBAAgB;EAChB,oBAAoB;EAGpB,MAAM;EACN,wBAAwB;CAC1B;CACA,aAAa;AACf"}
@@ -1,3 +1,5 @@
1
+ import baseConfig from "@mongez/config";
2
+
1
3
  //#region ../../packages/core/src/generations/stubs.ts
2
4
  const accessConfigStub = `import { type AccessConfigurations } from "@warlock.js/access";
3
5
  import { DatabaseAccessResolver } from "app/access/services/access-resolver";
@@ -655,11 +657,13 @@ router.group({ middleware: [authMiddleware([])] }, () => {
655
657
  notifications.nest("/:id/read").patch(markNotificationReadController);
656
658
  });
657
659
  `;
658
- /** `src/app/notifications/utils/locales.json` — the module's translations. */
659
- const notificationLocalesStub = `{
660
- "notFound": { "en": "Notification not found" }
660
+ /** Build module locale JSON, with English as the explicit translation fallback. */
661
+ function createNotificationLocalesStub() {
662
+ const configured = baseConfig.get("app.localeCodes");
663
+ const codes = Array.isArray(configured) && configured.length > 0 ? configured.filter((code) => typeof code === "string") : ["en"];
664
+ return JSON.stringify({ notFound: Object.fromEntries(codes.map((code) => [code, "Notification not found"])) }, null, 2) + "\n";
661
665
  }
662
- `;
666
+ const notificationLocalesStub = createNotificationLocalesStub();
663
667
  /** Shared fixtures for the generated signed-in notification controller specs. */
664
668
  const notificationTestFixtureStub = `import type { Auth } from "@warlock.js/auth";
665
669
  import type { ChildModel } from "@warlock.js/cascade";
@@ -1172,5 +1176,5 @@ function ContactMessage() {
1172
1176
  `;
1173
1177
 
1174
1178
  //#endregion
1175
- export { accessConfigStub, accessResolverStub, accessRoleMigrationStub, accessRoleModelIndexStub, accessRoleModelStub, accessUserRoleMigrationStub, accessUserRoleModelIndexStub, accessUserRoleModelStub, aiConfigStub, communicatorsConfigStub, listNotificationsControllerStub, listNotificationsSchemaStub, markAllNotificationsReadControllerStub, markNotificationReadControllerStub, markNotificationReadServiceStub, notificationControllerSpecStub, notificationLocalesStub, notificationMigrationStub, notificationModelStub, notificationResourceStub, notificationRoutesStub, notificationTestFixtureStub, notificationsConfigStub, notificationsRequestTypeStub, socketConfigStub, unreadNotificationsCountControllerStub, webContactControllerStub, webContactRoutesStub, webHomePageStub, webHomeSetupStub, webRootSetupStub, webRootStub };
1179
+ export { accessConfigStub, accessResolverStub, accessRoleMigrationStub, accessRoleModelIndexStub, accessRoleModelStub, accessUserRoleMigrationStub, accessUserRoleModelIndexStub, accessUserRoleModelStub, aiConfigStub, communicatorsConfigStub, createNotificationLocalesStub, listNotificationsControllerStub, listNotificationsSchemaStub, markAllNotificationsReadControllerStub, markNotificationReadControllerStub, markNotificationReadServiceStub, notificationControllerSpecStub, notificationMigrationStub, notificationModelStub, notificationResourceStub, notificationRoutesStub, notificationTestFixtureStub, notificationsConfigStub, notificationsRequestTypeStub, socketConfigStub, unreadNotificationsCountControllerStub, webContactControllerStub, webContactRoutesStub, webHomePageStub, webHomeSetupStub, webRootSetupStub, webRootStub };
1176
1180
  //# sourceMappingURL=stubs.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"stubs.mjs","names":[],"sources":["../../../../../../../../packages/core/src/generations/stubs.ts"],"sourcesContent":["export const accessConfigStub = `import { type AccessConfigurations } from \"@warlock.js/access\";\nimport { DatabaseAccessResolver } from \"app/access/services/access-resolver\";\n\n/**\n * Authorization configuration — read by @warlock.js/access on boot.\n *\n * The resolver is the one required piece: it tells the engine how to read a\n * user's roles + permissions. The ejected DatabaseAccessResolver reads roles\n * from the user_roles table and maps them through the roles catalog table (so\n * roles + their permissions are managed at runtime, in the DB).\n *\n * For a fixed, code-defined catalog with no tables, swap in DefaultAccessResolver:\n * import { DefaultAccessResolver } from \"@warlock.js/access\";\n * resolver: new DefaultAccessResolver({ admin: [\"*\"], editor: [\"orders.*\"] }),\n *\n * Multi-tenant? Add a \\`resolveTenant()\\` to the resolver to read the active\n * tenant from the request; checks then scope to it automatically.\n */\nconst access: AccessConfigurations = {\n resolver: new DatabaseAccessResolver(),\n\n // Cache resolved permission sets (default \"10m\").\n // cache: { ttl: \"10m\" },\n};\n\nexport default access;\n`;\n\nexport const aiConfigStub = `import type { AIConfig } from \"@warlock.js/ai\";\n\n// >>> warlock:ai-packages (auto-managed) >>>\n// Satellite packages augment the \"ai\" object on import — e.g. ai.workspace,\n// ai.tools / ai.mcp, and panoptic's ai.config({ panoptic }) wiring. The command\n// \"warlock add ai-workspace | ai-tools | ai-panoptic\" adds the matching\n// side-effect import below; keep them so the augmentation + runtime registration\n// load before the ai connector applies this config.\n// <<< warlock:ai-packages <<<\n\n/**\n * AI configuration — applied on boot by the ai connector, which calls\n * ai.config(...) with the object below. Cross-cutting defaults live here\n * (shared cache / snapshot stores, observability); per-call options always win.\n *\n * Wire a default model from a provider you installed, e.g.:\n * import { OpenAISDK } from \"@warlock.js/ai-openai\";\n * const openai = OpenAISDK({ apiKey: env(\"OPENAI_API_KEY\") });\n * // then pass openai.model({ name: \"gpt-4o-mini\" }) into your agents.\n */\nconst ai: Partial<AIConfig> = {\n // Default cache driver for cache-backed AI features (semantic cache, rag / memory vector stores).\n // defaultStore: cache.driver(\"redis\", { client }),\n\n // Observability — requires \"warlock add ai-panoptic\". Exporters + the local dashboard.\n // panoptic: { exporters: [], dashboard: false, observeAll: false },\n};\n\nexport default ai;\n`;\n\nexport const accessRoleModelStub = `import { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for the roles catalog — mirrors the migration columns\n * (snake_case). Each row is a role name plus the permission strings it grants;\n * wildcards work (\"orders.*\", \"*\"). The DatabaseAccessResolver maps a user's\n * assigned role names through this table to their effective permissions.\n */\nexport const roleSchema = v.object({\n name: v.string(),\n permissions: v.array(v.string()).default([]),\n});\n\nexport type RoleSchema = Infer<typeof roleSchema>;\n\n/**\n * The roles catalog — role name → the permissions it grants. Managed at runtime\n * (admins add roles + edit their permissions), unlike a fixed code map. Read by\n * DatabaseAccessResolver.resolvePermissions to expand a user's roles to permissions.\n */\n@RegisterModel()\nexport class Role extends Model<RoleSchema> {\n public static table = \"roles\";\n\n public static schema = roleSchema;\n\n /** The permission strings this role grants. */\n public get permissions(): string[] {\n return this.get<string[]>(\"permissions\", []);\n }\n}\n`;\n\nexport const accessRoleModelIndexStub = `export * from \"./role.model\";\n`;\n\nexport const accessRoleMigrationStub = `import { arrayText, Migration, text } from \"@warlock.js/cascade\";\nimport { Role } from \"../role.model\";\n\n/**\n * Roles catalog table. \\`name\\` is unique (one row per role); \\`permissions\\` is a\n * text array of the permission strings the role grants.\n */\nexport default Migration.create(Role, {\n name: text().notNullable().unique(),\n permissions: arrayText().nullable(),\n});\n`;\n\nexport const accessUserRoleModelStub = `import { access } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for a role assignment — mirrors the migration columns\n * (snake_case). \\`tenant\\` is nullable: a null tenant is a GLOBAL assignment.\n */\nexport const userRoleSchema = v.object({\n user_id: v.string(),\n user_type: v.string(),\n role: v.string(),\n tenant: v.string().optional(),\n});\n\nexport type UserRoleSchema = Infer<typeof userRoleSchema>;\n\n/**\n * The role-assignment table — which roles a user holds, optionally per tenant.\n * Read by DatabaseAccessResolver.resolveRoles; mutated via the statics below.\n * \\`assign\\` / \\`revoke\\` flush the cached permission set automatically, so callers\n * never need to call \\`access.flush(user, tenant)\\` themselves.\n */\n@RegisterModel()\nexport class UserRole extends Model<UserRoleSchema> {\n public static table = \"user_roles\";\n\n public static schema = userRoleSchema;\n\n /**\n * Role names assigned to the user in the given tenant.\n *\n * An unresolved tenant (\\`undefined\\`) scopes to GLOBAL roles only — the rows\n * stored with no tenant (\\`null\\`) — never the union across every tenant. The\n * union would be a privilege-escalation: a user who is \\`owner\\` in one tenant\n * must not be treated as \\`owner\\` everywhere just because a check didn't carry\n * a tenant. This mirrors how \\`assign(user, role)\\` stores a global row.\n */\n public static async rolesFor(user: Auth, tenant?: string): Promise<string[]> {\n const rows = await this.query()\n .where({\n user_id: user.id,\n user_type: user.userType,\n tenant: tenant ?? null,\n })\n .get();\n\n // De-dupe so a duplicate row (a concurrent assign that slipped past the\n // existence check) can't distort the resolved set.\n return [...new Set(rows.map((row) => row.get(\"role\") as string))];\n }\n\n /**\n * Assign a role to the user. No-op if the assignment already exists.\n * Flushes the user's cached permission set automatically.\n */\n public static async assign(user: Auth, role: string, tenant?: string): Promise<void> {\n const existing = await this.first({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n if (existing) return;\n\n await this.create({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant,\n });\n\n await access.flush(user, tenant);\n }\n\n /**\n * Remove a role assignment from the user.\n * Flushes the user's cached permission set automatically.\n */\n public static async revoke(user: Auth, role: string, tenant?: string): Promise<void> {\n await this.delete({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n await access.flush(user, tenant);\n }\n}\n`;\n\nexport const accessUserRoleModelIndexStub = `export * from \"./user-role.model\";\n`;\n\nexport const accessUserRoleMigrationStub = `import { Migration, text, uuid } from \"@warlock.js/cascade\";\nimport { UserRole } from \"../user-role.model\";\n\n/**\n * Role-assignment table. \\`user_id\\` is a UUID — override this migration if your\n * user ids are integers. The composite index powers the per-user (per-tenant)\n * lookup the resolver runs on every check.\n */\nexport default Migration.create(\n UserRole,\n {\n user_id: uuid().notNullable().index(),\n user_type: text().notNullable(),\n role: text().notNullable().index(),\n tenant: text().nullable().index(),\n },\n {\n index: [{ columns: [\"user_id\", \"user_type\", \"tenant\"] }],\n },\n);\n`;\n\nexport const accessResolverStub = `import type { AccessResolver } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Role } from \"app/access/models/role\";\nimport { UserRole } from \"app/access/models/user-role\";\n\n/**\n * The app's access adapter — connects @warlock.js/access to the ejected role\n * tables. Roles come from the user_roles assignment table; permissions are\n * expanded by mapping those role names through the roles catalog table. Both\n * are managed at runtime (in the DB), so admins can add roles + edit their\n * permissions without a deploy.\n *\n * The engine owns the hard parts (wildcard matching, caching, fail-closed); this\n * resolver only fetches — keep it dumb, never cache inside it.\n */\nexport class DatabaseAccessResolver implements AccessResolver {\n /** The role names this user holds (powers \\`hasRole\\` / \\`hasAnyRole\\`). */\n public async resolveRoles(user: Auth, tenant?: string): Promise<string[]> {\n return UserRole.rolesFor(user, tenant);\n }\n\n /** The effective permission strings this user has (powers \\`can\\` / \\`authorize\\`). */\n public async resolvePermissions(user: Auth, tenant?: string): Promise<string[]> {\n const names = await this.resolveRoles(user, tenant);\n\n if (names.length === 0) return [];\n\n const roles = await Role.query().whereIn(\"name\", names).get();\n\n // Flatten + de-dupe so two roles granting the same permission yield one entry.\n return [...new Set(roles.flatMap((role) => role.permissions))];\n }\n\n /**\n * Optional. Resolve the ambient tenant when a check doesn't pass one\n * explicitly — derive it from the authenticated user (safer than reading\n * client request input, which a caller could spoof). Uncomment + adapt for a\n * multi-tenant app (single-tenant apps leave this off and return undefined).\n */\n // public resolveTenant(user: Auth): string | undefined {\n // return user.get(\"organization_id\");\n // }\n}\n`;\n\nexport const socketConfigStub = `import type { SocketOptions } from \"@warlock.js/core\";\n\n/**\n * Socket.IO configuration — read by the framework's socket connector\n * on boot. When the HTTP server is running the socket server attaches\n * to it; otherwise it listens on its own configured port.\n *\n * Remove this file to disable the socket server entirely.\n */\nexport default {\n options: {\n cors: {\n origin: \"*\",\n },\n },\n} as SocketOptions;\n`;\n\nexport const communicatorsConfigStub = `import { env } from \"@warlock.js/core\";\nimport type { BrokerConfigurations, RabbitMQClientOptions } from \"@warlock.js/herald\";\n\nconst heraldConfigurations: BrokerConfigurations<RabbitMQClientOptions> = {\n driver: \"rabbitmq\",\n name: \"default\",\n isDefault: true,\n\n // ============================================================================\n // Connection Settings\n // ============================================================================\n\n host: env(\"RABBITMQ_HOST\", \"localhost\"),\n port: env(\"RABBITMQ_PORT\", 5672),\n username: env(\"RABBITMQ_USERNAME\", \"guest\"),\n password: env(\"RABBITMQ_PASSWORD\", \"guest\"),\n vhost: env(\"RABBITMQ_VHOST\", \"/\"),\n\n // Or use connection URI (takes precedence over host/port)\n // uri: env(\"RABBITMQ_URL\"),\n\n // ============================================================================\n // Connection Options\n // ============================================================================\n\n /** Heartbeat interval in seconds */\n heartbeat: 60,\n\n /** Connection timeout in milliseconds */\n connectionTimeout: 10000,\n\n /** Enable automatic reconnection on disconnect */\n reconnect: true,\n\n /** Delay between reconnection attempts in milliseconds */\n reconnectDelay: 5_000,\n\n // ============================================================================\n // Consumer Options\n // ============================================================================\n\n /** Default prefetch count (number of unacknowledged messages per consumer) */\n prefetch: 10,\n\n // ============================================================================\n // Client Options (Native amqplib options)\n // ============================================================================\n // These options are passed directly to amqplib.connect()\n // for low-level configuration like frame size, TLS, socket options, etc.\n // ============================================================================\n clientOptions: {\n // Frame max size in bytes (0 = no limit)\n // frameMax: 0,\n\n // Channel max (0 = unlimited)\n // channelMax: 0,\n\n // Socket options\n socket: {\n // Enable TCP keep-alive\n keepAlive: true,\n\n // Disable Nagle's algorithm for lower latency\n noDelay: true,\n\n // Socket timeout (in addition to heartbeat)\n // timeout: 30000,\n },\n\n // TLS/SSL options (uncomment for secure connections)\n // socket: {\n // ca: fs.readFileSync('/path/to/ca.pem'),\n // cert: fs.readFileSync('/path/to/cert.pem'),\n // key: fs.readFileSync('/path/to/key.pem'),\n // rejectUnauthorized: true,\n // },\n },\n};\n\nexport default heraldConfigurations;\n`;\n\nexport const notificationsConfigStub = `import { type NotificationConfig, inApp, mailChannel } from \"@warlock.js/notifications\";\nimport { Notification } from \"app/notifications/models/notification/notification.model\";\n\n/**\n * Notifications configuration. Auto-loaded from src/config on boot — the\n * framework's notifications connector reads this default export and hands it to\n * setNotificationConfig, so this file stays declarative (no side-effect call).\n *\n * Each channel is payload-typed, so notify.mail(...) / notify.database(...)\n * and defineNotification are type-checked against the registry.\n *\n * Channels enabled here:\n * - mail wraps @warlock.js/core sendMail; route is notifiable.email.\n * The \"from\" address defaults to config/mail.ts; override per\n * channel with mailChannel({ from: \"no-reply@yourapp.com\" }).\n * - database in-app store backed by the Notification model. The \"inApp\"\n * facade exposes the recipient-scoped read API: listUnread,\n * countUnread, markAsRead, dismiss, ...\n *\n * Async delivery (.queue()) is OPTIONAL: run \"npx warlock add herald\",\n * import { heraldQueue } from \"@warlock.js/notifications\", and uncomment the\n * queue line below.\n */\nconst config: NotificationConfig = {\n channels: {\n mail: mailChannel(),\n database: inApp.configure({ model: Notification }),\n },\n\n // Async queue — requires @warlock.js/herald (npx warlock add herald):\n // queue: heraldQueue(),\n};\n\nexport default config;\n`;\n\n/** `src/app/notifications/models/notification/notification.model.ts`. */\nexport const notificationModelStub = `import { RegisterModel } from \"@warlock.js/cascade\";\nimport { DatabaseNotification, type NotificationColumnMap } from \"@warlock.js/notifications\";\nimport { v } from \"@warlock.js/seal\";\nimport { NotificationResource } from \"../../resources/notification.resource\";\n\n/**\n * Validation schema for the notifications table — mirrors the migration\n * columns (snake_case). Cascade validates + casts every write against it:\n * nullable columns use .nullish() (may be absent or null), and payload is\n * free-form JSON. Keep this in sync with the migration + columnMap when you\n * add or rename columns.\n *\n * user_id accepts a string or an integer so it matches whichever id type your\n * users use (and the idType you pass to notificationColumns in the migration).\n * Narrow it to that one type.\n */\nconst notificationSchema = v.object({\n user_id: v.union([v.string(), v.int()]),\n type: v.string(),\n title: v.string(),\n body: v.string().nullish(),\n payload: v.record(v.any()).nullish(),\n read_at: v.date().nullish(),\n idempotency_key: v.string().nullish(),\n});\n\n/**\n * In-app notification model.\n *\n * Extends the package's DatabaseNotification base, which provides the stable\n * accessors (recipientId, tenantId, isRead, readAt, markRead) — all derived\n * from the columnMap below. The read/write API lives on the inApp facade\n * (configured in config/notifications.ts); you rarely touch this class directly.\n */\n@RegisterModel()\nexport class Notification extends DatabaseNotification {\n public static table = \"notifications\";\n public static schema = notificationSchema;\n\n /** Every response that returns a notification is shaped by this resource. */\n public static resource = NotificationResource;\n\n /**\n * Maps the in-app store's roles to your columns. This default is\n * single-tenant + read_at-only. Add tenant: \"organization_id\" for\n * multi-tenant; use isRead: \"is_read\" (instead of, or alongside, readAt) to\n * track a boolean read flag. The migration, the accessors and the resource\n * all follow this map.\n */\n public static columnMap: NotificationColumnMap = { readAt: \"read_at\" };\n}\n`;\n\n/** The notifications migration, under `models/notification/migrations/`. */\nexport const notificationMigrationStub = `import { Migration } from \"@warlock.js/cascade\";\nimport { notificationColumns } from \"@warlock.js/notifications\";\nimport { Notification } from \"../notification.model\";\n\n/**\n * Notifications table.\n *\n * Columns come from notificationColumns(Notification) — the recipient / tenant\n * / read-state names follow the model's columnMap; type / title / body /\n * payload / idempotency_key are fixed. The recipient column is a UUID unless\n * you pass { idType: \"integer\" } (or \"bigint\" / \"string\") to match your users.\n * Spread it to add your own columns (and mirror them in the model schema):\n *\n * import { uuid } from \"@warlock.js/cascade\";\n *\n * export default Migration.create(Notification, {\n * ...notificationColumns(Notification, { idType: \"integer\" }),\n * // category_id: uuid().index().nullable(),\n * });\n */\nexport default Migration.create(Notification, notificationColumns(Notification));\n`;\n\n/** `src/app/notifications/resources/notification.resource.ts` — the output shape. */\nexport const notificationResourceStub = `import { defineResource } from \"@warlock.js/core\";\n\n/**\n * What every notification endpoint returns, whatever columns the model holds.\n * readAt reads the default read_at column; change it if you change the model's\n * columnMap.\n */\nexport const NotificationResource = defineResource({\n schema: {\n // Passed through as stored: a UUID string or an integer, per the migration.\n id: (id: string | number) => id,\n type: \"string\",\n title: \"string\",\n body: \"string?\",\n payload: \"object?\",\n readAt: [\"read_at\", \"date?\"],\n createdAt: \"date?\",\n },\n});\n`;\n\n/** `src/app/notifications/schema/list-notifications.schema.ts` — the validated list query. */\nexport const listNotificationsSchemaStub = `import { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Query for GET /notifications. Only these keys reach the store (others, such\n * as a cache-busting \\`_\\`, are dropped rather than rejected), and limit is\n * capped so one request cannot read every row. Query values arrive as strings,\n * so the numbers and the flag are coerced.\n */\nexport const listNotificationsSchema = v.object({\n page: v.int().coerce().min(1).optional(),\n limit: v.int().coerce().min(1).max(50).optional(),\n type: v.string().optional(),\n unread: v.boolean().coerce().optional(),\n}).stripUnknown();\n\nexport type ListNotificationsSchema = Infer<typeof listNotificationsSchema>;\n`;\n\n/** `src/app/notifications/types/notifications-request.type.ts` — the guarded request. */\nexport const notificationsRequestTypeStub = `import type { Request, RequestHandler, RequestLocals } from \"@warlock.js/core\";\nimport type { Id } from \"@warlock.js/notifications\";\n\n/**\n * A request that passed authMiddleware, so locals.user is always set. Only the\n * user's id is declared because that is all the inApp store needs. If your\n * app has its own guarded request type, use it instead.\n */\nexport type NotificationsRequest<Payload = unknown> = Request<Payload> & {\n locals: RequestLocals & { user: { id: Id } };\n};\n\nexport type NotificationsRequestHandler<Payload = unknown> = RequestHandler<\n NotificationsRequest<Payload>\n>;\n`;\n\n/** `src/app/notifications/services/mark-notification-read.service.ts`. */\nexport const markNotificationReadServiceStub = `import { ResourceNotFoundError, t } from \"@warlock.js/core\";\nimport { type Id, inApp } from \"@warlock.js/notifications\";\n\n/**\n * Mark one of the user's notifications read and return it. inApp is scoped to\n * the recipient, so another user's id changes nothing and answers 404 here.\n */\nexport async function markNotificationReadService(userId: Id, notificationId: Id) {\n await inApp.markAsRead(userId, notificationId);\n\n const notification = await inApp.find(userId, notificationId);\n\n if (!notification) {\n throw new ResourceNotFoundError(t(\"notifications.notFound\"));\n }\n\n return notification;\n}\n`;\n\n/** `src/app/notifications/controllers/list-notifications.controller.ts`. */\nexport const listNotificationsControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport {\n type ListNotificationsSchema,\n listNotificationsSchema,\n} from \"../schema/list-notifications.schema\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications — the user's notifications, most recent first. */\nexport const listNotificationsController: NotificationsRequestHandler<\n ListNotificationsSchema\n> = async ({ request, response }) => {\n const { data, pagination } = await inApp.list(request.locals.user.id, request.validated());\n\n return response.success({ notifications: data, pagination });\n};\n\nlistNotificationsController.description = \"List notifications\";\n\nlistNotificationsController.validation = {\n schema: listNotificationsSchema,\n validating: [\"query\"],\n};\n`;\n\n/** `src/app/notifications/controllers/unread-notifications-count.controller.ts`. */\nexport const unreadNotificationsCountControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications/unread-count — drives the bell badge. */\nexport const unreadNotificationsCountController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.countUnread(request.locals.user.id);\n\n return response.success({ count });\n};\n\nunreadNotificationsCountController.description = \"Unread notifications count\";\n`;\n\n/** `src/app/notifications/controllers/mark-notification-read.controller.ts`. */\nexport const markNotificationReadControllerStub = `import { markNotificationReadService } from \"../services/mark-notification-read.service\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/:id/read — mark one read and return it. */\nexport const markNotificationReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n // Route params are strings. A numeric id is an integer id (the default\n // MongoDB stack); anything else, such as a UUID, stays a string.\n const rawId = request.string(\"id\");\n const id = /^\\\\d+$/.test(rawId) ? Number(rawId) : rawId;\n\n const notification = await markNotificationReadService(request.locals.user.id, id);\n\n return response.success({ notification });\n};\n\nmarkNotificationReadController.description = \"Mark notification read\";\n`;\n\n/** `src/app/notifications/controllers/mark-all-notifications-read.controller.ts`. */\nexport const markAllNotificationsReadControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/read-all — mark every unread one read. */\nexport const markAllNotificationsReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.markAsRead(request.locals.user.id);\n\n return response.success({ count });\n};\n\nmarkAllNotificationsReadController.description = \"Mark all notifications read\";\n`;\n\n/** `src/app/notifications/routes.ts` — the four read endpoints behind `authMiddleware`. */\nexport const notificationRoutesStub = `import { authMiddleware } from \"@warlock.js/auth\";\nimport { router } from \"@warlock.js/core\";\nimport { listNotificationsController } from \"./controllers/list-notifications.controller\";\nimport { markAllNotificationsReadController } from \"./controllers/mark-all-notifications-read.controller\";\nimport { markNotificationReadController } from \"./controllers/mark-notification-read.controller\";\nimport { unreadNotificationsCountController } from \"./controllers/unread-notifications-count.controller\";\n\n/**\n * The signed-in user's own notifications.\n *\n * Notifications come from domain events, so there is no create. Dismissing is\n * left out on purpose; add it when the product needs it (inApp.dismiss).\n *\n * authMiddleware([]) admits any signed-in user. To limit who may read\n * notifications, add a permission gate to the group:\n *\n * import { gate } from \"@warlock.js/access\";\n *\n * router.group({ middleware: [authMiddleware([]), gate(\"notifications.read\")] }, ...);\n */\nrouter.group({ middleware: [authMiddleware([])] }, () => {\n const notifications = router.route(\"/notifications\");\n\n notifications.list(listNotificationsController);\n notifications.nest(\"/unread-count\").get(unreadNotificationsCountController);\n notifications.nest(\"/read-all\").patch(markAllNotificationsReadController);\n notifications.nest(\"/:id/read\").patch(markNotificationReadController);\n});\n`;\n\n/** `src/app/notifications/utils/locales.json` — the module's translations. */\nexport const notificationLocalesStub = `{\n \"notFound\": { \"en\": \"Notification not found\" }\n}\n`;\n\n/** Shared fixtures for the generated signed-in notification controller specs. */\nexport const notificationTestFixtureStub = `import type { Auth } from \"@warlock.js/auth\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport { config } from \"@warlock.js/core\";\nimport { actingAs, type AuthenticatedTestClient } from \"@warlock.js/core/tests\";\nimport { randomUUID } from \"node:crypto\";\nimport { Notification } from \"../models/notification/notification.model\";\n\n/** Isolated recipients and rows; adjust user fields if your auth model requires more. */\nexport async function createNotificationTestFixture() {\n const User = config.key<ChildModel<Auth>>(\"auth.userType.user\");\n if (!User) throw new Error(\"Notification specs need the configured auth.userType.user model.\");\n const users: Auth[] = [];\n const clients: AuthenticatedTestClient[] = [];\n const rows: Notification[] = [];\n\n async function cleanup() {\n const credentials = await Promise.allSettled(\n clients.splice(0).map((client) => client.dispose()),\n );\n const notifications = await Promise.allSettled(\n rows.splice(0).map((row) => row.destroy({ strategy: \"permanent\" })),\n );\n const recipients = await Promise.allSettled(\n users.splice(0).map((user) => user.destroy({ strategy: \"permanent\" })),\n );\n const errors = [...credentials, ...notifications, ...recipients]\n .filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n .map((result) => result.reason);\n if (errors.length) throw new AggregateError(errors, \"Notification fixture cleanup failed.\");\n }\n\n const createUser = async () => {\n const user = await User.create({\n name: \"Notification test user\",\n email: \"notifications-\" + randomUUID() + \"@example.test\",\n password: \"test-password\",\n });\n users.push(user);\n return user;\n };\n const signIn = async (user: Auth) => {\n const client = await actingAs(user);\n clients.push(client);\n return client;\n };\n const createNotification = async (recipientId: string | number, title: string, readAt?: Date) => {\n const row = await Notification.create({\n user_id: recipientId,\n type: \"test\",\n title,\n read_at: readAt,\n });\n rows.push(row);\n return row;\n };\n\n try {\n const user = await createUser();\n const otherUser = await createUser();\n const client = await signIn(user);\n const otherClient = await signIn(otherUser);\n const own = await createNotification(user.id, \"Own unread notification\");\n const alreadyRead = await createNotification(user.id, \"Own read notification\", new Date());\n const foreign = await createNotification(otherUser.id, \"Other user's notification\");\n await createNotification(otherUser.id, \"Other user's second notification\");\n return { user, otherUser, client, otherClient, own, alreadyRead, foreign, cleanup };\n } catch (error) {\n // Preserve the setup failure after attempting every owned resource's cleanup.\n await cleanup().catch(() => undefined);\n throw error;\n }\n}\n`;\n\n/** A spec for each generated controller, including authenticated recipient isolation. */\nexport function notificationControllerSpecStub(method: \"GET\" | \"PATCH\", path: string): string {\n const helper = method === \"GET\" ? \"testGet\" : \"testPatch\";\n let signedInCases: string;\n if (path === \"/notifications\") {\n signedInCases = ` it(\"lists only the signed-in recipient's rows, ignoring a forged recipient query\", async () => {\n const response = await fixture.client.get(\n \"/notifications?recipientId=\" + fixture.otherUser.id,\n );\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual(\n expect.arrayContaining([fixture.own.id, fixture.alreadyRead.id]),\n );\n expect(body.notifications).toHaveLength(2);\n });\n\n it(\"applies unread and paging query filters\", async () => {\n const response = await fixture.client.get(\"/notifications?unread=true&limit=1\");\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual([fixture.own.id]);\n });\n\n it(\"rejects a list limit above the schema's cap\", async () => {\n expect((await fixture.client.get(\"/notifications?limit=999\")).status).toBe(422);\n });`;\n } else if (path === \"/notifications/unread-count\") {\n signedInCases = ` it(\"counts only this recipient's unread notifications\", async () => {\n const own = await expectJson<{ count: number }>(\n await fixture.client.get(\"/notifications/unread-count\"),\n );\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(own.count).toBe(1);\n expect(other.count).toBe(2);\n });`;\n } else if (path === \"/notifications/read-all\") {\n signedInCases = ` it(\"marks only this recipient's unread rows and leaves another recipient unchanged\", async () => {\n const body = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(body.count).toBe(1);\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(other.count).toBe(2);\n const again = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(again.count).toBe(0);\n });`;\n } else {\n signedInCases = ` it(\"marks its own notification read and returns it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.own.id + \"/read\");\n const body = await expectJson<{\n notification: { id: string | number; readAt?: string | null };\n }>(response);\n expect(body.notification.id).toBe(fixture.own.id);\n expect(body.notification.readAt).toBeTruthy();\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n });\n\n it(\"answers 404 for another recipient's notification without changing it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.foreign.id + \"/read\");\n expect(response.status).toBe(404);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n });`;\n }\n const modelImport =\n method === \"PATCH\"\n ? 'import { Notification } from \"../models/notification/notification.model\";\\n'\n : \"\";\n return `import { expectJson, ${helper} } from \"@warlock.js/core/tests\";\nimport { afterEach, beforeEach, describe, expect, it } from \"vitest\";\n${modelImport}import { createNotificationTestFixture } from \"../tests/notifications.fixture\";\n\ndescribe(\"${method} ${path}\", () => {\n it(\"answers 401 without a signed-in user\", async () => {\n const response = await ${helper}(\"${path}\");\n expect(response.status).toBe(401);\n });\n\n describe(\"signed in\", () => {\n let fixture: Awaited<ReturnType<typeof createNotificationTestFixture>> | undefined;\n beforeEach(async () => {\n fixture = await createNotificationTestFixture();\n });\n afterEach(async () => {\n const current = fixture;\n fixture = undefined;\n await current?.cleanup();\n });\n\n${signedInCases.replaceAll(\"fixture.\", \"fixture!.\")}\n });\n});\n`;\n}\n\n/** `src/web/root.setup.ts` — document policy. */\nexport const webRootSetupStub = `import type { RootConfig } from \"@warlock.js/web\";\n\nexport const config: RootConfig = { strictMode: true };\n`;\n\n/**\n * `src/web/root.tsx` — the application root for the SSR page layer.\n *\n * Deliberately minimal. The framework ships a default root, so this exists to\n * give you a place to start rather than because anything requires it. The\n * document component stays here; request policy and an app-level loader\n * belong in `root.setup.ts`. Named ErrorBoundary components stay in the UI.\n */\nexport const webRootStub = `import type { AppProps } from \"@warlock.js/web\";\nimport { Head, Scripts } from \"@warlock.js/web\";\n\n/**\n * The application root.\n *\n * NOT async, and it receives no request/response: it renders on the server and\n * again in the browser during hydration, where neither exists.\n */\nexport default function App({ children }: AppProps) {\n return (\n <html lang=\"en\">\n <head>\n {/*\n <Head /> also renders the viewport tag (width=device-width,\n initial-scale=1). Change it with \\`metadata.viewport\\`,\n or set it to false to leave it out; do not add a second one here.\n */}\n {/*\n Placement only. The framework injects the page's \\`metadata\\`, the\n stylesheet and preload tags for this route, and the canonical links\n into <head> by default — <Head /> just says WHERE they land.\n\n Do not add a <title> here: the page's \\`metadata\\` owns it, and a root\n that emits one too produces two.\n */}\n <Head />\n <link rel=\"icon\" href=\"data:,\" />\n </head>\n <body>\n {/*\n REQUIRED — this is the hydration mount point, not a styling wrapper.\n\n The browser runtime looks up \\`#vessel\\` and hydrates that element only.\n Remove this div, or rename the id, and the page still renders from the\n server but never becomes interactive: the runtime throws in the console\n and nothing on screen changes.\n\n Wrap it in your own markup freely, and put anything that must live\n outside the hydrated tree (a static footer, a portal target) outside\n it — just keep an element with \\`id=\"vessel\"\\` around {children}.\n */}\n <div id=\"vessel\">{children}</div>\n {/*\n The hydration payload and module tags. Written explicitly because\n placement occasionally matters — a CSP nonce, or ordering against\n your own scripts.\n */}\n <Scripts />\n </body>\n </html>\n );\n}\n`;\n\n/**\n * `src/app/contact/controllers/contact.controller.ts` — a real API endpoint\n * for the Web starter's contact form. It intentionally has no persistence\n * dependency: replace the acknowledgement with a mail/job/database action.\n */\nexport const webContactControllerStub = `import { type Request, type RequestHandler } from \"@warlock.js/core\";\nimport { v, type Infer } from \"@warlock.js/seal\";\n\nexport const contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nexport type ContactSchema = Infer.Output<typeof contactSchema>;\n\n/** POST /api/contact — validates the starter contact form. */\nexport const contactController: RequestHandler<Request<ContactSchema>> = async ({\n request,\n response,\n}) => {\n const contact = request.validated();\n\n // Replace this with delivery/persistence for your app. Keeping the accepted\n // payload visible makes the endpoint useful while remaining side-effect free.\n return response.success({\n message: \"Thanks, \" + contact.name + \". Your message has been received.\",\n });\n};\n\ncontactController.validation = { schema: contactSchema };\n`;\n\n/** `src/app/contact/routes.ts` — discovered by the standard app route loader. */\nexport const webContactRoutesStub = `import { router } from \"@warlock.js/core\";\nimport { contactController } from \"./controllers/contact.controller\";\n\nrouter.post(\"/api/contact\", contactController, { public: true });\n`;\n\n/** `src/web/index.setup.ts` — page policy and universal registration. */\nexport const webHomeSetupStub = `import { extend } from \"@mongez/localization\";\nimport type { PageConfig } from \"@warlock.js/web\";\n\nexport const config: PageConfig = {\n route: { path: \"/\", name: \"index\" },\n metadata: { title: \"Home\" },\n};\n\nexport function register() {\n extend(\"en\", {\n starter: {\n title: \"Your Warlock app is running.\",\n introduction: \"This page is rendered on the server and hydrated in the browser.\",\n language: \"العربية\",\n contact: \"Send a message\",\n name: \"Name\",\n email: \"Email\",\n message: \"Message\",\n submit: \"Send message\",\n sent: \"Thanks — your message has been received.\",\n },\n });\n extend(\"ar\", {\n starter: {\n title: \"تطبيق Warlock يعمل الآن.\",\n introduction: \"تُعرض هذه الصفحة على الخادم ثم تُفعَّل في المتصفح.\",\n language: \"English\",\n contact: \"أرسل رسالة\",\n name: \"الاسم\",\n email: \"البريد الإلكتروني\",\n message: \"الرسالة\",\n submit: \"إرسال الرسالة\",\n sent: \"شكرًا — تم استلام رسالتك.\",\n },\n });\n}\n`;\n\n/**\n * `src/web/index.page.tsx` — one page, so \\`warlock dev\\` has something to serve\n * the moment this finishes.\n */\nexport const webHomePageStub = `import { http } from \"@mongez/http\";\nimport { setCurrentLocaleCode } from \"@mongez/localization\";\nimport { Form, useFormControl, type FormControlProps } from \"@mongez/react-form\";\nimport { transX } from \"@mongez/react-localization\";\nimport { v } from \"@warlock.js/seal\";\nimport { Link, type PageProps } from \"@warlock.js/web\";\nimport { useState } from \"react\";\n\nconst contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nfunction TextInput({ label, ...controlProps }: FormControlProps & { label: string }) {\n const { error, getErrorProps, getInputProps } = useFormControl(controlProps);\n\n return (\n <div className=\"wk-field\">\n <label htmlFor={controlProps.name}>{label}</label>\n <input {...getInputProps()} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n\n/** Fetch data in index.setup.ts; use a type-only loader import for PageProps. */\nexport default function HomePage(_props: PageProps) {\n // Live state. If the button below does nothing, the page rendered on the\n // server but never hydrated — the runtime never mounted at \\`#vessel\\`. This is\n // deliberately here so that failure is impossible to miss.\n const [count, setCount] = useState(0);\n const [locale, setLocale] = useState<\"en\" | \"ar\">(\"en\");\n const [submitted, setSubmitted] = useState(false);\n const [submitError, setSubmitError] = useState<string | null>(null);\n\n const toggleLocale = () => {\n const nextLocale = locale === \"en\" ? \"ar\" : \"en\";\n setCurrentLocaleCode(nextLocale);\n setLocale(nextLocale);\n };\n\n return (\n <>\n {/*\n Self-contained, dependency-free styling: plain CSS, system fonts, and\n CSS custom properties, scoped to this page. No CSS framework, no utility\n classes, no external stylesheet — this page looks the same whether or\n not \\`warlock add tailwind\\` has ever been run.\n */}\n <style>{\\`\n .wk-home {\n --wk-fg: #0f172a;\n --wk-muted: #64748b;\n --wk-accent: #4f46e5;\n --wk-border: #e2e8f0;\n font-family: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n color: var(--wk-fg);\n max-width: 42rem;\n margin: 4rem auto;\n padding: 0 1.5rem;\n line-height: 1.6;\n }\n .wk-home h1 { font-size: 2.25rem; margin: 0 0 0.5rem; }\n .wk-home p { color: var(--wk-muted); margin: 0 0 1.5rem; }\n .wk-home code {\n font-family: ui-monospace, \"SFMono-Regular\", Menlo, monospace;\n background: #f1f5f9;\n padding: 0.1rem 0.35rem;\n border-radius: 0.25rem;\n }\n .wk-check {\n border: 1px solid var(--wk-border);\n border-radius: 0.75rem;\n padding: 1.25rem 1.5rem;\n margin: 2rem 0;\n }\n .wk-check strong { display: block; font-size: 1.5rem; }\n .wk-check button {\n font: inherit;\n cursor: pointer;\n background: var(--wk-accent);\n color: #fff;\n border: 0;\n border-radius: 0.5rem;\n padding: 0.5rem 1rem;\n margin-top: 0.75rem;\n }\n .wk-links { display: flex; gap: 1.25rem; font-size: 0.95rem; }\n .wk-links a { color: var(--wk-accent); text-decoration: none; }\n .wk-links a:hover { text-decoration: underline; }\n .wk-language { margin-left: auto; }\n .wk-contact { margin-top: 2rem; }\n .wk-field { display: grid; gap: 0.35rem; margin: 0.8rem 0; }\n .wk-field input, .wk-field textarea { font: inherit; padding: 0.55rem; }\n .wk-field p, .wk-submit-error { color: #b91c1c; margin: 0; }\n .wk-success { color: #047857; }\n \\`}</style>\n\n <main className=\"wk-home\" dir={locale === \"ar\" ? \"rtl\" : \"ltr\"}>\n <nav className=\"wk-links\" aria-label=\"Starter links\">\n <a href=\"https://warlock.js.org\" target=\"_blank\" rel=\"noreferrer\">\n Docs\n </a>\n <Link href=\"/\" aria-current=\"page\">\n Home\n </Link>\n <button\n className=\"wk-language\"\n type=\"button\"\n aria-pressed={locale === \"ar\"}\n onClick={toggleLocale}\n >\n {transX(\"starter.language\")}\n </button>\n </nav>\n\n <h1>{transX(\"starter.title\")}</h1>\n <p>{transX(\"starter.introduction\")}</p>\n\n <section className=\"wk-check\">\n <label>If this number goes up when you click, React is hydrated:</label>\n <strong>{count}</strong>\n <button type=\"button\" onClick={() => setCount((c) => c + 1)}>\n Count up\n </button>\n </section>\n\n <section className=\"wk-contact\" aria-labelledby=\"contact-heading\">\n <h2 id=\"contact-heading\">{transX(\"starter.contact\")}</h2>\n <Form<typeof contactSchema>\n id=\"contact-form\"\n schema={contactSchema}\n onSubmit={async ({ form, values }) => {\n setSubmitted(false);\n setSubmitError(null);\n const result = await http.post<{ message: string }>(\"/api/contact\", values);\n\n if (result.error) {\n if (result.error.isValidationError) {\n const body = result.error.body as {\n errors?: Array<{ input: string; error: string }>;\n message?: string;\n };\n form.setErrors(\n Object.fromEntries(\n (body.errors ?? []).map(({ input, error }) => [input, error]),\n ),\n );\n setSubmitError(body.message ?? \"Please correct the highlighted fields.\");\n } else {\n setSubmitError(\"Your message could not be sent. Please try again.\");\n }\n return;\n }\n\n setSubmitted(true);\n form.reset();\n }}\n >\n <TextInput name=\"name\" label={transX(\"starter.name\")} autoComplete=\"name\" />\n <TextInput\n name=\"email\"\n label={transX(\"starter.email\")}\n type=\"email\"\n autoComplete=\"email\"\n />\n <ContactMessage />\n <button type=\"submit\">{transX(\"starter.submit\")}</button>\n {submitError && (\n <p className=\"wk-submit-error\" role=\"alert\">\n {submitError}\n </p>\n )}\n {submitted && (\n <p className=\"wk-success\" role=\"status\">\n {transX(\"starter.sent\")}\n </p>\n )}\n </Form>\n </section>\n </main>\n </>\n );\n}\n\nfunction ContactMessage() {\n const { error, getErrorProps, getInputProps } = useFormControl({ name: \"message\" });\n\n return (\n <div className=\"wk-field\">\n <label htmlFor=\"message\">{transX(\"starter.message\")}</label>\n <textarea {...getInputProps()} rows={5} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n`;\n"],"mappings":";AAAA,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BhC,MAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B5B,MAAa,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCnC,MAAa,2BAA2B;;AAGxC,MAAa,0BAA0B;;;;;;;;;;;;AAavC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FvC,MAAa,+BAA+B;;AAG5C,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;AAsB3C,MAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ClC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;AAkBhC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFvC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCvC,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDrC,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;AAwBzC,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;AAsBxC,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,MAAa,+BAA+B;;;;;;;;;;;;;;;;;AAkB5C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;AAqB/C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;AAyB/C,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;AAsBlD,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BtC,MAAa,0BAA0B;;;;;AAMvC,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3C,SAAgB,+BAA+B,QAAyB,MAAsB;CAC5F,MAAM,SAAS,WAAW,QAAQ,YAAY;CAC9C,IAAI;CACJ,IAAI,SAAS,kBACX,gBAAgB;;;;;;;;;;;;;;;;;;;;MAoBX,IAAI,SAAS,+BAClB,gBAAgB;;;;;;;;;;MAUX,IAAI,SAAS,2BAClB,gBAAgB;;;;;;;;;;;;;;;;MAiBhB,gBAAgB;;;;;;;;;;;;;;;CAoBlB,OAAO,wBAAwB,OAAO;;EAHpC,WAAW,UACP,kFACA,GAGM;;YAEF,OAAO,GAAG,KAAK;;6BAEE,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;EAe3C,cAAc,WAAW,YAAY,WAAW,EAAE;;;;AAIpD;;AAGA,MAAa,mBAAmB;;;;;;;;;;;;AAahC,MAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4D3B,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BxC,MAAa,uBAAuB;;;;;;AAOpC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0ChC,MAAa,kBAAkB"}
1
+ {"version":3,"file":"stubs.mjs","names":["config"],"sources":["../../../../../../../../packages/core/src/generations/stubs.ts"],"sourcesContent":["import config from \"@mongez/config\";\n\nexport const accessConfigStub = `import { type AccessConfigurations } from \"@warlock.js/access\";\nimport { DatabaseAccessResolver } from \"app/access/services/access-resolver\";\n\n/**\n * Authorization configuration — read by @warlock.js/access on boot.\n *\n * The resolver is the one required piece: it tells the engine how to read a\n * user's roles + permissions. The ejected DatabaseAccessResolver reads roles\n * from the user_roles table and maps them through the roles catalog table (so\n * roles + their permissions are managed at runtime, in the DB).\n *\n * For a fixed, code-defined catalog with no tables, swap in DefaultAccessResolver:\n * import { DefaultAccessResolver } from \"@warlock.js/access\";\n * resolver: new DefaultAccessResolver({ admin: [\"*\"], editor: [\"orders.*\"] }),\n *\n * Multi-tenant? Add a \\`resolveTenant()\\` to the resolver to read the active\n * tenant from the request; checks then scope to it automatically.\n */\nconst access: AccessConfigurations = {\n resolver: new DatabaseAccessResolver(),\n\n // Cache resolved permission sets (default \"10m\").\n // cache: { ttl: \"10m\" },\n};\n\nexport default access;\n`;\n\nexport const aiConfigStub = `import type { AIConfig } from \"@warlock.js/ai\";\n\n// >>> warlock:ai-packages (auto-managed) >>>\n// Satellite packages augment the \"ai\" object on import — e.g. ai.workspace,\n// ai.tools / ai.mcp, and panoptic's ai.config({ panoptic }) wiring. The command\n// \"warlock add ai-workspace | ai-tools | ai-panoptic\" adds the matching\n// side-effect import below; keep them so the augmentation + runtime registration\n// load before the ai connector applies this config.\n// <<< warlock:ai-packages <<<\n\n/**\n * AI configuration — applied on boot by the ai connector, which calls\n * ai.config(...) with the object below. Cross-cutting defaults live here\n * (shared cache / snapshot stores, observability); per-call options always win.\n *\n * Wire a default model from a provider you installed, e.g.:\n * import { OpenAISDK } from \"@warlock.js/ai-openai\";\n * const openai = OpenAISDK({ apiKey: env(\"OPENAI_API_KEY\") });\n * // then pass openai.model({ name: \"gpt-4o-mini\" }) into your agents.\n */\nconst ai: Partial<AIConfig> = {\n // Default cache driver for cache-backed AI features (semantic cache, rag / memory vector stores).\n // defaultStore: cache.driver(\"redis\", { client }),\n\n // Observability — requires \"warlock add ai-panoptic\". Exporters + the local dashboard.\n // panoptic: { exporters: [], dashboard: false, observeAll: false },\n};\n\nexport default ai;\n`;\n\nexport const accessRoleModelStub = `import { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for the roles catalog — mirrors the migration columns\n * (snake_case). Each row is a role name plus the permission strings it grants;\n * wildcards work (\"orders.*\", \"*\"). The DatabaseAccessResolver maps a user's\n * assigned role names through this table to their effective permissions.\n */\nexport const roleSchema = v.object({\n name: v.string(),\n permissions: v.array(v.string()).default([]),\n});\n\nexport type RoleSchema = Infer<typeof roleSchema>;\n\n/**\n * The roles catalog — role name → the permissions it grants. Managed at runtime\n * (admins add roles + edit their permissions), unlike a fixed code map. Read by\n * DatabaseAccessResolver.resolvePermissions to expand a user's roles to permissions.\n */\n@RegisterModel()\nexport class Role extends Model<RoleSchema> {\n public static table = \"roles\";\n\n public static schema = roleSchema;\n\n /** The permission strings this role grants. */\n public get permissions(): string[] {\n return this.get<string[]>(\"permissions\", []);\n }\n}\n`;\n\nexport const accessRoleModelIndexStub = `export * from \"./role.model\";\n`;\n\nexport const accessRoleMigrationStub = `import { arrayText, Migration, text } from \"@warlock.js/cascade\";\nimport { Role } from \"../role.model\";\n\n/**\n * Roles catalog table. \\`name\\` is unique (one row per role); \\`permissions\\` is a\n * text array of the permission strings the role grants.\n */\nexport default Migration.create(Role, {\n name: text().notNullable().unique(),\n permissions: arrayText().nullable(),\n});\n`;\n\nexport const accessUserRoleModelStub = `import { access } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Model, RegisterModel } from \"@warlock.js/cascade\";\nimport { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Validation schema for a role assignment — mirrors the migration columns\n * (snake_case). \\`tenant\\` is nullable: a null tenant is a GLOBAL assignment.\n */\nexport const userRoleSchema = v.object({\n user_id: v.string(),\n user_type: v.string(),\n role: v.string(),\n tenant: v.string().optional(),\n});\n\nexport type UserRoleSchema = Infer<typeof userRoleSchema>;\n\n/**\n * The role-assignment table — which roles a user holds, optionally per tenant.\n * Read by DatabaseAccessResolver.resolveRoles; mutated via the statics below.\n * \\`assign\\` / \\`revoke\\` flush the cached permission set automatically, so callers\n * never need to call \\`access.flush(user, tenant)\\` themselves.\n */\n@RegisterModel()\nexport class UserRole extends Model<UserRoleSchema> {\n public static table = \"user_roles\";\n\n public static schema = userRoleSchema;\n\n /**\n * Role names assigned to the user in the given tenant.\n *\n * An unresolved tenant (\\`undefined\\`) scopes to GLOBAL roles only — the rows\n * stored with no tenant (\\`null\\`) — never the union across every tenant. The\n * union would be a privilege-escalation: a user who is \\`owner\\` in one tenant\n * must not be treated as \\`owner\\` everywhere just because a check didn't carry\n * a tenant. This mirrors how \\`assign(user, role)\\` stores a global row.\n */\n public static async rolesFor(user: Auth, tenant?: string): Promise<string[]> {\n const rows = await this.query()\n .where({\n user_id: user.id,\n user_type: user.userType,\n tenant: tenant ?? null,\n })\n .get();\n\n // De-dupe so a duplicate row (a concurrent assign that slipped past the\n // existence check) can't distort the resolved set.\n return [...new Set(rows.map((row) => row.get(\"role\") as string))];\n }\n\n /**\n * Assign a role to the user. No-op if the assignment already exists.\n * Flushes the user's cached permission set automatically.\n */\n public static async assign(user: Auth, role: string, tenant?: string): Promise<void> {\n const existing = await this.first({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n if (existing) return;\n\n await this.create({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant,\n });\n\n await access.flush(user, tenant);\n }\n\n /**\n * Remove a role assignment from the user.\n * Flushes the user's cached permission set automatically.\n */\n public static async revoke(user: Auth, role: string, tenant?: string): Promise<void> {\n await this.delete({\n user_id: user.id,\n user_type: user.userType,\n role,\n tenant: tenant ?? null,\n });\n\n await access.flush(user, tenant);\n }\n}\n`;\n\nexport const accessUserRoleModelIndexStub = `export * from \"./user-role.model\";\n`;\n\nexport const accessUserRoleMigrationStub = `import { Migration, text, uuid } from \"@warlock.js/cascade\";\nimport { UserRole } from \"../user-role.model\";\n\n/**\n * Role-assignment table. \\`user_id\\` is a UUID — override this migration if your\n * user ids are integers. The composite index powers the per-user (per-tenant)\n * lookup the resolver runs on every check.\n */\nexport default Migration.create(\n UserRole,\n {\n user_id: uuid().notNullable().index(),\n user_type: text().notNullable(),\n role: text().notNullable().index(),\n tenant: text().nullable().index(),\n },\n {\n index: [{ columns: [\"user_id\", \"user_type\", \"tenant\"] }],\n },\n);\n`;\n\nexport const accessResolverStub = `import type { AccessResolver } from \"@warlock.js/access\";\nimport type { Auth } from \"@warlock.js/auth\";\nimport { Role } from \"app/access/models/role\";\nimport { UserRole } from \"app/access/models/user-role\";\n\n/**\n * The app's access adapter — connects @warlock.js/access to the ejected role\n * tables. Roles come from the user_roles assignment table; permissions are\n * expanded by mapping those role names through the roles catalog table. Both\n * are managed at runtime (in the DB), so admins can add roles + edit their\n * permissions without a deploy.\n *\n * The engine owns the hard parts (wildcard matching, caching, fail-closed); this\n * resolver only fetches — keep it dumb, never cache inside it.\n */\nexport class DatabaseAccessResolver implements AccessResolver {\n /** The role names this user holds (powers \\`hasRole\\` / \\`hasAnyRole\\`). */\n public async resolveRoles(user: Auth, tenant?: string): Promise<string[]> {\n return UserRole.rolesFor(user, tenant);\n }\n\n /** The effective permission strings this user has (powers \\`can\\` / \\`authorize\\`). */\n public async resolvePermissions(user: Auth, tenant?: string): Promise<string[]> {\n const names = await this.resolveRoles(user, tenant);\n\n if (names.length === 0) return [];\n\n const roles = await Role.query().whereIn(\"name\", names).get();\n\n // Flatten + de-dupe so two roles granting the same permission yield one entry.\n return [...new Set(roles.flatMap((role) => role.permissions))];\n }\n\n /**\n * Optional. Resolve the ambient tenant when a check doesn't pass one\n * explicitly — derive it from the authenticated user (safer than reading\n * client request input, which a caller could spoof). Uncomment + adapt for a\n * multi-tenant app (single-tenant apps leave this off and return undefined).\n */\n // public resolveTenant(user: Auth): string | undefined {\n // return user.get(\"organization_id\");\n // }\n}\n`;\n\nexport const socketConfigStub = `import type { SocketOptions } from \"@warlock.js/core\";\n\n/**\n * Socket.IO configuration — read by the framework's socket connector\n * on boot. When the HTTP server is running the socket server attaches\n * to it; otherwise it listens on its own configured port.\n *\n * Remove this file to disable the socket server entirely.\n */\nexport default {\n options: {\n cors: {\n origin: \"*\",\n },\n },\n} as SocketOptions;\n`;\n\nexport const communicatorsConfigStub = `import { env } from \"@warlock.js/core\";\nimport type { BrokerConfigurations, RabbitMQClientOptions } from \"@warlock.js/herald\";\n\nconst heraldConfigurations: BrokerConfigurations<RabbitMQClientOptions> = {\n driver: \"rabbitmq\",\n name: \"default\",\n isDefault: true,\n\n // ============================================================================\n // Connection Settings\n // ============================================================================\n\n host: env(\"RABBITMQ_HOST\", \"localhost\"),\n port: env(\"RABBITMQ_PORT\", 5672),\n username: env(\"RABBITMQ_USERNAME\", \"guest\"),\n password: env(\"RABBITMQ_PASSWORD\", \"guest\"),\n vhost: env(\"RABBITMQ_VHOST\", \"/\"),\n\n // Or use connection URI (takes precedence over host/port)\n // uri: env(\"RABBITMQ_URL\"),\n\n // ============================================================================\n // Connection Options\n // ============================================================================\n\n /** Heartbeat interval in seconds */\n heartbeat: 60,\n\n /** Connection timeout in milliseconds */\n connectionTimeout: 10000,\n\n /** Enable automatic reconnection on disconnect */\n reconnect: true,\n\n /** Delay between reconnection attempts in milliseconds */\n reconnectDelay: 5_000,\n\n // ============================================================================\n // Consumer Options\n // ============================================================================\n\n /** Default prefetch count (number of unacknowledged messages per consumer) */\n prefetch: 10,\n\n // ============================================================================\n // Client Options (Native amqplib options)\n // ============================================================================\n // These options are passed directly to amqplib.connect()\n // for low-level configuration like frame size, TLS, socket options, etc.\n // ============================================================================\n clientOptions: {\n // Frame max size in bytes (0 = no limit)\n // frameMax: 0,\n\n // Channel max (0 = unlimited)\n // channelMax: 0,\n\n // Socket options\n socket: {\n // Enable TCP keep-alive\n keepAlive: true,\n\n // Disable Nagle's algorithm for lower latency\n noDelay: true,\n\n // Socket timeout (in addition to heartbeat)\n // timeout: 30000,\n },\n\n // TLS/SSL options (uncomment for secure connections)\n // socket: {\n // ca: fs.readFileSync('/path/to/ca.pem'),\n // cert: fs.readFileSync('/path/to/cert.pem'),\n // key: fs.readFileSync('/path/to/key.pem'),\n // rejectUnauthorized: true,\n // },\n },\n};\n\nexport default heraldConfigurations;\n`;\n\nexport const notificationsConfigStub = `import { type NotificationConfig, inApp, mailChannel } from \"@warlock.js/notifications\";\nimport { Notification } from \"app/notifications/models/notification/notification.model\";\n\n/**\n * Notifications configuration. Auto-loaded from src/config on boot — the\n * framework's notifications connector reads this default export and hands it to\n * setNotificationConfig, so this file stays declarative (no side-effect call).\n *\n * Each channel is payload-typed, so notify.mail(...) / notify.database(...)\n * and defineNotification are type-checked against the registry.\n *\n * Channels enabled here:\n * - mail wraps @warlock.js/core sendMail; route is notifiable.email.\n * The \"from\" address defaults to config/mail.ts; override per\n * channel with mailChannel({ from: \"no-reply@yourapp.com\" }).\n * - database in-app store backed by the Notification model. The \"inApp\"\n * facade exposes the recipient-scoped read API: listUnread,\n * countUnread, markAsRead, dismiss, ...\n *\n * Async delivery (.queue()) is OPTIONAL: run \"npx warlock add herald\",\n * import { heraldQueue } from \"@warlock.js/notifications\", and uncomment the\n * queue line below.\n */\nconst config: NotificationConfig = {\n channels: {\n mail: mailChannel(),\n database: inApp.configure({ model: Notification }),\n },\n\n // Async queue — requires @warlock.js/herald (npx warlock add herald):\n // queue: heraldQueue(),\n};\n\nexport default config;\n`;\n\n/** `src/app/notifications/models/notification/notification.model.ts`. */\nexport const notificationModelStub = `import { RegisterModel } from \"@warlock.js/cascade\";\nimport { DatabaseNotification, type NotificationColumnMap } from \"@warlock.js/notifications\";\nimport { v } from \"@warlock.js/seal\";\nimport { NotificationResource } from \"../../resources/notification.resource\";\n\n/**\n * Validation schema for the notifications table — mirrors the migration\n * columns (snake_case). Cascade validates + casts every write against it:\n * nullable columns use .nullish() (may be absent or null), and payload is\n * free-form JSON. Keep this in sync with the migration + columnMap when you\n * add or rename columns.\n *\n * user_id accepts a string or an integer so it matches whichever id type your\n * users use (and the idType you pass to notificationColumns in the migration).\n * Narrow it to that one type.\n */\nconst notificationSchema = v.object({\n user_id: v.union([v.string(), v.int()]),\n type: v.string(),\n title: v.string(),\n body: v.string().nullish(),\n payload: v.record(v.any()).nullish(),\n read_at: v.date().nullish(),\n idempotency_key: v.string().nullish(),\n});\n\n/**\n * In-app notification model.\n *\n * Extends the package's DatabaseNotification base, which provides the stable\n * accessors (recipientId, tenantId, isRead, readAt, markRead) — all derived\n * from the columnMap below. The read/write API lives on the inApp facade\n * (configured in config/notifications.ts); you rarely touch this class directly.\n */\n@RegisterModel()\nexport class Notification extends DatabaseNotification {\n public static table = \"notifications\";\n public static schema = notificationSchema;\n\n /** Every response that returns a notification is shaped by this resource. */\n public static resource = NotificationResource;\n\n /**\n * Maps the in-app store's roles to your columns. This default is\n * single-tenant + read_at-only. Add tenant: \"organization_id\" for\n * multi-tenant; use isRead: \"is_read\" (instead of, or alongside, readAt) to\n * track a boolean read flag. The migration, the accessors and the resource\n * all follow this map.\n */\n public static columnMap: NotificationColumnMap = { readAt: \"read_at\" };\n}\n`;\n\n/** The notifications migration, under `models/notification/migrations/`. */\nexport const notificationMigrationStub = `import { Migration } from \"@warlock.js/cascade\";\nimport { notificationColumns } from \"@warlock.js/notifications\";\nimport { Notification } from \"../notification.model\";\n\n/**\n * Notifications table.\n *\n * Columns come from notificationColumns(Notification) — the recipient / tenant\n * / read-state names follow the model's columnMap; type / title / body /\n * payload / idempotency_key are fixed. The recipient column is a UUID unless\n * you pass { idType: \"integer\" } (or \"bigint\" / \"string\") to match your users.\n * Spread it to add your own columns (and mirror them in the model schema):\n *\n * import { uuid } from \"@warlock.js/cascade\";\n *\n * export default Migration.create(Notification, {\n * ...notificationColumns(Notification, { idType: \"integer\" }),\n * // category_id: uuid().index().nullable(),\n * });\n */\nexport default Migration.create(Notification, notificationColumns(Notification));\n`;\n\n/** `src/app/notifications/resources/notification.resource.ts` — the output shape. */\nexport const notificationResourceStub = `import { defineResource } from \"@warlock.js/core\";\n\n/**\n * What every notification endpoint returns, whatever columns the model holds.\n * readAt reads the default read_at column; change it if you change the model's\n * columnMap.\n */\nexport const NotificationResource = defineResource({\n schema: {\n // Passed through as stored: a UUID string or an integer, per the migration.\n id: (id: string | number) => id,\n type: \"string\",\n title: \"string\",\n body: \"string?\",\n payload: \"object?\",\n readAt: [\"read_at\", \"date?\"],\n createdAt: \"date?\",\n },\n});\n`;\n\n/** `src/app/notifications/schema/list-notifications.schema.ts` — the validated list query. */\nexport const listNotificationsSchemaStub = `import { type Infer, v } from \"@warlock.js/seal\";\n\n/**\n * Query for GET /notifications. Only these keys reach the store (others, such\n * as a cache-busting \\`_\\`, are dropped rather than rejected), and limit is\n * capped so one request cannot read every row. Query values arrive as strings,\n * so the numbers and the flag are coerced.\n */\nexport const listNotificationsSchema = v.object({\n page: v.int().coerce().min(1).optional(),\n limit: v.int().coerce().min(1).max(50).optional(),\n type: v.string().optional(),\n unread: v.boolean().coerce().optional(),\n}).stripUnknown();\n\nexport type ListNotificationsSchema = Infer<typeof listNotificationsSchema>;\n`;\n\n/** `src/app/notifications/types/notifications-request.type.ts` — the guarded request. */\nexport const notificationsRequestTypeStub = `import type { Request, RequestHandler, RequestLocals } from \"@warlock.js/core\";\nimport type { Id } from \"@warlock.js/notifications\";\n\n/**\n * A request that passed authMiddleware, so locals.user is always set. Only the\n * user's id is declared because that is all the inApp store needs. If your\n * app has its own guarded request type, use it instead.\n */\nexport type NotificationsRequest<Payload = unknown> = Request<Payload> & {\n locals: RequestLocals & { user: { id: Id } };\n};\n\nexport type NotificationsRequestHandler<Payload = unknown> = RequestHandler<\n NotificationsRequest<Payload>\n>;\n`;\n\n/** `src/app/notifications/services/mark-notification-read.service.ts`. */\nexport const markNotificationReadServiceStub = `import { ResourceNotFoundError, t } from \"@warlock.js/core\";\nimport { type Id, inApp } from \"@warlock.js/notifications\";\n\n/**\n * Mark one of the user's notifications read and return it. inApp is scoped to\n * the recipient, so another user's id changes nothing and answers 404 here.\n */\nexport async function markNotificationReadService(userId: Id, notificationId: Id) {\n await inApp.markAsRead(userId, notificationId);\n\n const notification = await inApp.find(userId, notificationId);\n\n if (!notification) {\n throw new ResourceNotFoundError(t(\"notifications.notFound\"));\n }\n\n return notification;\n}\n`;\n\n/** `src/app/notifications/controllers/list-notifications.controller.ts`. */\nexport const listNotificationsControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport {\n type ListNotificationsSchema,\n listNotificationsSchema,\n} from \"../schema/list-notifications.schema\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications — the user's notifications, most recent first. */\nexport const listNotificationsController: NotificationsRequestHandler<\n ListNotificationsSchema\n> = async ({ request, response }) => {\n const { data, pagination } = await inApp.list(request.locals.user.id, request.validated());\n\n return response.success({ notifications: data, pagination });\n};\n\nlistNotificationsController.description = \"List notifications\";\n\nlistNotificationsController.validation = {\n schema: listNotificationsSchema,\n validating: [\"query\"],\n};\n`;\n\n/** `src/app/notifications/controllers/unread-notifications-count.controller.ts`. */\nexport const unreadNotificationsCountControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** GET /notifications/unread-count — drives the bell badge. */\nexport const unreadNotificationsCountController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.countUnread(request.locals.user.id);\n\n return response.success({ count });\n};\n\nunreadNotificationsCountController.description = \"Unread notifications count\";\n`;\n\n/** `src/app/notifications/controllers/mark-notification-read.controller.ts`. */\nexport const markNotificationReadControllerStub = `import { markNotificationReadService } from \"../services/mark-notification-read.service\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/:id/read — mark one read and return it. */\nexport const markNotificationReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n // Route params are strings. A numeric id is an integer id (the default\n // MongoDB stack); anything else, such as a UUID, stays a string.\n const rawId = request.string(\"id\");\n const id = /^\\\\d+$/.test(rawId) ? Number(rawId) : rawId;\n\n const notification = await markNotificationReadService(request.locals.user.id, id);\n\n return response.success({ notification });\n};\n\nmarkNotificationReadController.description = \"Mark notification read\";\n`;\n\n/** `src/app/notifications/controllers/mark-all-notifications-read.controller.ts`. */\nexport const markAllNotificationsReadControllerStub = `import { inApp } from \"@warlock.js/notifications\";\nimport type { NotificationsRequestHandler } from \"../types/notifications-request.type\";\n\n/** PATCH /notifications/read-all — mark every unread one read. */\nexport const markAllNotificationsReadController: NotificationsRequestHandler = async ({\n request,\n response,\n}) => {\n const count = await inApp.markAsRead(request.locals.user.id);\n\n return response.success({ count });\n};\n\nmarkAllNotificationsReadController.description = \"Mark all notifications read\";\n`;\n\n/** `src/app/notifications/routes.ts` — the four read endpoints behind `authMiddleware`. */\nexport const notificationRoutesStub = `import { authMiddleware } from \"@warlock.js/auth\";\nimport { router } from \"@warlock.js/core\";\nimport { listNotificationsController } from \"./controllers/list-notifications.controller\";\nimport { markAllNotificationsReadController } from \"./controllers/mark-all-notifications-read.controller\";\nimport { markNotificationReadController } from \"./controllers/mark-notification-read.controller\";\nimport { unreadNotificationsCountController } from \"./controllers/unread-notifications-count.controller\";\n\n/**\n * The signed-in user's own notifications.\n *\n * Notifications come from domain events, so there is no create. Dismissing is\n * left out on purpose; add it when the product needs it (inApp.dismiss).\n *\n * authMiddleware([]) admits any signed-in user. To limit who may read\n * notifications, add a permission gate to the group:\n *\n * import { gate } from \"@warlock.js/access\";\n *\n * router.group({ middleware: [authMiddleware([]), gate(\"notifications.read\")] }, ...);\n */\nrouter.group({ middleware: [authMiddleware([])] }, () => {\n const notifications = router.route(\"/notifications\");\n\n notifications.list(listNotificationsController);\n notifications.nest(\"/unread-count\").get(unreadNotificationsCountController);\n notifications.nest(\"/read-all\").patch(markAllNotificationsReadController);\n notifications.nest(\"/:id/read\").patch(markNotificationReadController);\n});\n`;\n\n/** Build module locale JSON, with English as the explicit translation fallback. */\nexport function createNotificationLocalesStub(): string {\n const configured: unknown = config.get(\"app.localeCodes\");\n const codes: string[] =\n Array.isArray(configured) && configured.length > 0\n ? configured.filter((code): code is string => typeof code === \"string\")\n : [\"en\"];\n return (\n JSON.stringify(\n { notFound: Object.fromEntries(codes.map((code) => [code, \"Notification not found\"])) },\n null,\n 2,\n ) + \"\\n\"\n );\n}\n\nexport const notificationLocalesStub = createNotificationLocalesStub();\n\n/** Shared fixtures for the generated signed-in notification controller specs. */\nexport const notificationTestFixtureStub = `import type { Auth } from \"@warlock.js/auth\";\nimport type { ChildModel } from \"@warlock.js/cascade\";\nimport { config } from \"@warlock.js/core\";\nimport { actingAs, type AuthenticatedTestClient } from \"@warlock.js/core/tests\";\nimport { randomUUID } from \"node:crypto\";\nimport { Notification } from \"../models/notification/notification.model\";\n\n/** Isolated recipients and rows; adjust user fields if your auth model requires more. */\nexport async function createNotificationTestFixture() {\n const User = config.key<ChildModel<Auth>>(\"auth.userType.user\");\n if (!User) throw new Error(\"Notification specs need the configured auth.userType.user model.\");\n const users: Auth[] = [];\n const clients: AuthenticatedTestClient[] = [];\n const rows: Notification[] = [];\n\n async function cleanup() {\n const credentials = await Promise.allSettled(\n clients.splice(0).map((client) => client.dispose()),\n );\n const notifications = await Promise.allSettled(\n rows.splice(0).map((row) => row.destroy({ strategy: \"permanent\" })),\n );\n const recipients = await Promise.allSettled(\n users.splice(0).map((user) => user.destroy({ strategy: \"permanent\" })),\n );\n const errors = [...credentials, ...notifications, ...recipients]\n .filter((result): result is PromiseRejectedResult => result.status === \"rejected\")\n .map((result) => result.reason);\n if (errors.length) throw new AggregateError(errors, \"Notification fixture cleanup failed.\");\n }\n\n const createUser = async () => {\n const user = await User.create({\n name: \"Notification test user\",\n email: \"notifications-\" + randomUUID() + \"@example.test\",\n password: \"test-password\",\n });\n users.push(user);\n return user;\n };\n const signIn = async (user: Auth) => {\n const client = await actingAs(user);\n clients.push(client);\n return client;\n };\n const createNotification = async (recipientId: string | number, title: string, readAt?: Date) => {\n const row = await Notification.create({\n user_id: recipientId,\n type: \"test\",\n title,\n read_at: readAt,\n });\n rows.push(row);\n return row;\n };\n\n try {\n const user = await createUser();\n const otherUser = await createUser();\n const client = await signIn(user);\n const otherClient = await signIn(otherUser);\n const own = await createNotification(user.id, \"Own unread notification\");\n const alreadyRead = await createNotification(user.id, \"Own read notification\", new Date());\n const foreign = await createNotification(otherUser.id, \"Other user's notification\");\n await createNotification(otherUser.id, \"Other user's second notification\");\n return { user, otherUser, client, otherClient, own, alreadyRead, foreign, cleanup };\n } catch (error) {\n // Preserve the setup failure after attempting every owned resource's cleanup.\n await cleanup().catch(() => undefined);\n throw error;\n }\n}\n`;\n\n/** A spec for each generated controller, including authenticated recipient isolation. */\nexport function notificationControllerSpecStub(method: \"GET\" | \"PATCH\", path: string): string {\n const helper = method === \"GET\" ? \"testGet\" : \"testPatch\";\n let signedInCases: string;\n if (path === \"/notifications\") {\n signedInCases = ` it(\"lists only the signed-in recipient's rows, ignoring a forged recipient query\", async () => {\n const response = await fixture.client.get(\n \"/notifications?recipientId=\" + fixture.otherUser.id,\n );\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual(\n expect.arrayContaining([fixture.own.id, fixture.alreadyRead.id]),\n );\n expect(body.notifications).toHaveLength(2);\n });\n\n it(\"applies unread and paging query filters\", async () => {\n const response = await fixture.client.get(\"/notifications?unread=true&limit=1\");\n const body = await expectJson<{ notifications: { id: string | number }[] }>(response);\n expect(body.notifications.map((row) => row.id)).toEqual([fixture.own.id]);\n });\n\n it(\"rejects a list limit above the schema's cap\", async () => {\n expect((await fixture.client.get(\"/notifications?limit=999\")).status).toBe(422);\n });`;\n } else if (path === \"/notifications/unread-count\") {\n signedInCases = ` it(\"counts only this recipient's unread notifications\", async () => {\n const own = await expectJson<{ count: number }>(\n await fixture.client.get(\"/notifications/unread-count\"),\n );\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(own.count).toBe(1);\n expect(other.count).toBe(2);\n });`;\n } else if (path === \"/notifications/read-all\") {\n signedInCases = ` it(\"marks only this recipient's unread rows and leaves another recipient unchanged\", async () => {\n const body = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(body.count).toBe(1);\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n const other = await expectJson<{ count: number }>(\n await fixture.otherClient.get(\"/notifications/unread-count\"),\n );\n expect(other.count).toBe(2);\n const again = await expectJson<{ count: number }>(\n await fixture.client.patch(\"/notifications/read-all\"),\n );\n expect(again.count).toBe(0);\n });`;\n } else {\n signedInCases = ` it(\"marks its own notification read and returns it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.own.id + \"/read\");\n const body = await expectJson<{\n notification: { id: string | number; readAt?: string | null };\n }>(response);\n expect(body.notification.id).toBe(fixture.own.id);\n expect(body.notification.readAt).toBeTruthy();\n expect((await Notification.find(fixture.own.id))?.isRead).toBe(true);\n });\n\n it(\"answers 404 for another recipient's notification without changing it\", async () => {\n const response = await fixture.client.patch(\"/notifications/\" + fixture.foreign.id + \"/read\");\n expect(response.status).toBe(404);\n expect((await Notification.find(fixture.foreign.id))?.isRead).toBe(false);\n });`;\n }\n const modelImport =\n method === \"PATCH\"\n ? 'import { Notification } from \"../models/notification/notification.model\";\\n'\n : \"\";\n return `import { expectJson, ${helper} } from \"@warlock.js/core/tests\";\nimport { afterEach, beforeEach, describe, expect, it } from \"vitest\";\n${modelImport}import { createNotificationTestFixture } from \"../tests/notifications.fixture\";\n\ndescribe(\"${method} ${path}\", () => {\n it(\"answers 401 without a signed-in user\", async () => {\n const response = await ${helper}(\"${path}\");\n expect(response.status).toBe(401);\n });\n\n describe(\"signed in\", () => {\n let fixture: Awaited<ReturnType<typeof createNotificationTestFixture>> | undefined;\n beforeEach(async () => {\n fixture = await createNotificationTestFixture();\n });\n afterEach(async () => {\n const current = fixture;\n fixture = undefined;\n await current?.cleanup();\n });\n\n${signedInCases.replaceAll(\"fixture.\", \"fixture!.\")}\n });\n});\n`;\n}\n\n/** `src/web/root.setup.ts` — document policy. */\nexport const webRootSetupStub = `import type { RootConfig } from \"@warlock.js/web\";\n\nexport const config: RootConfig = { strictMode: true };\n`;\n\n/**\n * `src/web/root.tsx` — the application root for the SSR page layer.\n *\n * Deliberately minimal. The framework ships a default root, so this exists to\n * give you a place to start rather than because anything requires it. The\n * document component stays here; request policy and an app-level loader\n * belong in `root.setup.ts`. Named ErrorBoundary components stay in the UI.\n */\nexport const webRootStub = `import type { AppProps } from \"@warlock.js/web\";\nimport { Head, Scripts } from \"@warlock.js/web\";\n\n/**\n * The application root.\n *\n * NOT async, and it receives no request/response: it renders on the server and\n * again in the browser during hydration, where neither exists.\n */\nexport default function App({ children }: AppProps) {\n return (\n <html lang=\"en\">\n <head>\n {/*\n <Head /> also renders the viewport tag (width=device-width,\n initial-scale=1). Change it with \\`metadata.viewport\\`,\n or set it to false to leave it out; do not add a second one here.\n */}\n {/*\n Placement only. The framework injects the page's \\`metadata\\`, the\n stylesheet and preload tags for this route, and the canonical links\n into <head> by default — <Head /> just says WHERE they land.\n\n Do not add a <title> here: the page's \\`metadata\\` owns it, and a root\n that emits one too produces two.\n */}\n <Head />\n <link rel=\"icon\" href=\"data:,\" />\n </head>\n <body>\n {/*\n REQUIRED — this is the hydration mount point, not a styling wrapper.\n\n The browser runtime looks up \\`#vessel\\` and hydrates that element only.\n Remove this div, or rename the id, and the page still renders from the\n server but never becomes interactive: the runtime throws in the console\n and nothing on screen changes.\n\n Wrap it in your own markup freely, and put anything that must live\n outside the hydrated tree (a static footer, a portal target) outside\n it — just keep an element with \\`id=\"vessel\"\\` around {children}.\n */}\n <div id=\"vessel\">{children}</div>\n {/*\n The hydration payload and module tags. Written explicitly because\n placement occasionally matters — a CSP nonce, or ordering against\n your own scripts.\n */}\n <Scripts />\n </body>\n </html>\n );\n}\n`;\n\n/**\n * `src/app/contact/controllers/contact.controller.ts` — a real API endpoint\n * for the Web starter's contact form. It intentionally has no persistence\n * dependency: replace the acknowledgement with a mail/job/database action.\n */\nexport const webContactControllerStub = `import { type Request, type RequestHandler } from \"@warlock.js/core\";\nimport { v, type Infer } from \"@warlock.js/seal\";\n\nexport const contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nexport type ContactSchema = Infer.Output<typeof contactSchema>;\n\n/** POST /api/contact — validates the starter contact form. */\nexport const contactController: RequestHandler<Request<ContactSchema>> = async ({\n request,\n response,\n}) => {\n const contact = request.validated();\n\n // Replace this with delivery/persistence for your app. Keeping the accepted\n // payload visible makes the endpoint useful while remaining side-effect free.\n return response.success({\n message: \"Thanks, \" + contact.name + \". Your message has been received.\",\n });\n};\n\ncontactController.validation = { schema: contactSchema };\n`;\n\n/** `src/app/contact/routes.ts` — discovered by the standard app route loader. */\nexport const webContactRoutesStub = `import { router } from \"@warlock.js/core\";\nimport { contactController } from \"./controllers/contact.controller\";\n\nrouter.post(\"/api/contact\", contactController, { public: true });\n`;\n\n/** `src/web/index.setup.ts` — page policy and universal registration. */\nexport const webHomeSetupStub = `import { extend } from \"@mongez/localization\";\nimport type { PageConfig } from \"@warlock.js/web\";\n\nexport const config: PageConfig = {\n route: { path: \"/\", name: \"index\" },\n metadata: { title: \"Home\" },\n};\n\nexport function register() {\n extend(\"en\", {\n starter: {\n title: \"Your Warlock app is running.\",\n introduction: \"This page is rendered on the server and hydrated in the browser.\",\n language: \"العربية\",\n contact: \"Send a message\",\n name: \"Name\",\n email: \"Email\",\n message: \"Message\",\n submit: \"Send message\",\n sent: \"Thanks — your message has been received.\",\n },\n });\n extend(\"ar\", {\n starter: {\n title: \"تطبيق Warlock يعمل الآن.\",\n introduction: \"تُعرض هذه الصفحة على الخادم ثم تُفعَّل في المتصفح.\",\n language: \"English\",\n contact: \"أرسل رسالة\",\n name: \"الاسم\",\n email: \"البريد الإلكتروني\",\n message: \"الرسالة\",\n submit: \"إرسال الرسالة\",\n sent: \"شكرًا — تم استلام رسالتك.\",\n },\n });\n}\n`;\n\n/**\n * `src/web/index.page.tsx` — one page, so \\`warlock dev\\` has something to serve\n * the moment this finishes.\n */\nexport const webHomePageStub = `import { http } from \"@mongez/http\";\nimport { setCurrentLocaleCode } from \"@mongez/localization\";\nimport { Form, useFormControl, type FormControlProps } from \"@mongez/react-form\";\nimport { transX } from \"@mongez/react-localization\";\nimport { v } from \"@warlock.js/seal\";\nimport { Link, type PageProps } from \"@warlock.js/web\";\nimport { useState } from \"react\";\n\nconst contactSchema = v.object({\n name: v.string().min(2),\n email: v.email(),\n message: v.string().min(10),\n});\n\nfunction TextInput({ label, ...controlProps }: FormControlProps & { label: string }) {\n const { error, getErrorProps, getInputProps } = useFormControl(controlProps);\n\n return (\n <div className=\"wk-field\">\n <label htmlFor={controlProps.name}>{label}</label>\n <input {...getInputProps()} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n\n/** Fetch data in index.setup.ts; use a type-only loader import for PageProps. */\nexport default function HomePage(_props: PageProps) {\n // Live state. If the button below does nothing, the page rendered on the\n // server but never hydrated — the runtime never mounted at \\`#vessel\\`. This is\n // deliberately here so that failure is impossible to miss.\n const [count, setCount] = useState(0);\n const [locale, setLocale] = useState<\"en\" | \"ar\">(\"en\");\n const [submitted, setSubmitted] = useState(false);\n const [submitError, setSubmitError] = useState<string | null>(null);\n\n const toggleLocale = () => {\n const nextLocale = locale === \"en\" ? \"ar\" : \"en\";\n setCurrentLocaleCode(nextLocale);\n setLocale(nextLocale);\n };\n\n return (\n <>\n {/*\n Self-contained, dependency-free styling: plain CSS, system fonts, and\n CSS custom properties, scoped to this page. No CSS framework, no utility\n classes, no external stylesheet — this page looks the same whether or\n not \\`warlock add tailwind\\` has ever been run.\n */}\n <style>{\\`\n .wk-home {\n --wk-fg: #0f172a;\n --wk-muted: #64748b;\n --wk-accent: #4f46e5;\n --wk-border: #e2e8f0;\n font-family: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n color: var(--wk-fg);\n max-width: 42rem;\n margin: 4rem auto;\n padding: 0 1.5rem;\n line-height: 1.6;\n }\n .wk-home h1 { font-size: 2.25rem; margin: 0 0 0.5rem; }\n .wk-home p { color: var(--wk-muted); margin: 0 0 1.5rem; }\n .wk-home code {\n font-family: ui-monospace, \"SFMono-Regular\", Menlo, monospace;\n background: #f1f5f9;\n padding: 0.1rem 0.35rem;\n border-radius: 0.25rem;\n }\n .wk-check {\n border: 1px solid var(--wk-border);\n border-radius: 0.75rem;\n padding: 1.25rem 1.5rem;\n margin: 2rem 0;\n }\n .wk-check strong { display: block; font-size: 1.5rem; }\n .wk-check button {\n font: inherit;\n cursor: pointer;\n background: var(--wk-accent);\n color: #fff;\n border: 0;\n border-radius: 0.5rem;\n padding: 0.5rem 1rem;\n margin-top: 0.75rem;\n }\n .wk-links { display: flex; gap: 1.25rem; font-size: 0.95rem; }\n .wk-links a { color: var(--wk-accent); text-decoration: none; }\n .wk-links a:hover { text-decoration: underline; }\n .wk-language { margin-left: auto; }\n .wk-contact { margin-top: 2rem; }\n .wk-field { display: grid; gap: 0.35rem; margin: 0.8rem 0; }\n .wk-field input, .wk-field textarea { font: inherit; padding: 0.55rem; }\n .wk-field p, .wk-submit-error { color: #b91c1c; margin: 0; }\n .wk-success { color: #047857; }\n \\`}</style>\n\n <main className=\"wk-home\" dir={locale === \"ar\" ? \"rtl\" : \"ltr\"}>\n <nav className=\"wk-links\" aria-label=\"Starter links\">\n <a href=\"https://warlock.js.org\" target=\"_blank\" rel=\"noreferrer\">\n Docs\n </a>\n <Link href=\"/\" aria-current=\"page\">\n Home\n </Link>\n <button\n className=\"wk-language\"\n type=\"button\"\n aria-pressed={locale === \"ar\"}\n onClick={toggleLocale}\n >\n {transX(\"starter.language\")}\n </button>\n </nav>\n\n <h1>{transX(\"starter.title\")}</h1>\n <p>{transX(\"starter.introduction\")}</p>\n\n <section className=\"wk-check\">\n <label>If this number goes up when you click, React is hydrated:</label>\n <strong>{count}</strong>\n <button type=\"button\" onClick={() => setCount((c) => c + 1)}>\n Count up\n </button>\n </section>\n\n <section className=\"wk-contact\" aria-labelledby=\"contact-heading\">\n <h2 id=\"contact-heading\">{transX(\"starter.contact\")}</h2>\n <Form<typeof contactSchema>\n id=\"contact-form\"\n schema={contactSchema}\n onSubmit={async ({ form, values }) => {\n setSubmitted(false);\n setSubmitError(null);\n const result = await http.post<{ message: string }>(\"/api/contact\", values);\n\n if (result.error) {\n if (result.error.isValidationError) {\n const body = result.error.body as {\n errors?: Array<{ input: string; error: string }>;\n message?: string;\n };\n form.setErrors(\n Object.fromEntries(\n (body.errors ?? []).map(({ input, error }) => [input, error]),\n ),\n );\n setSubmitError(body.message ?? \"Please correct the highlighted fields.\");\n } else {\n setSubmitError(\"Your message could not be sent. Please try again.\");\n }\n return;\n }\n\n setSubmitted(true);\n form.reset();\n }}\n >\n <TextInput name=\"name\" label={transX(\"starter.name\")} autoComplete=\"name\" />\n <TextInput\n name=\"email\"\n label={transX(\"starter.email\")}\n type=\"email\"\n autoComplete=\"email\"\n />\n <ContactMessage />\n <button type=\"submit\">{transX(\"starter.submit\")}</button>\n {submitError && (\n <p className=\"wk-submit-error\" role=\"alert\">\n {submitError}\n </p>\n )}\n {submitted && (\n <p className=\"wk-success\" role=\"status\">\n {transX(\"starter.sent\")}\n </p>\n )}\n </Form>\n </section>\n </main>\n </>\n );\n}\n\nfunction ContactMessage() {\n const { error, getErrorProps, getInputProps } = useFormControl({ name: \"message\" });\n\n return (\n <div className=\"wk-field\">\n <label htmlFor=\"message\">{transX(\"starter.message\")}</label>\n <textarea {...getInputProps()} rows={5} />\n {error && <p {...getErrorProps()}>{error}</p>}\n </div>\n );\n}\n`;\n"],"mappings":";;;AAEA,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BhC,MAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B5B,MAAa,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCnC,MAAa,2BAA2B;;AAGxC,MAAa,0BAA0B;;;;;;;;;;;;AAavC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FvC,MAAa,+BAA+B;;AAG5C,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;AAsB3C,MAAa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ClC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;AAkBhC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFvC,MAAa,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCvC,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDrC,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;AAwBzC,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;AAsBxC,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,MAAa,+BAA+B;;;;;;;;;;;;;;;;;AAkB5C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;AAqB/C,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;AAyB/C,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;AAsBlD,MAAa,yCAAyC;;;;;;;;;;;;;;;;AAiBtD,MAAa,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BtC,SAAgB,gCAAwC;CACtD,MAAM,aAAsBA,WAAO,IAAI,iBAAiB;CACxD,MAAM,QACJ,MAAM,QAAQ,UAAU,KAAK,WAAW,SAAS,IAC7C,WAAW,QAAQ,SAAyB,OAAO,SAAS,QAAQ,IACpE,CAAC,IAAI;CACX,OACE,KAAK,UACH,EAAE,UAAU,OAAO,YAAY,MAAM,KAAK,SAAS,CAAC,MAAM,wBAAwB,CAAC,CAAC,EAAE,GACtF,MACA,CACF,IAAI;AAER;AAEA,MAAa,0BAA0B,8BAA8B;;AAGrE,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3C,SAAgB,+BAA+B,QAAyB,MAAsB;CAC5F,MAAM,SAAS,WAAW,QAAQ,YAAY;CAC9C,IAAI;CACJ,IAAI,SAAS,kBACX,gBAAgB;;;;;;;;;;;;;;;;;;;;MAoBX,IAAI,SAAS,+BAClB,gBAAgB;;;;;;;;;;MAUX,IAAI,SAAS,2BAClB,gBAAgB;;;;;;;;;;;;;;;;MAiBhB,gBAAgB;;;;;;;;;;;;;;;CAoBlB,OAAO,wBAAwB,OAAO;;EAHpC,WAAW,UACP,kFACA,GAGM;;YAEF,OAAO,GAAG,KAAK;;6BAEE,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;EAe3C,cAAc,WAAW,YAAY,WAAW,EAAE;;;;AAIpD;;AAGA,MAAa,mBAAmB;;;;;;;;;;;;AAahC,MAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4D3B,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BxC,MAAa,uBAAuB;;;;;;AAOpC,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0ChC,MAAa,kBAAkB"}
@@ -26,7 +26,7 @@ export type HttpErrorMapping = {
26
26
  * (a worker, a CLI, a standalone helper) carry a status without extending
27
27
  * Core's `HttpError`.
28
28
  *
29
- * Called only for errors that are not already an `HttpError`. Return a
29
+ * Called only for errors that are not already an `HttpError` or `AppError`. Return a
30
30
  * mapping (or an `HttpError`) to answer with it, or `undefined` to keep the
31
31
  * default handling (a model validation error keeps its configured status,
32
32
  * anything else is an opaque 500).
@@ -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 };