@warlock.js/core 5.34.3 → 5.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/esm/cli/cli-commands.manager.mjs +1 -1
  3. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  4. package/esm/cli/commands/add.command.mjs +1 -0
  5. package/esm/cli/commands/add.command.mjs.map +1 -1
  6. package/esm/cli/commands/build.command.mjs +30 -3
  7. package/esm/cli/commands/build.command.mjs.map +1 -1
  8. package/esm/cli/commands/check/check-command.action.mjs +1 -0
  9. package/esm/cli/commands/check/check-command.action.mjs.map +1 -1
  10. package/esm/cli/commands/check.command.mjs +5 -0
  11. package/esm/cli/commands/check.command.mjs.map +1 -1
  12. package/esm/cli/commands/explain/explain-command.action.mjs +21 -0
  13. package/esm/cli/commands/explain/explain-command.action.mjs.map +1 -1
  14. package/esm/cli/commands/explain.command.mjs +14 -4
  15. package/esm/cli/commands/explain.command.mjs.map +1 -1
  16. package/esm/cli/commands/generate/generate.command.mjs +19 -1
  17. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  18. package/esm/cli/commands/generate/generators/endpoint.generator.mjs +1 -1
  19. package/esm/cli/commands/generate/generators/endpoint.generator.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generators/web.generator.mjs +169 -0
  21. package/esm/cli/commands/generate/generators/web.generator.mjs.map +1 -0
  22. package/esm/cli/commands/generate/templates/web-stubs.mjs +231 -0
  23. package/esm/cli/commands/generate/templates/web-stubs.mjs.map +1 -0
  24. package/esm/cli/commands/inspect/inspect-command.action.mjs +4 -3
  25. package/esm/cli/commands/inspect/inspect-command.action.mjs.map +1 -1
  26. package/esm/cli/commands/inspect.command.mjs +13 -8
  27. package/esm/cli/commands/inspect.command.mjs.map +1 -1
  28. package/esm/cli/commands/mcp/mcp-command.action.mjs +1 -1
  29. package/esm/cli/commands/mcp/mcp-command.action.mjs.map +1 -1
  30. package/esm/config/config-loader.d.mts.map +1 -1
  31. package/esm/config/config-loader.mjs +2 -0
  32. package/esm/config/config-loader.mjs.map +1 -1
  33. package/esm/config/load-config-files.mjs +4 -0
  34. package/esm/config/load-config-files.mjs.map +1 -1
  35. package/esm/dev-server/file-event-handler.mjs +11 -1
  36. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  37. package/esm/dev-server/file-manager.d.mts +1 -1
  38. package/esm/dev-server/file-manager.d.mts.map +1 -1
  39. package/esm/dev-server/file-manager.mjs.map +1 -1
  40. package/esm/dev-server/files-orchestrator.mjs +16 -1
  41. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  42. package/esm/dev-server/files-watcher.mjs +13 -4
  43. package/esm/dev-server/files-watcher.mjs.map +1 -1
  44. package/esm/dev-server/loader/loader-port-acks.mjs +21 -9
  45. package/esm/dev-server/loader/loader-port-acks.mjs.map +1 -1
  46. package/esm/dev-server/loader/register-loader.mjs +31 -12
  47. package/esm/dev-server/loader/register-loader.mjs.map +1 -1
  48. package/esm/dev-server/module-loader.mjs +14 -0
  49. package/esm/dev-server/module-loader.mjs.map +1 -1
  50. package/esm/dev-server/special-file-patterns.mjs +4 -1
  51. package/esm/dev-server/special-file-patterns.mjs.map +1 -1
  52. package/esm/e2e/index.d.mts +2 -2
  53. package/esm/e2e/page.d.mts +6 -1
  54. package/esm/e2e/page.d.mts.map +1 -1
  55. package/esm/e2e/page.mjs +36 -1
  56. package/esm/e2e/page.mjs.map +1 -1
  57. package/esm/e2e/types.d.mts +31 -0
  58. package/esm/e2e/types.d.mts.map +1 -1
  59. package/esm/e2e/types.mjs.map +1 -1
  60. package/esm/errors/error-codes.d.mts +48 -0
  61. package/esm/errors/error-codes.d.mts.map +1 -1
  62. package/esm/errors/error-codes.mjs +48 -0
  63. package/esm/errors/error-codes.mjs.map +1 -1
  64. package/esm/errors/index.d.mts +2 -2
  65. package/esm/errors/index.mjs +2 -2
  66. package/esm/generations/add-command.action.mjs +2 -0
  67. package/esm/generations/add-command.action.mjs.map +1 -1
  68. package/esm/generations/design-system-payload.mjs +53 -0
  69. package/esm/generations/design-system-payload.mjs.map +1 -0
  70. package/esm/generations/features/design-system.feature.mjs +38 -0
  71. package/esm/generations/features/design-system.feature.mjs.map +1 -0
  72. package/esm/generations/features/index.mjs +3 -1
  73. package/esm/generations/features/index.mjs.map +1 -1
  74. package/esm/generations/features/notifications.feature.mjs +13 -2
  75. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  76. package/esm/generations/features/test.feature.mjs +48 -13
  77. package/esm/generations/features/test.feature.mjs.map +1 -1
  78. package/esm/generations/stubs.mjs +9 -5
  79. package/esm/generations/stubs.mjs.map +1 -1
  80. package/esm/http/error-mapper.d.mts +1 -1
  81. package/esm/http/error-mapper.mjs +3 -3
  82. package/esm/http/error-mapper.mjs.map +1 -1
  83. package/esm/http/error-response.d.mts +3 -0
  84. package/esm/http/error-response.d.mts.map +1 -1
  85. package/esm/http/error-response.mjs +8 -2
  86. package/esm/http/error-response.mjs.map +1 -1
  87. package/esm/http/errors/errors.d.mts +8 -0
  88. package/esm/http/errors/errors.d.mts.map +1 -1
  89. package/esm/http/errors/errors.mjs +13 -1
  90. package/esm/http/errors/errors.mjs.map +1 -1
  91. package/esm/http/index.d.mts +3 -2
  92. package/esm/http/index.mjs +3 -2
  93. package/esm/http/list-endpoint.d.mts +35 -0
  94. package/esm/http/list-endpoint.d.mts.map +1 -0
  95. package/esm/http/list-endpoint.mjs +28 -0
  96. package/esm/http/list-endpoint.mjs.map +1 -0
  97. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  98. package/esm/http/middleware/inject-request-context.mjs +12 -2
  99. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  100. package/esm/http/server.mjs +1 -1
  101. package/esm/index.d.mts +8 -6
  102. package/esm/index.mjs +3 -2
  103. package/esm/openapi/security.mjs +12 -4
  104. package/esm/openapi/security.mjs.map +1 -1
  105. package/esm/openapi/types.d.mts +2 -0
  106. package/esm/openapi/types.d.mts.map +1 -1
  107. package/esm/production/build-budgets.d.mts +46 -0
  108. package/esm/production/build-budgets.d.mts.map +1 -0
  109. package/esm/production/build-budgets.mjs +109 -0
  110. package/esm/production/build-budgets.mjs.map +1 -0
  111. package/esm/production/production-builder.mjs +13 -1
  112. package/esm/production/production-builder.mjs.map +1 -1
  113. package/esm/production/resolve-build-config.d.mts +1 -1
  114. package/esm/production/resolve-build-config.d.mts.map +1 -1
  115. package/esm/production/resolve-build-config.mjs.map +1 -1
  116. package/esm/restful/restful.d.mts +1 -1
  117. package/esm/tests/fakes/storage-fake.d.mts +3 -1
  118. package/esm/tests/fakes/storage-fake.d.mts.map +1 -1
  119. package/esm/tests/fakes/storage-fake.mjs +3 -3
  120. package/esm/tests/fakes/storage-fake.mjs.map +1 -1
  121. package/esm/tests/fakes/test-fakes.d.mts +3 -1
  122. package/esm/tests/fakes/test-fakes.d.mts.map +1 -1
  123. package/esm/tests/fakes/test-fakes.mjs +3 -2
  124. package/esm/tests/fakes/test-fakes.mjs.map +1 -1
  125. package/esm/tests/index.d.mts +4 -2
  126. package/esm/tests/index.mjs +3 -1
  127. package/esm/tests/load-unit-config.mjs +24 -0
  128. package/esm/tests/load-unit-config.mjs.map +1 -0
  129. package/esm/tests/response-contract.d.mts +32 -0
  130. package/esm/tests/response-contract.d.mts.map +1 -0
  131. package/esm/tests/response-contract.mjs +116 -0
  132. package/esm/tests/response-contract.mjs.map +1 -0
  133. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  134. package/esm/tests/start-http-development-server.mjs +10 -2
  135. package/esm/tests/start-http-development-server.mjs.map +1 -1
  136. package/esm/tests/test-lifecycle-state.mjs.map +1 -1
  137. package/esm/tests/test-locales.mjs +33 -0
  138. package/esm/tests/test-locales.mjs.map +1 -0
  139. package/esm/tests/test-runtime-scope.d.mts +15 -0
  140. package/esm/tests/test-runtime-scope.d.mts.map +1 -0
  141. package/esm/tests/test-runtime-scope.mjs +80 -0
  142. package/esm/tests/test-runtime-scope.mjs.map +1 -0
  143. package/esm/tests/vitest-setup.d.mts +13 -3
  144. package/esm/tests/vitest-setup.d.mts.map +1 -1
  145. package/esm/tests/vitest-setup.mjs +146 -18
  146. package/esm/tests/vitest-setup.mjs.map +1 -1
  147. package/esm/tooling/check/affected-files.d.mts +5 -0
  148. package/esm/tooling/check/affected-files.d.mts.map +1 -0
  149. package/esm/tooling/check/affected-files.mjs +56 -0
  150. package/esm/tooling/check/affected-files.mjs.map +1 -0
  151. package/esm/tooling/check/changed-files.d.mts +2 -0
  152. package/esm/tooling/check/changed-files.d.mts.map +1 -1
  153. package/esm/tooling/check/changed-files.mjs +2 -2
  154. package/esm/tooling/check/changed-files.mjs.map +1 -1
  155. package/esm/tooling/check/conventions-step.d.mts +2 -1
  156. package/esm/tooling/check/conventions-step.d.mts.map +1 -1
  157. package/esm/tooling/check/conventions-step.mjs +48 -6
  158. package/esm/tooling/check/conventions-step.mjs.map +1 -1
  159. package/esm/tooling/check/fixes.d.mts +8 -0
  160. package/esm/tooling/check/fixes.d.mts.map +1 -0
  161. package/esm/tooling/check/fixes.mjs +31 -0
  162. package/esm/tooling/check/fixes.mjs.map +1 -0
  163. package/esm/tooling/check/index.d.mts +12 -0
  164. package/esm/tooling/check/index.mjs +3 -2
  165. package/esm/tooling/check/run-check.d.mts +2 -0
  166. package/esm/tooling/check/run-check.d.mts.map +1 -1
  167. package/esm/tooling/check/run-check.mjs +20 -4
  168. package/esm/tooling/check/run-check.mjs.map +1 -1
  169. package/esm/tooling/check/run-tests.mjs +1 -1
  170. package/esm/tooling/check/source-ast.d.mts +1 -0
  171. package/esm/tooling/check/web-conventions.d.mts +10 -0
  172. package/esm/tooling/check/web-conventions.d.mts.map +1 -0
  173. package/esm/tooling/check/web-conventions.mjs +126 -0
  174. package/esm/tooling/check/web-conventions.mjs.map +1 -0
  175. package/esm/tooling/index.d.mts +7 -2
  176. package/esm/tooling/index.mjs +4 -2
  177. package/esm/tooling/inspect/collect-files.mjs +172 -0
  178. package/esm/tooling/inspect/collect-files.mjs.map +1 -0
  179. package/esm/tooling/inspect/collect-pages.mjs +3 -2
  180. package/esm/tooling/inspect/collect-pages.mjs.map +1 -1
  181. package/esm/tooling/inspect/collect-routes.mjs +1 -1
  182. package/esm/tooling/inspect/collect-routes.mjs.map +1 -1
  183. package/esm/tooling/inspect/explain-file.d.mts +12 -0
  184. package/esm/tooling/inspect/explain-file.d.mts.map +1 -0
  185. package/esm/tooling/inspect/explain-file.mjs +45 -0
  186. package/esm/tooling/inspect/explain-file.mjs.map +1 -0
  187. package/esm/tooling/inspect/index.d.mts +3 -2
  188. package/esm/tooling/inspect/index.mjs +2 -1
  189. package/esm/tooling/inspect/inspect-app.d.mts.map +1 -1
  190. package/esm/tooling/inspect/inspect-app.mjs +9 -3
  191. package/esm/tooling/inspect/inspect-app.mjs.map +1 -1
  192. package/esm/tooling/inspect/inspect-report.schema.mjs +34 -1
  193. package/esm/tooling/inspect/inspect-report.schema.mjs.map +1 -1
  194. package/esm/tooling/inspect/inspect-report.types.d.mts +17 -1
  195. package/esm/tooling/inspect/inspect-report.types.d.mts.map +1 -1
  196. package/esm/tooling/inspect/inspect-report.types.mjs +2 -1
  197. package/esm/tooling/inspect/inspect-report.types.mjs.map +1 -1
  198. package/esm/tooling/mcp/mcp-tools.d.mts.map +1 -1
  199. package/esm/tooling/mcp/mcp-tools.mjs +8 -2
  200. package/esm/tooling/mcp/mcp-tools.mjs.map +1 -1
  201. package/esm/tooling/problem.d.mts +4 -0
  202. package/esm/tooling/problem.d.mts.map +1 -1
  203. package/esm/tooling/problem.mjs +1 -0
  204. package/esm/tooling/problem.mjs.map +1 -1
  205. package/esm/tooling/syntax/ast.d.mts +2 -0
  206. package/esm/tooling/typecheck/run-typecheck.mjs +5 -1
  207. package/esm/tooling/typecheck/run-typecheck.mjs.map +1 -1
  208. package/esm/vite/index.d.mts +3 -1
  209. package/esm/vite/index.mjs +3 -1
  210. package/esm/vite/test-setup-reporter.d.mts +16 -0
  211. package/esm/vite/test-setup-reporter.d.mts.map +1 -0
  212. package/esm/vite/test-setup-reporter.mjs +55 -0
  213. package/esm/vite/test-setup-reporter.mjs.map +1 -0
  214. package/esm/vite/test-workers.d.mts +5 -0
  215. package/esm/vite/test-workers.d.mts.map +1 -0
  216. package/esm/vite/test-workers.mjs +38 -0
  217. package/esm/vite/test-workers.mjs.map +1 -0
  218. package/esm/warlock-config/index.d.mts +2 -1
  219. package/esm/warlock-config/types.d.mts +3 -0
  220. package/esm/warlock-config/types.d.mts.map +1 -1
  221. package/llms-full.txt +763 -9
  222. package/llms.txt +2 -0
  223. package/package.json +15 -14
  224. package/schemas/inspect-report.schema.json +47 -1
  225. package/skills/build-budgets/SKILL.md +51 -0
  226. package/skills/build-restful/SKILL.md +56 -0
  227. package/skills/configure-app/SKILL.md +7 -0
  228. package/skills/create-module/SKILL.md +9 -0
  229. package/skills/generate-web-ui/SKILL.md +71 -0
  230. package/skills/index.md +2 -2
  231. package/skills/run-app/SKILL.md +1 -1
  232. package/skills/send-mail/SKILL.md +25 -0
  233. package/skills/send-response/SKILL.md +50 -0
  234. package/skills/test-browser/SKILL.md +53 -0
  235. package/skills/test-http/SKILL.md +91 -0
  236. package/skills/test-service/SKILL.md +161 -3
  237. package/skills/upgrade-from-5-29/SKILL.md +18 -0
  238. package/skills/use-localization/SKILL.md +21 -0
  239. package/skills/warlock-check/SKILL.md +72 -1
  240. package/skills/warlock-inspect/SKILL.md +45 -2
  241. package/skills/warlock-mcp/SKILL.md +4 -0
  242. package/skills/write-cli-command/SKILL.md +18 -0
  243. package/esm/production/build-app-production.mjs +0 -14
  244. package/esm/production/build-app-production.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../../packages/core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n getJsonFileAsync,\n putFileAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport esbuild from \"esbuild\";\nimport glob from \"fast-glob\";\nimport path from \"path\";\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\nimport { configKeyFromPath } from \"../config/config-key-from-path\";\nimport {\n isConfigFile,\n isEventFile,\n isLocaleFile,\n isMainFile,\n isRouteFile,\n isWorkerFile,\n} from \"../dev-server/special-file-patterns\";\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\nimport { appPath, rootPath, warlockPath } from \"../utils\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\nimport { collectRouteRegistrationSnapshot } from \"./route-registration-snapshot\";\nimport { clearOwnedRouteTypes } from \"../dev-server/route-types-publisher\";\nimport {\n commitDistAsync,\n createTempOutputDir,\n rollbackDistAsync,\n stageDistAsync,\n type StagedDist,\n} from \"./promote-dist\";\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\n\n/**\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\n *\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\n * esbuild substitutes a stub that throws — **after the build has reported\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\n * firing, and it is the defect this shim removes.\n *\n * `__dirname` matters as much as `require`: without it a dependency resolving\n * an asset path silently gets `undefined` and fails later, further from the\n * cause.\n *\n * Written as one line because esbuild inserts a banner verbatim above the\n * bundle and a multi-line string here would shift every mapped line.\n */\nconst ESM_INTEROP_SHIM =\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\n \"import{dirname as __wlDirname}from'node:path';\" +\n \"const require=__wlCreateRequire(import.meta.url);\" +\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\n \"const __dirname=__wlDirname(__filename);\";\n\n/**\n * Combine the framework's banner with the user's, keeping both.\n *\n * esbuild's `banner` is an object keyed by output type, and every merge in the\n * path to it — the config merge and the options spread — REPLACES that object\n * rather than merging it. So whichever is applied second silently deletes the\n * other. This is the only place the two can coexist.\n *\n * The shim goes first: it defines `require`, which a user banner may use.\n *\n * @param userBanner banner from `warlock.config.ts`, if any\n * @param shim the interop shim, or undefined when it does not apply\n */\nfunction mergeBanner(\n userBanner: Record<string, string> | undefined,\n shim: string | undefined,\n): Record<string, string> | undefined {\n if (!shim) return userBanner;\n\n const userJs = userBanner?.js;\n\n return {\n ...userBanner,\n js: userJs ? `${shim}${userJs}` : shim,\n };\n}\n\n/**\n * Prefix every generated file uses to reach the app root.\n *\n * Generated sources are written into `.warlock/production/`, two levels below\n * the app root, so `../../` lands back on it — the same hop already spelled\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\n * config-loader generators emit. Named once so a generator that needs a new\n * app-root file (`warlock.config`) cannot pick a different depth.\n */\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\n\n/**\n * Production Builder\n * Generates production-ready files and bundles them for deployment\n * Build options are loaded from warlock.config.ts\n */\nexport class ProductionBuilder {\n private options!: ResolvedBuildConfig;\n private readonly productionDir = warlockPath(\"production\");\n\n /**\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\n * never calls `boot()`/`start()` on them; it only\n * drains their `build` contributions.\n */\n private connectors: readonly Connector[] = [];\n\n /**\n * The contributors' merged esbuild patch, produced by the `generate` pass\n * and consumed by {@link bundle}.\n */\n private contributedEsbuild: ConnectorEsbuildPatch = {};\n\n /** Browser-safe API metadata captured in a fresh registration-only child. */\n private namedApiRoutes?: readonly import(\"../router/types\").NamedApiRoute[];\n\n /**\n * Main build entry point\n *\n * The esbuild bundle is written into a TEMP directory next to the real\n * output directory, never into it, and that directory is renamed over\n * `outdir` as one filesystem operation — so `outdir` is never observed as\n * a mix of the old build and the new one, and a build that fails before\n * that rename never touches `outdir` at all.\n *\n * `this.options.outdir` is NOT repointed at the temp directory while that\n * happens, and must never be. It is not merely a write target: consumers\n * BAKE it into runtime output — `web`'s build contribution derives the\n * `clientDir` recorded in its pages manifest from it\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\n * produces an artifact whose browser paths point at a directory promotion\n * has since renamed away. The temp path is passed explicitly, as a\n * parameter, to the one operation that writes into it ({@link bundle});\n * everything else, `buildContext()` included, keeps reading the final\n * destination.\n *\n * That is also why promotion is STAGED rather than done at the very end.\n * Connector `emit` hooks write real artifacts (the web client bundle) and\n * see the final `outdir`, so they must run when `outdir` genuinely holds\n * this build — after the rename, not before it, or promotion would replace\n * the directory they just wrote into. The previous build is kept parked\n * aside until they finish: `emit` throwing rolls the whole promotion back,\n * and the build-success marker `warlock start` checks is written last of\n * all, so a failure at any point leaves no `dist` that start will boot.\n */\n public async build(): Promise<void> {\n console.log(colors.cyan(\"Building for production...\\n\"));\n\n // Step 0: Fail fast when esbuild's native binary never got linked (the\n // state pnpm leaves a project in when its build-script approval gate\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\n // own cryptic \"package could not be found\" error several steps from now.\n assertEsbuildBinaryIsLinked();\n\n // Step 1: Initialize options from config\n await this.initializeOptions();\n\n const finalOutDir = this.options.outdir!;\n const tempOutDir = createTempOutputDir(finalOutDir);\n\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\n // presence is what tells the catch below whether a failure has a\n // promotion to undo or only a temp directory to discard.\n let staged: StagedDist | undefined;\n\n try {\n // Step 2: Generate combined files\n await this.generateCombinedFiles();\n\n // Step 3: Generate entry point\n await this.generateEntryPoint();\n\n // Step 4: Refuse to bundle code the app could not resolve at runtime\n await this.assertGeneratedImports();\n\n // Step 4.5: Drain the connectors' `generate` contributions\n await this.captureNamedApiRoutesForWeb();\n const contributed = await this.runGenerateContributions();\n\n // Step 4.6: Re-assert over what the contributors just wrote.\n //\n // Step 4 only saw core's own generated files; a contributor writes its\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\n // specifier in it reaches the bundle unchecked. Under\n // `packages: \"external\"` that specifier survives verbatim into the\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\n // and re-reading the production dir is pure cost in the common case.\n if (contributed) {\n await this.assertGeneratedImports();\n }\n\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\n // operation handed that path — it is a write target, not config.\n await this.bundle(tempOutDir);\n\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\n // build parked aside. `outdir` now holds exactly this build, so the\n // steps below write into — and record — the real destination.\n staged = await stageDistAsync(tempOutDir, finalOutDir);\n\n // Step 5.6: Drain the connectors' `emit` contributions — after the\n // bundle is in place (so what they write survives promotion and the\n // paths they bake in resolve), and BEFORE step 6 deletes the\n // production directory they may still read.\n await runEmitContributions(this.connectors, this.buildContext());\n\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\n // `warlock start` trusts. Written LAST on purpose: every earlier step\n // can still fail, and until this file exists nothing will boot what\n // they left behind.\n await writeDistBuildManifestAsync(finalOutDir);\n\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\n await commitDistAsync(staged);\n } catch (error) {\n if (staged) {\n // The promotion already happened; put the previous build back and\n // take this half-finished one out of `outdir`.\n await rollbackDistAsync(staged);\n } else {\n // Nothing this build produced ever reached `outdir` — discard the\n // temp directory and leave `outdir` exactly as it was.\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\n }\n\n throw error;\n }\n\n // Step 6: Remove production folder\n await removeDirectoryAsync(this.productionDir);\n\n console.log(colors.green(\"Build complete!\"));\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\n }\n\n /**\n * Initialize options from warlock.config.ts\n */\n private async initializeOptions(): Promise<void> {\n this.options = resolveBuildConfig();\n // Same config object `resolveBuildConfig` just read — `warlock build`\n // preloads warlock.config.ts, so no additional load happens here.\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\n\n // Checked here, where the array is first read, so nothing downstream has\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\n // a name listed twice would write its files and merge its esbuild options\n // twice into an artifact the runtime then boots that name only once from.\n // A build that half-applied a connector and reported success is worse than\n // one that never started.\n assertUniqueConnectorNames([...connectors]);\n\n // And here rather than only at boot, for the same reason: a name a built-in\n // already owns is skipped by the runtime, so an artifact built from it\n // carries the custom connector's generated files and esbuild patches while\n // the server boots the built-in instead. Refusing it at boot alone would\n // mean the build had already emitted that artifact — the failure has to\n // land on the developer running `warlock build`, not on whoever starts the\n // server. Same assertion the registration half calls, over the same names.\n assertNoReservedConnectorNames([...connectors]);\n\n this.connectors = connectors;\n\n // Ensure production directory exists\n await ensureDirectoryAsync(this.productionDir);\n }\n\n /**\n * The context handed to every build contribution.\n */\n private buildContext(): ConnectorBuildContext {\n return {\n productionDir: this.productionDir,\n appRoot: rootPath(),\n options: this.options,\n namedApiRoutes: this.namedApiRoutes,\n };\n }\n\n /**\n * Web route declarations need application API registration, which cannot be\n * inferred from generated files. Capture it once in a disposable child before\n * contributors write build artifacts; no connector lifecycle runs there.\n */\n private async captureNamedApiRoutesForWeb(): Promise<void> {\n if (!this.connectors.some((connector) => connector.name === \"web\")) {\n await clearOwnedRouteTypes(rootPath());\n return;\n }\n\n this.namedApiRoutes = (\n await collectRouteRegistrationSnapshot({\n cwd: rootPath(),\n timeoutMs: this.options.routeRegistrationTimeoutMs,\n })\n ).routes;\n }\n\n /**\n * Drain the `generate` hooks and fold what they returned back into the\n * build.\n *\n * The entry point is REGENERATED here rather than generated later. The\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\n * bundles that the app could not resolve) and before `bundle` — while\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\n * generated code the assertion has to see; moving it past the assertion\n * would silently drop the entry from that check. Rewriting one small file\n * is cheaper than losing either guarantee, and the write is pure\n * (`generatedFiles` + these imports), so doing it twice is not a\n * correctness risk.\n *\n * @returns whether any connector ran a `generate` hook — the caller uses it\n * to decide if the import assertion is worth a second pass. Keyed on the\n * hook EXISTING, not on what it returned: a hook that returns nothing may\n * still have written files into `productionDir`, and those are exactly the\n * files the second pass is there to read.\n */\n private async runGenerateContributions(): Promise<boolean> {\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\n\n const { entryImports, esbuild } = await runGenerateContributions(\n this.connectors,\n this.buildContext(),\n );\n\n this.contributedEsbuild = esbuild;\n\n if (entryImports.length > 0) {\n await this.generateEntryPoint(entryImports);\n }\n\n return contributed;\n }\n\n /**\n * Track which special files were generated\n */\n private generatedFiles = {\n locales: false,\n events: false,\n main: false,\n routes: false,\n workers: false,\n };\n\n /**\n * Generate all combined files\n */\n private async generateCombinedFiles(): Promise<void> {\n console.log(colors.yellow(\" Generating production files...\"));\n\n // Generate bootstrap.ts file\n await this.generateBootstrap();\n\n // Generate config loader\n await this.generateConfigLoader();\n\n // Generate special files and track which ones have content\n const [locales, events, main, routes, workers] = await Promise.all([\n this.generateLocales(),\n this.generateEvents(),\n this.generateMain(),\n this.generateRoutes(),\n this.generateWorkers(),\n ]);\n\n this.generatedFiles = { locales, events, main, routes, workers };\n }\n\n /**\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\n */\n private async generateBootstrap(): Promise<void> {\n // ESM hoists imports, so the app bootstrap must be the first import to run first\n const appBootstrapImport = (await fileExistsAsync(appPath(\"bootstrap.ts\")))\n ? \"import './../../src/app/bootstrap';\\n\"\n : \"\";\n\n const content = `${appBootstrapImport}import { bootstrap, Application } from \"@warlock.js/core\";\n\n// Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins\nApplication.setRuntimeStrategy(\"production\");\nif (!process.env.NODE_ENV) {\n Application.setEnvironment(\"production\");\n}\n\n// Bootstrap the application\nbootstrap();\n`;\n\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\n }\n\n /**\n * Fail the build when generated code imports a package the app does not\n * declare.\n *\n * The bundler is configured `packages: \"external\"`, so every bare specifier\n * written above survives verbatim into an artifact that resolves against the\n * **consuming app's** node_modules. A framework-internal dependency imported\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\n * which is how a production app shipped that could not boot. Rewriting the\n * offending import fixes today's bundle; this check is what stops the next\n * change to the generator from quietly reintroducing it.\n */\n private async assertGeneratedImports(): Promise<void> {\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\n cwd: this.productionDir,\n absolute: false,\n });\n\n const [files, appPackage] = await Promise.all([\n Promise.all(\n generatedPaths.map(async (file) => ({\n file,\n content: await getFileAsync(path.join(this.productionDir, file)),\n })),\n ),\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\n ]);\n\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\n }\n\n /**\n * Glob `src/app` and keep the files the shared dev-server predicate accepts,\n * so production discovers exactly what the dev collector does.\n * Returns relative paths from .warlock/production/ to src/app/\n */\n private async globModule(matches: (relativePath: string) => boolean): Promise<string[]> {\n const files = await glob(\"**/*.{ts,tsx,json}\", {\n cwd: appPath(),\n absolute: false,\n });\n\n // e.g., \"users/main.ts\" -> \"../../src/app/users/main\"\n return files\n .filter((file) => matches(\"src/app/\" + file))\n .sort()\n .map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\n }\n\n /**\n * Generate config-loader.ts\n */\n private async generateConfigLoader(): Promise<void> {\n const configDirectory = path.join(process.cwd(), \"src/config\");\n\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: configDirectory,\n absolute: false,\n });\n\n // Same key rule as the dev config loader: the raw path, never camel-cased\n const configNames = files\n .filter((f) => isConfigFile(\"src/config/\" + f))\n .map((f) => ({\n path: f.replace(/\\.(ts|tsx)$/, \"\"),\n key: configKeyFromPath(\"src/config/\" + f),\n }))\n .filter((entry): entry is { path: string; key: string } => entry.key !== undefined)\n .sort((a, b) => a.path.localeCompare(b.path));\n\n // Only `@warlock.js/core` — the one package the app itself declares. See\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\n // dependency, so a bare import of it resolved by luck under npm/yarn\n // hoisting and died under pnpm's strict layout.\n const imports: string[] = [\n 'import { assertValidConfigModules, configSpecialHandlers, setConfig } from \"@warlock.js/core\";',\n ];\n const configImports: string[] = [];\n const configSetCalls: string[] = [];\n const validations: string[] = [];\n const executors: string[] = [];\n\n configNames.forEach(({ path: configPath, key }, index) => {\n // Index-based identifier: keys like \"rate-limit\" or \"mail/smtp\" are not valid names.\n // A namespace import, so a file's optional `configSchema` export travels with it.\n const varName = `config${index}`;\n const name = JSON.stringify(key);\n configImports.push(`import * as ${varName} from \"../../src/config/${configPath}\";`);\n configSetCalls.push(`setConfig(${name}, ${varName}.default);`);\n validations.push(` { name: ${name}, module: ${varName} },`);\n executors.push(`await configSpecialHandlers.execute(${name}, ${varName}.default);`);\n });\n\n // ESM hoists imports, so prestart must be the first import to run first\n const prestartImports = (await fileExistsAsync(appPath(\"prestart.ts\")))\n ? [\"import './../../src/app/prestart';\"]\n : [];\n\n const content = [\n ...prestartImports,\n ...imports,\n \"\",\n \"// Config imports\",\n ...configImports,\n \"\",\n \"// Register configs\",\n ...configSetCalls,\n \"\",\n \"// Refuse to start when a config file's `configSchema` is not satisfied\",\n \"await assertValidConfigModules([\",\n ...validations,\n \"]);\",\n \"\",\n \"// Special handlers\",\n ...executors,\n \"\",\n ].join(\"\\n\");\n\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\n }\n\n /**\n * Generate locales.ts (only if there are locale files)\n * @returns true if file was generated with content\n */\n private async generateLocales(): Promise<boolean> {\n const files = await this.globModule(isLocaleFile);\n if (files.length === 0) return false;\n const content = files\n .map((file, index) => {\n if (!file.endsWith(\".json\")) return `import \"${file}\";`;\n const moduleFolder = file.split(\"/\").at(-3)!;\n return [\n `import dictionary${index} from \"${file}\";`,\n 'import { registerLocaleDictionary } from \"@warlock.js/core\";',\n `registerLocaleDictionary({ sourceFile: ${JSON.stringify(file)}, source: JSON.stringify(dictionary${index}), defaultNamespace: ${JSON.stringify(moduleFolder)} });`,\n ].join(\"\\n\");\n })\n .join(\"\\n\");\n await putFileAsync(path.join(this.productionDir, \"locales.ts\"), content + \"\\n\");\n return true;\n }\n\n /**\n * Generate events.ts (only if there are event files)\n * @returns true if file was generated with content\n */\n private async generateEvents(): Promise<boolean> {\n const files = await this.globModule(isEventFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"events.ts\");\n return true;\n }\n\n /**\n * Generate main.ts (only if there are main files)\n * @returns true if file was generated with content\n */\n private async generateMain(): Promise<boolean> {\n const files = await this.globModule(isMainFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"main.ts\");\n return true;\n }\n\n /**\n * Generate routes.ts (only if there are route files)\n * @returns true if file was generated with content\n */\n private async generateRoutes(): Promise<boolean> {\n const files = await this.globModule(isRouteFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"routes.ts\");\n return true;\n }\n\n /**\n * Generate workers.ts (only if there are worker files)\n * @returns true if file was generated with content\n */\n private async generateWorkers(): Promise<boolean> {\n const files = await this.globModule(isWorkerFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"workers.ts\");\n return true;\n }\n\n /**\n * Generate a file with imports from all given files\n */\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, outputFile), content);\n }\n\n /**\n * Generate the main entry point (app.ts)\n *\n * @param contributedImports lines from connector `generate` hooks, appended\n * to section 4 after `./routes`\n */\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\n console.log(colors.yellow(\" Generating entry point...\"));\n\n // The names this build resolved, baked in as a literal. The entry imports\n // the config source, and that source is re-evaluated at startup — an\n // env-conditional `connectors` array can hand the boot a different list\n // than the one drained here. A literal is the only part of the array that\n // survives into the artifact unchanged, so it is what the boot compares\n // against.\n const expectedNames = this.connectors\n .map((connector) => JSON.stringify(connector.name))\n .join(\", \");\n\n // Build imports based on which files were generated\n const imports: string[] = [\n \"// 1. Bootstrap (loads .env, initializes framework)\",\n 'import \"./bootstrap\";',\n \"\",\n \"// 2. Load configs\",\n 'import \"./config-loader\";',\n \"\",\n // Registration has to sit between the config being available and the\n // first phase starting: the connectors listed in `connectors` are the\n // same ones this build drained contributions from, so the bundle boots\n // exactly what it was built for. Register any later and an early-phase\n // connector would miss its own start.\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\n \"// build read its contributions from, so built-for and boots-with match).\",\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\n \"// and the array is handed over explicitly — an artifact has no\",\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\n \"// that quietly found nothing to register is the exact drift this\",\n \"// section exists to prevent.\",\n \"// `expectedNames` is the list this build resolved, in order — boot\",\n \"// refuses to start when the config hands over a different set or order.\",\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\n \"\",\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\n \"// own preflight is not reached until the database and cache have\",\n \"// connected and every app module has been imported — seconds of work\",\n \"// thrown away before anyone learns the port was taken. This probe is\",\n \"// a bind-and-release on a socket that is never served, and it reports\",\n \"// on stderr because no log channel is configured this early.\",\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\n 'if (Application.hasRole(\"api\") || Application.hasRole(\"web\")) {',\n \" await preflightConfiguredHttpPort();\",\n \"}\",\n \"\",\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\n \"// so data sources, cache, etc. are ready before app code runs\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\n ];\n\n // App code uses dynamic `await import(...)` so each module's side\n // effects fire at THIS point in execution. Static imports would be\n // hoisted to module-instantiation time (before the early-phase await\n // resolves), which is exactly the bug this split is meant to fix.\n //\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\n // it at the await, not at instantiation. It does NOT come from\n // `splitting: true`, which only decides one-file-vs-chunks. This\n // previously said splitting was required; it is not, and `singleBundle`\n // (splitting: false) preserves the ordering.\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\n\n if (this.generatedFiles.events) {\n imports.push('await import(\"./events\");');\n }\n if (this.generatedFiles.locales) {\n imports.push('await import(\"./locales\");');\n }\n if (this.generatedFiles.main) {\n imports.push('await import(\"./main\");');\n }\n if (this.generatedFiles.routes) {\n imports.push('if (Application.hasRole(\"api\")) {', ' await import(\"./routes\");', \"}\");\n }\n if (this.generatedFiles.workers) {\n imports.push('if (Application.hasRole(\"worker\")) {', ' await import(\"./workers\");', \"}\");\n }\n\n // Contributor imports come AFTER `./routes`, never before: a connector\n // that registers pages needs the routes app code already collected —\n // the same ordering dev uses (routes first, then the connector installs\n // on top of them). Emitted verbatim; the contributor writes the whole\n // statement (e.g. `await import(\"./pages\");`).\n imports.push(...contributedImports);\n\n // A rejecting validator (Application.onValidateBoot) must abort boot\n // before late-phase connectors bind a port.\n imports.push(\n \"\",\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\n \"await Application.runStartupValidators();\",\n );\n\n // Start late-phase connectors after app code registers routes/listeners\n imports.push(\n \"\",\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\n \"// listeners registered by app code are now ready to bind\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\n \"\",\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\n \"connectorsManager.shutdownOnProcessKill();\",\n );\n\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\n }\n\n /**\n * Bundle with esbuild\n *\n * @param writeOutDir the directory esbuild writes into — the build's\n * private temp directory, NOT `options.outdir`. Taken as a parameter\n * rather than read off `this.options` because the two are different paths\n * with different meanings: `options.outdir` is the final destination every\n * consumer bakes into the artifact, and this is only where bytes land\n * before promotion moves them there.\n */\n private async bundle(writeOutDir: string): Promise<void> {\n console.log(colors.magenta(\" Bundling with esbuild...\"));\n\n const entryPoint = path.join(this.productionDir, \"app.ts\");\n const outFileName = this.options.outFile!;\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\n const entryName = path.basename(outFileName, path.extname(outFileName));\n\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\n // unknown keys, and the user options are spread into its call verbatim.\n const singleBundle = this.options.singleBundle === true;\n const esmShim = this.options.esmShim !== false;\n // Read before deleting: the merged banner is applied AFTER the user\n // spread, so a user banner must not be lost to it or clobber the shim.\n const userBanner = this.options.banner;\n\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\n // resolve-build-config.ts documents that widening them pushed a lie downstream\n // into start-production.command.ts, which then could not trust its own config.\n // This is the one place they must be absent - the object is spread into esbuild's\n // call verbatim and esbuild throws on unknown keys.\n //\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\n // contribution hook, including the `emit` pass that runs AFTER this method\n // returns (`build()` step 5.6). Deleting these keys from the shared object\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\n // types them as present. A shallow copy is enough — every field this method\n // reads off it is either scalar or already re-merged below (`define`,\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\n\n delete esbuildOptions.outFile;\n delete esbuildOptions.entryPath;\n delete esbuildOptions.singleBundle;\n delete esbuildOptions.esmShim;\n delete esbuildOptions.banner;\n delete esbuildOptions.routeRegistrationTimeoutMs;\n\n await ensureDirectoryAsync(writeOutDir);\n\n const alias = this.buildAliasMapFromTsconfig();\n\n // Whether this build decides externality per import EDGE\n // (`bundle-framework-dependencies.ts`, which explains the rule at\n // length) or keeps the blunt `packages: \"external\"`.\n //\n // Not in `singleBundle` mode: that bundles everything by definition, and\n // a plugin that can only ever ADD an external would silently narrow it.\n // Not when the user set `packages` themselves: their value has always\n // won over the default below, and it must keep winning — the plugin is\n // the default's implementation, not a new policy layered on top.\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\n\n // The user can override `format`, so gate the shim on the EFFECTIVE\n // format rather than on the default below. A CJS build already has\n // `require` and friends; injecting them there would be a redefinition.\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\n\n // Contributor patch, split into the part that can ride the spread order\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\n // BEFORE the user spread below, which gives the ruled precedence for\n // free: builder defaults < contributor < user config.\n //\n // `define`, `external` and `loader` are pulled out because a spread\n // REPLACES them wholesale — the same trap `banner` documents. Two\n // contributors' env defines, a contributor's optional peers plus the\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\n // must both survive, so they are merged by key/by set and re-applied\n // after the spread with the user still winning per key.\n const {\n define: contributedDefine,\n external: contributedExternal,\n loader: contributedLoader,\n plugins: contributedPlugins,\n ...contributedOptions\n } = this.contributedEsbuild;\n\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\n const userExternal: string[] | undefined = esbuildOptions.external;\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\n\n const define =\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\n\n const loader =\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\n\n const external =\n contributedExternal || userExternal\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\n : undefined;\n\n if (singleBundle) {\n console.log(\n colors.magenta(\n \" Single-bundle mode — one JS file\" +\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\n \". Native .node addons are still emitted alongside it.\",\n ),\n );\n }\n\n try {\n await esbuild.build({\n platform: \"node\",\n entryPoints: [entryPoint],\n bundle: true,\n // Both are DEFAULTS the user can override — they sit before the\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\n //\n // Phase ordering does not depend on `splitting`: it comes from the\n // generated app.ts using dynamic `await import(...)` (see\n // generateAppEntry above), which esbuild defers to the call site in\n // either mode. Splitting only decides one file vs chunks.\n splitting: !singleBundle,\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\n // the plugin below returns `external: true` for every bare specifier\n // this build must not bundle, which is all of them bar the framework's\n // own declared dependencies. Saying `\"external\"` here instead would\n // externalise them before the plugin could rule.\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\n minify: esbuildOptions.minify,\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\n format: \"esm\",\n // Targeting a concrete Node version (not \"esnext\") so esbuild\n // transpiles TC39 stage 3 decorators into helpers — Node does not\n // implement them natively yet.\n target: [\"node22\"],\n entryNames: entryName,\n alias,\n plugins: [\n nativeNodeModulesPlugin,\n // BEFORE the framework-dependency plugin, and the order is\n // load-bearing: the first `onResolve` callback to answer wins, and\n // `app/users/...` is a bare specifier the other one would rule\n // external.\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\n ...(perEdgeExternals\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\n : []),\n // Contributor plugins run last: they load their own file types and\n // must not shadow the resolvers above.\n ...(contributedPlugins ?? []),\n ],\n // Between the defaults and the user spread — the ruled precedence.\n ...contributedOptions,\n ...(esbuildOptions as any),\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\n // that spread carrying the FINAL destination, which is exactly where\n // this build must not write yet. The final path is the user's setting\n // and stays authoritative for everyone reading the config — it is only\n // this one esbuild call that is redirected, and only until promotion\n // moves the result onto that very path.\n outdir: writeOutDir,\n // AFTER the spread for the same reason `banner` is: a spread replaces\n // these objects instead of merging them, so the merged values are\n // re-applied here. The user still wins — they were merged in last.\n ...(define ? { define } : {}),\n ...(external ? { external } : {}),\n ...(loader ? { loader } : {}),\n // AFTER the spread, and intentionally so: `banner` is an object, and\n // both the config merge and this spread REPLACE it wholesale rather\n // than merging. Left as a default above, any user banner would delete\n // the shim; left to the spread, the shim would delete theirs. The\n // merge is the only form that keeps both.\n ...(banner ? { banner } : {}),\n });\n } catch (e) {\n console.log(e);\n throw e;\n }\n }\n\n /**\n * The WILDCARD half of the same tsconfig `paths` map that\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\n * so the entries it skips have to be resolved by a plugin instead of being\n * left to no one.\n */\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\n tsconfigManager.init();\n\n return {\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\n paths: tsconfigManager.aliases as Record<string, string[]>,\n };\n }\n\n /**\n * Build an alias map from tsconfig `paths` so esbuild resolves local\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\n * folders during bundling. Without this, `packages: \"external\"` would\n * leave those bare specifiers as raw imports and Node would fail to\n * resolve them at runtime (they aren't installed in node_modules).\n *\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\n * option doesn't support glob-style mappings. The wildcard half is not\n * dropped, it is handled elsewhere: see\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\n */\n private buildAliasMapFromTsconfig(): Record<string, string> {\n tsconfigManager.init();\n\n const alias: Record<string, string> = {};\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\n\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\n continue;\n }\n\n const target = to[0];\n\n if (target === undefined) {\n continue;\n }\n\n alias[from] = path.resolve(baseUrl, target);\n }\n\n return alias;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;;;;;AAWA,MAAM,+BAA+B;;;;;;AAOrC,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;oBAOd,CAAC;4BAMQ,CAAC;wBAoO5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;GACR,SAAS;EACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAxMA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAMvD,4BAA4B;EAG5B,MAAM,KAAK,kBAAkB;EAE7B,MAAM,cAAc,KAAK,QAAQ;EACjC,MAAM,aAAa,oBAAoB,WAAW;EAKlD,IAAI;EAEJ,IAAI;GAEF,MAAM,KAAK,sBAAsB;GAGjC,MAAM,KAAK,mBAAmB;GAG9B,MAAM,KAAK,uBAAuB;GAGlC,M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AI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../../packages/core/src/production/production-builder.ts"],"sourcesContent":["import {\n evaluateBuildBudgets,\n readBuildBudgetReport,\n writeBuildBudgetReport,\n formatBuildBudgets,\n formatBudgetViolations,\n type BuildBudgetReport,\n} from \"./build-budgets\";\nimport { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n getJsonFileAsync,\n putFileAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport esbuild from \"esbuild\";\nimport glob from \"fast-glob\";\nimport path from \"path\";\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\nimport { configKeyFromPath } from \"../config/config-key-from-path\";\nimport {\n isConfigFile,\n isEventFile,\n isLocaleFile,\n isMainFile,\n isRouteFile,\n isWorkerFile,\n} from \"../dev-server/special-file-patterns\";\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\nimport { appPath, rootPath, warlockPath } from \"../utils\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\nimport { collectRouteRegistrationSnapshot } from \"./route-registration-snapshot\";\nimport { clearOwnedRouteTypes } from \"../dev-server/route-types-publisher\";\nimport {\n commitDistAsync,\n createTempOutputDir,\n rollbackDistAsync,\n stageDistAsync,\n type StagedDist,\n} from \"./promote-dist\";\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\n\n/**\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\n *\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\n * esbuild substitutes a stub that throws — **after the build has reported\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\n * firing, and it is the defect this shim removes.\n *\n * `__dirname` matters as much as `require`: without it a dependency resolving\n * an asset path silently gets `undefined` and fails later, further from the\n * cause.\n *\n * Written as one line because esbuild inserts a banner verbatim above the\n * bundle and a multi-line string here would shift every mapped line.\n */\nconst ESM_INTEROP_SHIM =\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\n \"import{dirname as __wlDirname}from'node:path';\" +\n \"const require=__wlCreateRequire(import.meta.url);\" +\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\n \"const __dirname=__wlDirname(__filename);\";\n\n/**\n * Combine the framework's banner with the user's, keeping both.\n *\n * esbuild's `banner` is an object keyed by output type, and every merge in the\n * path to it — the config merge and the options spread — REPLACES that object\n * rather than merging it. So whichever is applied second silently deletes the\n * other. This is the only place the two can coexist.\n *\n * The shim goes first: it defines `require`, which a user banner may use.\n *\n * @param userBanner banner from `warlock.config.ts`, if any\n * @param shim the interop shim, or undefined when it does not apply\n */\nfunction mergeBanner(\n userBanner: Record<string, string> | undefined,\n shim: string | undefined,\n): Record<string, string> | undefined {\n if (!shim) return userBanner;\n\n const userJs = userBanner?.js;\n\n return {\n ...userBanner,\n js: userJs ? `${shim}${userJs}` : shim,\n };\n}\n\n/**\n * Prefix every generated file uses to reach the app root.\n *\n * Generated sources are written into `.warlock/production/`, two levels below\n * the app root, so `../../` lands back on it — the same hop already spelled\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\n * config-loader generators emit. Named once so a generator that needs a new\n * app-root file (`warlock.config`) cannot pick a different depth.\n */\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\n\n/**\n * Production Builder\n * Generates production-ready files and bundles them for deployment\n * Build options are loaded from warlock.config.ts\n */\nexport class ProductionBuilder {\n private options!: ResolvedBuildConfig;\n private readonly productionDir = warlockPath(\"production\");\n\n /**\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\n * never calls `boot()`/`start()` on them; it only\n * drains their `build` contributions.\n */\n private connectors: readonly Connector[] = [];\n\n /**\n * The contributors' merged esbuild patch, produced by the `generate` pass\n * and consumed by {@link bundle}.\n */\n private contributedEsbuild: ConnectorEsbuildPatch = {};\n\n /** Browser-safe API metadata captured in a fresh registration-only child. */\n private namedApiRoutes?: readonly import(\"../router/types\").NamedApiRoute[];\n\n public budgetReport?: BuildBudgetReport;\n\n /**\n * Main build entry point\n *\n * The esbuild bundle is written into a TEMP directory next to the real\n * output directory, never into it, and that directory is renamed over\n * `outdir` as one filesystem operation — so `outdir` is never observed as\n * a mix of the old build and the new one, and a build that fails before\n * that rename never touches `outdir` at all.\n *\n * `this.options.outdir` is NOT repointed at the temp directory while that\n * happens, and must never be. It is not merely a write target: consumers\n * BAKE it into runtime output — `web`'s build contribution derives the\n * `clientDir` recorded in its pages manifest from it\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\n * produces an artifact whose browser paths point at a directory promotion\n * has since renamed away. The temp path is passed explicitly, as a\n * parameter, to the one operation that writes into it ({@link bundle});\n * everything else, `buildContext()` included, keeps reading the final\n * destination.\n *\n * That is also why promotion is STAGED rather than done at the very end.\n * Connector `emit` hooks write real artifacts (the web client bundle) and\n * see the final `outdir`, so they must run when `outdir` genuinely holds\n * this build — after the rename, not before it, or promotion would replace\n * the directory they just wrote into. The previous build is kept parked\n * aside until they finish: `emit` throwing rolls the whole promotion back,\n * and the build-success marker `warlock start` checks is written last of\n * all, so a failure at any point leaves no `dist` that start will boot.\n */\n public async build(): Promise<void> {\n console.log(colors.cyan(\"Building for production...\\n\"));\n\n // Step 0: Fail fast when esbuild's native binary never got linked (the\n // state pnpm leaves a project in when its build-script approval gate\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\n // own cryptic \"package could not be found\" error several steps from now.\n assertEsbuildBinaryIsLinked();\n\n // Step 1: Initialize options from config\n await this.initializeOptions();\n\n const finalOutDir = this.options.outdir!;\n const previousBudgetReport = await readBuildBudgetReport(finalOutDir);\n const tempOutDir = createTempOutputDir(finalOutDir);\n\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\n // presence is what tells the catch below whether a failure has a\n // promotion to undo or only a temp directory to discard.\n let staged: StagedDist | undefined;\n\n try {\n // Step 2: Generate combined files\n await this.generateCombinedFiles();\n\n // Step 3: Generate entry point\n await this.generateEntryPoint();\n\n // Step 4: Refuse to bundle code the app could not resolve at runtime\n await this.assertGeneratedImports();\n\n // Step 4.5: Drain the connectors' `generate` contributions\n await this.captureNamedApiRoutesForWeb();\n const contributed = await this.runGenerateContributions();\n\n // Step 4.6: Re-assert over what the contributors just wrote.\n //\n // Step 4 only saw core's own generated files; a contributor writes its\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\n // specifier in it reaches the bundle unchecked. Under\n // `packages: \"external\"` that specifier survives verbatim into the\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\n // and re-reading the production dir is pure cost in the common case.\n if (contributed) {\n await this.assertGeneratedImports();\n }\n\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\n // operation handed that path — it is a write target, not config.\n await this.bundle(tempOutDir);\n\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\n // build parked aside. `outdir` now holds exactly this build, so the\n // steps below write into — and record — the real destination.\n staged = await stageDistAsync(tempOutDir, finalOutDir);\n\n // Step 5.6: Drain the connectors' `emit` contributions — after the\n // bundle is in place (so what they write survives promotion and the\n // paths they bake in resolve), and BEFORE step 6 deletes the\n // production directory they may still read.\n await runEmitContributions(this.connectors, this.buildContext());\n\n const clientReport = await readBuildBudgetReport(finalOutDir);\n this.budgetReport = evaluateBuildBudgets(\n clientReport?.pages ?? [],\n this.options.budgets,\n previousBudgetReport,\n );\n if (clientReport) await writeBuildBudgetReport(finalOutDir, this.budgetReport);\n if (this.budgetReport.pages.length > 0) console.log(formatBuildBudgets(this.budgetReport));\n if (this.budgetReport.violations.length > 0) {\n const message = formatBudgetViolations(this.budgetReport);\n if (this.options.budgets?.mode !== \"warn\") throw new Error(message);\n console.warn(message);\n }\n\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\n // `warlock start` trusts. Written LAST on purpose: every earlier step\n // can still fail, and until this file exists nothing will boot what\n // they left behind.\n await writeDistBuildManifestAsync(finalOutDir);\n\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\n await commitDistAsync(staged);\n } catch (error) {\n if (staged) {\n // The promotion already happened; put the previous build back and\n // take this half-finished one out of `outdir`.\n await rollbackDistAsync(staged);\n } else {\n // Nothing this build produced ever reached `outdir` — discard the\n // temp directory and leave `outdir` exactly as it was.\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\n }\n\n throw error;\n }\n\n // Step 6: Remove production folder\n await removeDirectoryAsync(this.productionDir);\n\n console.log(colors.green(\"Build complete!\"));\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\n }\n\n /**\n * Initialize options from warlock.config.ts\n */\n private async initializeOptions(): Promise<void> {\n this.options = resolveBuildConfig();\n // Same config object `resolveBuildConfig` just read — `warlock build`\n // preloads warlock.config.ts, so no additional load happens here.\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\n\n // Checked here, where the array is first read, so nothing downstream has\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\n // a name listed twice would write its files and merge its esbuild options\n // twice into an artifact the runtime then boots that name only once from.\n // A build that half-applied a connector and reported success is worse than\n // one that never started.\n assertUniqueConnectorNames([...connectors]);\n\n // And here rather than only at boot, for the same reason: a name a built-in\n // already owns is skipped by the runtime, so an artifact built from it\n // carries the custom connector's generated files and esbuild patches while\n // the server boots the built-in instead. Refusing it at boot alone would\n // mean the build had already emitted that artifact — the failure has to\n // land on the developer running `warlock build`, not on whoever starts the\n // server. Same assertion the registration half calls, over the same names.\n assertNoReservedConnectorNames([...connectors]);\n\n this.connectors = connectors;\n\n // Ensure production directory exists\n await ensureDirectoryAsync(this.productionDir);\n }\n\n /**\n * The context handed to every build contribution.\n */\n private buildContext(): ConnectorBuildContext {\n return {\n productionDir: this.productionDir,\n appRoot: rootPath(),\n options: this.options,\n namedApiRoutes: this.namedApiRoutes,\n };\n }\n\n /**\n * Web route declarations need application API registration, which cannot be\n * inferred from generated files. Capture it once in a disposable child before\n * contributors write build artifacts; no connector lifecycle runs there.\n */\n private async captureNamedApiRoutesForWeb(): Promise<void> {\n if (!this.connectors.some((connector) => connector.name === \"web\")) {\n await clearOwnedRouteTypes(rootPath());\n return;\n }\n\n this.namedApiRoutes = (\n await collectRouteRegistrationSnapshot({\n cwd: rootPath(),\n timeoutMs: this.options.routeRegistrationTimeoutMs,\n })\n ).routes;\n }\n\n /**\n * Drain the `generate` hooks and fold what they returned back into the\n * build.\n *\n * The entry point is REGENERATED here rather than generated later. The\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\n * bundles that the app could not resolve) and before `bundle` — while\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\n * generated code the assertion has to see; moving it past the assertion\n * would silently drop the entry from that check. Rewriting one small file\n * is cheaper than losing either guarantee, and the write is pure\n * (`generatedFiles` + these imports), so doing it twice is not a\n * correctness risk.\n *\n * @returns whether any connector ran a `generate` hook — the caller uses it\n * to decide if the import assertion is worth a second pass. Keyed on the\n * hook EXISTING, not on what it returned: a hook that returns nothing may\n * still have written files into `productionDir`, and those are exactly the\n * files the second pass is there to read.\n */\n private async runGenerateContributions(): Promise<boolean> {\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\n\n const { entryImports, esbuild } = await runGenerateContributions(\n this.connectors,\n this.buildContext(),\n );\n\n this.contributedEsbuild = esbuild;\n\n if (entryImports.length > 0) {\n await this.generateEntryPoint(entryImports);\n }\n\n return contributed;\n }\n\n /**\n * Track which special files were generated\n */\n private generatedFiles = {\n locales: false,\n events: false,\n main: false,\n routes: false,\n workers: false,\n };\n\n /**\n * Generate all combined files\n */\n private async generateCombinedFiles(): Promise<void> {\n console.log(colors.yellow(\" Generating production files...\"));\n\n // Generate bootstrap.ts file\n await this.generateBootstrap();\n\n // Generate config loader\n await this.generateConfigLoader();\n\n // Generate special files and track which ones have content\n const [locales, events, main, routes, workers] = await Promise.all([\n this.generateLocales(),\n this.generateEvents(),\n this.generateMain(),\n this.generateRoutes(),\n this.generateWorkers(),\n ]);\n\n this.generatedFiles = { locales, events, main, routes, workers };\n }\n\n /**\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\n */\n private async generateBootstrap(): Promise<void> {\n // ESM hoists imports, so the app bootstrap must be the first import to run first\n const appBootstrapImport = (await fileExistsAsync(appPath(\"bootstrap.ts\")))\n ? \"import './../../src/app/bootstrap';\\n\"\n : \"\";\n\n const content = `${appBootstrapImport}import { bootstrap, Application } from \"@warlock.js/core\";\n\n// Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins\nApplication.setRuntimeStrategy(\"production\");\nif (!process.env.NODE_ENV) {\n Application.setEnvironment(\"production\");\n}\n\n// Bootstrap the application\nbootstrap();\n`;\n\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\n }\n\n /**\n * Fail the build when generated code imports a package the app does not\n * declare.\n *\n * The bundler is configured `packages: \"external\"`, so every bare specifier\n * written above survives verbatim into an artifact that resolves against the\n * **consuming app's** node_modules. A framework-internal dependency imported\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\n * which is how a production app shipped that could not boot. Rewriting the\n * offending import fixes today's bundle; this check is what stops the next\n * change to the generator from quietly reintroducing it.\n */\n private async assertGeneratedImports(): Promise<void> {\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\n cwd: this.productionDir,\n absolute: false,\n });\n\n const [files, appPackage] = await Promise.all([\n Promise.all(\n generatedPaths.map(async (file) => ({\n file,\n content: await getFileAsync(path.join(this.productionDir, file)),\n })),\n ),\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\n ]);\n\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\n }\n\n /**\n * Glob `src/app` and keep the files the shared dev-server predicate accepts,\n * so production discovers exactly what the dev collector does.\n * Returns relative paths from .warlock/production/ to src/app/\n */\n private async globModule(matches: (relativePath: string) => boolean): Promise<string[]> {\n const files = await glob(\"**/*.{ts,tsx,json}\", {\n cwd: appPath(),\n absolute: false,\n });\n\n // e.g., \"users/main.ts\" -> \"../../src/app/users/main\"\n return files\n .filter((file) => matches(\"src/app/\" + file))\n .sort()\n .map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\n }\n\n /**\n * Generate config-loader.ts\n */\n private async generateConfigLoader(): Promise<void> {\n const configDirectory = path.join(process.cwd(), \"src/config\");\n\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: configDirectory,\n absolute: false,\n });\n\n // Same key rule as the dev config loader: the raw path, never camel-cased\n const configNames = files\n .filter((f) => isConfigFile(\"src/config/\" + f))\n .map((f) => ({\n path: f.replace(/\\.(ts|tsx)$/, \"\"),\n key: configKeyFromPath(\"src/config/\" + f),\n }))\n .filter((entry): entry is { path: string; key: string } => entry.key !== undefined)\n .sort((a, b) => a.path.localeCompare(b.path));\n\n // Only `@warlock.js/core` — the one package the app itself declares. See\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\n // dependency, so a bare import of it resolved by luck under npm/yarn\n // hoisting and died under pnpm's strict layout.\n const imports: string[] = [\n 'import { assertValidConfigModules, configSpecialHandlers, setConfig } from \"@warlock.js/core\";',\n ];\n const configImports: string[] = [];\n const configSetCalls: string[] = [];\n const validations: string[] = [];\n const executors: string[] = [];\n\n configNames.forEach(({ path: configPath, key }, index) => {\n // Index-based identifier: keys like \"rate-limit\" or \"mail/smtp\" are not valid names.\n // A namespace import, so a file's optional `configSchema` export travels with it.\n const varName = `config${index}`;\n const name = JSON.stringify(key);\n configImports.push(`import * as ${varName} from \"../../src/config/${configPath}\";`);\n configSetCalls.push(`setConfig(${name}, ${varName}.default);`);\n validations.push(` { name: ${name}, module: ${varName} },`);\n executors.push(`await configSpecialHandlers.execute(${name}, ${varName}.default);`);\n });\n\n // ESM hoists imports, so prestart must be the first import to run first\n const prestartImports = (await fileExistsAsync(appPath(\"prestart.ts\")))\n ? [\"import './../../src/app/prestart';\"]\n : [];\n\n const content = [\n ...prestartImports,\n ...imports,\n \"\",\n \"// Config imports\",\n ...configImports,\n \"\",\n \"// Register configs\",\n ...configSetCalls,\n \"\",\n \"// Refuse to start when a config file's `configSchema` is not satisfied\",\n \"await assertValidConfigModules([\",\n ...validations,\n \"]);\",\n \"\",\n \"// Special handlers\",\n ...executors,\n \"\",\n ].join(\"\\n\");\n\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\n }\n\n /**\n * Generate locales.ts (only if there are locale files)\n * @returns true if file was generated with content\n */\n private async generateLocales(): Promise<boolean> {\n const files = await this.globModule(isLocaleFile);\n if (files.length === 0) return false;\n const content = files\n .map((file, index) => {\n if (!file.endsWith(\".json\")) return `import \"${file}\";`;\n const moduleFolder = file.split(\"/\").at(-3)!;\n return [\n `import dictionary${index} from \"${file}\";`,\n 'import { registerLocaleDictionary } from \"@warlock.js/core\";',\n `registerLocaleDictionary({ sourceFile: ${JSON.stringify(file)}, source: JSON.stringify(dictionary${index}), defaultNamespace: ${JSON.stringify(moduleFolder)} });`,\n ].join(\"\\n\");\n })\n .join(\"\\n\");\n await putFileAsync(path.join(this.productionDir, \"locales.ts\"), content + \"\\n\");\n return true;\n }\n\n /**\n * Generate events.ts (only if there are event files)\n * @returns true if file was generated with content\n */\n private async generateEvents(): Promise<boolean> {\n const files = await this.globModule(isEventFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"events.ts\");\n return true;\n }\n\n /**\n * Generate main.ts (only if there are main files)\n * @returns true if file was generated with content\n */\n private async generateMain(): Promise<boolean> {\n const files = await this.globModule(isMainFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"main.ts\");\n return true;\n }\n\n /**\n * Generate routes.ts (only if there are route files)\n * @returns true if file was generated with content\n */\n private async generateRoutes(): Promise<boolean> {\n const files = await this.globModule(isRouteFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"routes.ts\");\n return true;\n }\n\n /**\n * Generate workers.ts (only if there are worker files)\n * @returns true if file was generated with content\n */\n private async generateWorkers(): Promise<boolean> {\n const files = await this.globModule(isWorkerFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"workers.ts\");\n return true;\n }\n\n /**\n * Generate a file with imports from all given files\n */\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, outputFile), content);\n }\n\n /**\n * Generate the main entry point (app.ts)\n *\n * @param contributedImports lines from connector `generate` hooks, appended\n * to section 4 after `./routes`\n */\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\n console.log(colors.yellow(\" Generating entry point...\"));\n\n // The names this build resolved, baked in as a literal. The entry imports\n // the config source, and that source is re-evaluated at startup — an\n // env-conditional `connectors` array can hand the boot a different list\n // than the one drained here. A literal is the only part of the array that\n // survives into the artifact unchanged, so it is what the boot compares\n // against.\n const expectedNames = this.connectors\n .map((connector) => JSON.stringify(connector.name))\n .join(\", \");\n\n // Build imports based on which files were generated\n const imports: string[] = [\n \"// 1. Bootstrap (loads .env, initializes framework)\",\n 'import \"./bootstrap\";',\n \"\",\n \"// 2. Load configs\",\n 'import \"./config-loader\";',\n \"\",\n // Registration has to sit between the config being available and the\n // first phase starting: the connectors listed in `connectors` are the\n // same ones this build drained contributions from, so the bundle boots\n // exactly what it was built for. Register any later and an early-phase\n // connector would miss its own start.\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\n \"// build read its contributions from, so built-for and boots-with match).\",\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\n \"// and the array is handed over explicitly — an artifact has no\",\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\n \"// that quietly found nothing to register is the exact drift this\",\n \"// section exists to prevent.\",\n \"// `expectedNames` is the list this build resolved, in order — boot\",\n \"// refuses to start when the config hands over a different set or order.\",\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\n \"\",\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\n \"// own preflight is not reached until the database and cache have\",\n \"// connected and every app module has been imported — seconds of work\",\n \"// thrown away before anyone learns the port was taken. This probe is\",\n \"// a bind-and-release on a socket that is never served, and it reports\",\n \"// on stderr because no log channel is configured this early.\",\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\n 'if (Application.hasRole(\"api\") || Application.hasRole(\"web\")) {',\n \" await preflightConfiguredHttpPort();\",\n \"}\",\n \"\",\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\n \"// so data sources, cache, etc. are ready before app code runs\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\n ];\n\n // App code uses dynamic `await import(...)` so each module's side\n // effects fire at THIS point in execution. Static imports would be\n // hoisted to module-instantiation time (before the early-phase await\n // resolves), which is exactly the bug this split is meant to fix.\n //\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\n // it at the await, not at instantiation. It does NOT come from\n // `splitting: true`, which only decides one-file-vs-chunks. This\n // previously said splitting was required; it is not, and `singleBundle`\n // (splitting: false) preserves the ordering.\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\n\n if (this.generatedFiles.events) {\n imports.push('await import(\"./events\");');\n }\n if (this.generatedFiles.locales) {\n imports.push('await import(\"./locales\");');\n }\n if (this.generatedFiles.main) {\n imports.push('await import(\"./main\");');\n }\n if (this.generatedFiles.routes) {\n imports.push('if (Application.hasRole(\"api\")) {', ' await import(\"./routes\");', \"}\");\n }\n if (this.generatedFiles.workers) {\n imports.push('if (Application.hasRole(\"worker\")) {', ' await import(\"./workers\");', \"}\");\n }\n\n // Contributor imports come AFTER `./routes`, never before: a connector\n // that registers pages needs the routes app code already collected —\n // the same ordering dev uses (routes first, then the connector installs\n // on top of them). Emitted verbatim; the contributor writes the whole\n // statement (e.g. `await import(\"./pages\");`).\n imports.push(...contributedImports);\n\n // A rejecting validator (Application.onValidateBoot) must abort boot\n // before late-phase connectors bind a port.\n imports.push(\n \"\",\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\n \"await Application.runStartupValidators();\",\n );\n\n // Start late-phase connectors after app code registers routes/listeners\n imports.push(\n \"\",\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\n \"// listeners registered by app code are now ready to bind\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\n \"\",\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\n \"connectorsManager.shutdownOnProcessKill();\",\n );\n\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\n }\n\n /**\n * Bundle with esbuild\n *\n * @param writeOutDir the directory esbuild writes into — the build's\n * private temp directory, NOT `options.outdir`. Taken as a parameter\n * rather than read off `this.options` because the two are different paths\n * with different meanings: `options.outdir` is the final destination every\n * consumer bakes into the artifact, and this is only where bytes land\n * before promotion moves them there.\n */\n private async bundle(writeOutDir: string): Promise<void> {\n console.log(colors.magenta(\" Bundling with esbuild...\"));\n\n const entryPoint = path.join(this.productionDir, \"app.ts\");\n const outFileName = this.options.outFile!;\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\n const entryName = path.basename(outFileName, path.extname(outFileName));\n\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\n // unknown keys, and the user options are spread into its call verbatim.\n const singleBundle = this.options.singleBundle === true;\n const esmShim = this.options.esmShim !== false;\n // Read before deleting: the merged banner is applied AFTER the user\n // spread, so a user banner must not be lost to it or clobber the shim.\n const userBanner = this.options.banner;\n\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\n // resolve-build-config.ts documents that widening them pushed a lie downstream\n // into start-production.command.ts, which then could not trust its own config.\n // This is the one place they must be absent - the object is spread into esbuild's\n // call verbatim and esbuild throws on unknown keys.\n //\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\n // contribution hook, including the `emit` pass that runs AFTER this method\n // returns (`build()` step 5.6). Deleting these keys from the shared object\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\n // types them as present. A shallow copy is enough — every field this method\n // reads off it is either scalar or already re-merged below (`define`,\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\n\n delete esbuildOptions.outFile;\n delete esbuildOptions.entryPath;\n delete esbuildOptions.singleBundle;\n delete esbuildOptions.esmShim;\n delete esbuildOptions.banner;\n delete esbuildOptions.routeRegistrationTimeoutMs;\n delete esbuildOptions.budgets;\n\n await ensureDirectoryAsync(writeOutDir);\n\n const alias = this.buildAliasMapFromTsconfig();\n\n // Whether this build decides externality per import EDGE\n // (`bundle-framework-dependencies.ts`, which explains the rule at\n // length) or keeps the blunt `packages: \"external\"`.\n //\n // Not in `singleBundle` mode: that bundles everything by definition, and\n // a plugin that can only ever ADD an external would silently narrow it.\n // Not when the user set `packages` themselves: their value has always\n // won over the default below, and it must keep winning — the plugin is\n // the default's implementation, not a new policy layered on top.\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\n\n // The user can override `format`, so gate the shim on the EFFECTIVE\n // format rather than on the default below. A CJS build already has\n // `require` and friends; injecting them there would be a redefinition.\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\n\n // Contributor patch, split into the part that can ride the spread order\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\n // BEFORE the user spread below, which gives the ruled precedence for\n // free: builder defaults < contributor < user config.\n //\n // `define`, `external` and `loader` are pulled out because a spread\n // REPLACES them wholesale — the same trap `banner` documents. Two\n // contributors' env defines, a contributor's optional peers plus the\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\n // must both survive, so they are merged by key/by set and re-applied\n // after the spread with the user still winning per key.\n const {\n define: contributedDefine,\n external: contributedExternal,\n loader: contributedLoader,\n plugins: contributedPlugins,\n ...contributedOptions\n } = this.contributedEsbuild;\n\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\n const userExternal: string[] | undefined = esbuildOptions.external;\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\n\n const define =\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\n\n const loader =\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\n\n const external =\n contributedExternal || userExternal\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\n : undefined;\n\n if (singleBundle) {\n console.log(\n colors.magenta(\n \" Single-bundle mode — one JS file\" +\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\n \". Native .node addons are still emitted alongside it.\",\n ),\n );\n }\n\n try {\n await esbuild.build({\n platform: \"node\",\n entryPoints: [entryPoint],\n bundle: true,\n // Both are DEFAULTS the user can override — they sit before the\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\n //\n // Phase ordering does not depend on `splitting`: it comes from the\n // generated app.ts using dynamic `await import(...)` (see\n // generateAppEntry above), which esbuild defers to the call site in\n // either mode. Splitting only decides one file vs chunks.\n splitting: !singleBundle,\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\n // the plugin below returns `external: true` for every bare specifier\n // this build must not bundle, which is all of them bar the framework's\n // own declared dependencies. Saying `\"external\"` here instead would\n // externalise them before the plugin could rule.\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\n minify: esbuildOptions.minify,\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\n format: \"esm\",\n // Targeting a concrete Node version (not \"esnext\") so esbuild\n // transpiles TC39 stage 3 decorators into helpers — Node does not\n // implement them natively yet.\n target: [\"node22\"],\n entryNames: entryName,\n alias,\n plugins: [\n nativeNodeModulesPlugin,\n // BEFORE the framework-dependency plugin, and the order is\n // load-bearing: the first `onResolve` callback to answer wins, and\n // `app/users/...` is a bare specifier the other one would rule\n // external.\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\n ...(perEdgeExternals\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\n : []),\n // Contributor plugins run last: they load their own file types and\n // must not shadow the resolvers above.\n ...(contributedPlugins ?? []),\n ],\n // Between the defaults and the user spread — the ruled precedence.\n ...contributedOptions,\n ...(esbuildOptions as any),\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\n // that spread carrying the FINAL destination, which is exactly where\n // this build must not write yet. The final path is the user's setting\n // and stays authoritative for everyone reading the config — it is only\n // this one esbuild call that is redirected, and only until promotion\n // moves the result onto that very path.\n outdir: writeOutDir,\n // AFTER the spread for the same reason `banner` is: a spread replaces\n // these objects instead of merging them, so the merged values are\n // re-applied here. The user still wins — they were merged in last.\n ...(define ? { define } : {}),\n ...(external ? { external } : {}),\n ...(loader ? { loader } : {}),\n // AFTER the spread, and intentionally so: `banner` is an object, and\n // both the config merge and this spread REPLACE it wholesale rather\n // than merging. Left as a default above, any user banner would delete\n // the shim; left to the spread, the shim would delete theirs. The\n // merge is the only form that keeps both.\n ...(banner ? { banner } : {}),\n });\n } catch (e) {\n console.log(e);\n throw e;\n }\n }\n\n /**\n * The WILDCARD half of the same tsconfig `paths` map that\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\n * so the entries it skips have to be resolved by a plugin instead of being\n * left to no one.\n */\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\n tsconfigManager.init();\n\n return {\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\n paths: tsconfigManager.aliases as Record<string, string[]>,\n };\n }\n\n /**\n * Build an alias map from tsconfig `paths` so esbuild resolves local\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\n * folders during bundling. Without this, `packages: \"external\"` would\n * leave those bare specifiers as raw imports and Node would fail to\n * resolve them at runtime (they aren't installed in node_modules).\n *\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\n * option doesn't support glob-style mappings. The wildcard half is not\n * dropped, it is handled elsewhere: see\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\n */\n private buildAliasMapFromTsconfig(): Record<string, string> {\n tsconfigManager.init();\n\n const alias: Record<string, string> = {};\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\n\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\n continue;\n }\n\n const target = to[0];\n\n if (target === undefined) {\n continue;\n }\n\n alias[from] = path.resolve(baseUrl, target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GAC7D;GAGF,MAAM,SAAS,GAAG;GAElB,IAAI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
@@ -15,7 +15,7 @@ import { WarlockConfig } from "../warlock-config/types.mjs";
15
15
  * that; widening them to `string | undefined` pushed the lie downstream into
16
16
  * `start-production.command.ts`, which then could not trust its own config.
17
17
  */
18
- type BuilderStrippedKeys = "singleBundle" | "esmShim" | "banner" | "routeRegistrationTimeoutMs";
18
+ type BuilderStrippedKeys = "budgets" | "singleBundle" | "esmShim" | "banner" | "routeRegistrationTimeoutMs";
19
19
  export type ResolvedBuildConfig = Required<Omit<NonNullable<WarlockConfig["build"]>, "outDirectory" | BuilderStrippedKeys>> & Partial<Pick<NonNullable<WarlockConfig["build"]>, BuilderStrippedKeys>> & {
20
20
  /** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */
21
21
  entryPath: string;
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-build-config.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/production/resolve-build-config.ts"],"mappings":";;;;;;;;;;;;;;;;;KAqBK;YAEO,sBAAsB,SAChC,KAAK,YAAY,0CAA0C,wBAE3D,QAAQ,KAAK,YAAY,yBAAyB;;EAEhD"}
1
+ {"version":3,"file":"resolve-build-config.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/production/resolve-build-config.ts"],"mappings":";;;;;;;;;;;;;;;;;KAqBK;YAOO,sBAAsB,SAChC,KAAK,YAAY,0CAA0C,wBAE3D,QAAQ,KAAK,YAAY,yBAAyB;;EAEhD"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-build-config.mjs","names":[],"sources":["../../../../../../../../packages/core/src/production/resolve-build-config.ts"],"sourcesContent":["import path from \"path\";\nimport { defaultWarlockConfigurations } from \"../warlock-config/default-configurations\";\nimport { normalizeBuildConfig } from \"../warlock-config/normalize-build-config\";\nimport type { WarlockConfig } from \"../warlock-config/types\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n/**\n * Keys the builder deletes before handing the options to esbuild — ours\n * (`singleBundle`, `esmShim`), which esbuild would reject as unknown, and\n * `banner`, which is re-merged and re-applied after the user spread.\n *\n * They are optional here for a concrete reason: `Required<…>` makes `delete`\n * a type error (TS2790). Naming exactly these three says which keys are\n * removable, rather than casting at each `delete` — a cast there would also\n * hide a genuine mistake.\n *\n * `outFile` and `entryPath` stay REQUIRED even though the builder deletes\n * them too. They are always present after resolution and callers depend on\n * that; widening them to `string | undefined` pushed the lie downstream into\n * `start-production.command.ts`, which then could not trust its own config.\n */\ntype BuilderStrippedKeys = \"singleBundle\" | \"esmShim\" | \"banner\" | \"routeRegistrationTimeoutMs\";\n\nexport type ResolvedBuildConfig = Required<\n Omit<NonNullable<WarlockConfig[\"build\"]>, \"outDirectory\" | BuilderStrippedKeys>\n> &\n Partial<Pick<NonNullable<WarlockConfig[\"build\"]>, BuilderStrippedKeys>> & {\n /** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */\n entryPath: string;\n };\n\n/**\n * esbuild options the build config may not carry, and why.\n *\n * Both apply the named compiler options to EVERY file in the bundle, not just\n * the app's own sources — workspace packages compiled under their own tsconfig\n * are silently recompiled under the app's. An app-level\n * `verbatimModuleSyntax: true` reaching package sources that never opted into\n * it strips the imports their decorators rely on, and the build succeeds only\n * to die at import time with `Class extends value undefined`.\n */\nconst FORBIDDEN_BUILD_OPTIONS = {\n tsconfig: \"points esbuild at a tsconfig file\",\n tsconfigRaw: \"inlines compiler options\",\n} as const;\n\n/**\n * Raised when the build config carries an esbuild option the framework owns.\n *\n * The typed config already omits these keys; this catches the forms the type\n * cannot see — an `as any` cast, or a plain `warlock.config.js`. Rejected\n * rather than deleted: dropping the key quietly would leave the author\n * believing a setting applied when it never did.\n */\nexport class ForbiddenBuildOptionError extends Error {\n /** Stable Warlock error code; `warlock explain WL1006` prints the fix. */\n public readonly code = \"WL1006\";\n\n public constructor(public readonly option: keyof typeof FORBIDDEN_BUILD_OPTIONS) {\n super(\n [\n `build.${option} is not a supported warlock build option.`,\n \"\",\n `Setting it ${FORBIDDEN_BUILD_OPTIONS[option]} for every file in the bundle,`,\n \"including workspace packages that were compiled under their own tsconfig.\",\n \"Options such as `verbatimModuleSyntax` then apply to sources that never\",\n \"opted into them, and the build succeeds but crashes at import time with\",\n \"`Class extends value undefined`.\",\n \"\",\n `Remove \\`${option}\\` from the \\`build\\` block of your warlock config. The builder`,\n \"already reads the app's tsconfig for the parts it needs (path aliases); to\",\n \"change how your own sources compile, edit that tsconfig.json instead.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"ForbiddenBuildOptionError\";\n }\n}\n\n/**\n * Resolve the build config with framework defaults applied.\n *\n * Both the production builder and `warlock start` call this so they\n * agree on where the bundle lives — previously each had its own local\n * fallbacks and they drifted (`.warlock/production` vs `dist`),\n * letting `build` and `start` look at different paths.\n */\nexport function resolveBuildConfig(): ResolvedBuildConfig {\n // Normalised here rather than only in `defineConfig` because a project may\n // export a plain config object that never went through it.\n const userBuild = normalizeBuildConfig(warlockConfigManager.get(\"build\") ?? {});\n\n // Before the merge, so the option cannot reach the esbuild spread in\n // production-builder — which overrides framework defaults with user config.\n for (const option of Object.keys(FORBIDDEN_BUILD_OPTIONS) as Array<\n keyof typeof FORBIDDEN_BUILD_OPTIONS\n >) {\n if (option in userBuild) {\n throw new ForbiddenBuildOptionError(option);\n }\n }\n\n const defaults = defaultWarlockConfigurations.build!;\n const merged = { ...defaults, ...userBuild } as ResolvedBuildConfig;\n\n return {\n ...merged,\n routeRegistrationTimeoutMs: resolveRouteRegistrationTimeoutMs(\n merged.routeRegistrationTimeoutMs,\n ),\n entryPath: path.resolve(merged.outdir, merged.outFile),\n };\n}\n\nconst DEFAULT_ROUTE_REGISTRATION_TIMEOUT_MS = 30_000;\nconst ROUTE_REGISTRATION_TIMEOUT_ENV = \"WARLOCK_ROUTE_REGISTRATION_TIMEOUT_MS\";\n\nfunction resolveRouteRegistrationTimeoutMs(configured: unknown): number {\n const environment = process.env[ROUTE_REGISTRATION_TIMEOUT_ENV];\n const value = environment === undefined ? configured : environment;\n const source =\n environment === undefined ? \"build.routeRegistrationTimeoutMs\" : ROUTE_REGISTRATION_TIMEOUT_ENV;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value > 0) return value;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed) && parsed > 0) return parsed;\n }\n\n console.warn(\n `Invalid ${source} value ${JSON.stringify(value)}; using ${DEFAULT_ROUTE_REGISTRATION_TIMEOUT_MS}ms.`,\n );\n return DEFAULT_ROUTE_REGISTRATION_TIMEOUT_MS;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,MAAM,0BAA0B;CAC9B,UAAU;CACV,aAAa;AACf;;;;;;;;;AAUA,IAAa,4BAAb,cAA+C,MAAM;CAInD,AAAO,YAAY,AAAgB,QAA8C;EAC/E,MACE;GACE,SAAS,OAAO;GAChB;GACA,cAAc,wBAAwB,QAAQ;GAC9C;GACA;GACA;GACA;GACA;GACA,YAAY,OAAO;GACnB;GACA;EACF,CAAC,CAAC,KAAK,IAAI,CACb;EAfiC;cAFZ;EAmBrB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,SAAgB,qBAA0C;CAGxD,MAAM,YAAY,qBAAqB,qBAAqB,IAAI,OAAO,KAAK,CAAC,CAAC;CAI9E,KAAK,MAAM,UAAU,OAAO,KAAK,uBAAuB,GAGtD,IAAI,UAAU,WACZ,MAAM,IAAI,0BAA0B,MAAM;CAK9C,MAAM,SAAS;EAAE,GADA,6BAA6B;EAChB,GAAG;CAAU;CAE3C,OAAO;EACL,GAAG;EACH,4BAA4B,kCAC1B,OAAO,0BACT;EACA,WAAW,KAAK,QAAQ,OAAO,QAAQ,OAAO,OAAO;CACvD;AACF;AAEA,MAAM,wCAAwC;AAC9C,MAAM,iCAAiC;AAEvC,SAAS,kCAAkC,YAA6B;CACtE,MAAM,cAAc,QAAQ,IAAI;CAChC,MAAM,QAAQ,gBAAgB,SAAY,aAAa;CACvD,MAAM,SACJ,gBAAgB,SAAY,qCAAqC;CAEnE,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG,OAAO;CAC7E,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,IAAI;EACpD,MAAM,SAAS,OAAO,KAAK;EAC3B,IAAI,OAAO,SAAS,MAAM,KAAK,SAAS,GAAG,OAAO;CACpD;CAEA,QAAQ,KACN,WAAW,OAAO,SAAS,KAAK,UAAU,KAAK,EAAE,UAAU,sCAAsC,IACnG;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"resolve-build-config.mjs","names":[],"sources":["../../../../../../../../packages/core/src/production/resolve-build-config.ts"],"sourcesContent":["import path from \"path\";\nimport { defaultWarlockConfigurations } from \"../warlock-config/default-configurations\";\nimport { normalizeBuildConfig } from \"../warlock-config/normalize-build-config\";\nimport type { WarlockConfig } from \"../warlock-config/types\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n/**\n * Keys the builder deletes before handing the options to esbuild — ours\n * (`singleBundle`, `esmShim`), which esbuild would reject as unknown, and\n * `banner`, which is re-merged and re-applied after the user spread.\n *\n * They are optional here for a concrete reason: `Required<…>` makes `delete`\n * a type error (TS2790). Naming exactly these three says which keys are\n * removable, rather than casting at each `delete` — a cast there would also\n * hide a genuine mistake.\n *\n * `outFile` and `entryPath` stay REQUIRED even though the builder deletes\n * them too. They are always present after resolution and callers depend on\n * that; widening them to `string | undefined` pushed the lie downstream into\n * `start-production.command.ts`, which then could not trust its own config.\n */\ntype BuilderStrippedKeys =\n | \"budgets\"\n | \"singleBundle\"\n | \"esmShim\"\n | \"banner\"\n | \"routeRegistrationTimeoutMs\";\n\nexport type ResolvedBuildConfig = Required<\n Omit<NonNullable<WarlockConfig[\"build\"]>, \"outDirectory\" | BuilderStrippedKeys>\n> &\n Partial<Pick<NonNullable<WarlockConfig[\"build\"]>, BuilderStrippedKeys>> & {\n /** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */\n entryPath: string;\n };\n\n/**\n * esbuild options the build config may not carry, and why.\n *\n * Both apply the named compiler options to EVERY file in the bundle, not just\n * the app's own sources — workspace packages compiled under their own tsconfig\n * are silently recompiled under the app's. An app-level\n * `verbatimModuleSyntax: true` reaching package sources that never opted into\n * it strips the imports their decorators rely on, and the build succeeds only\n * to die at import time with `Class extends value undefined`.\n */\nconst FORBIDDEN_BUILD_OPTIONS = {\n tsconfig: \"points esbuild at a tsconfig file\",\n tsconfigRaw: \"inlines compiler options\",\n} as const;\n\n/**\n * Raised when the build config carries an esbuild option the framework owns.\n *\n * The typed config already omits these keys; this catches the forms the type\n * cannot see — an `as any` cast, or a plain `warlock.config.js`. Rejected\n * rather than deleted: dropping the key quietly would leave the author\n * believing a setting applied when it never did.\n */\nexport class ForbiddenBuildOptionError extends Error {\n /** Stable Warlock error code; `warlock explain WL1006` prints the fix. */\n public readonly code = \"WL1006\";\n\n public constructor(public readonly option: keyof typeof FORBIDDEN_BUILD_OPTIONS) {\n super(\n [\n `build.${option} is not a supported warlock build option.`,\n \"\",\n `Setting it ${FORBIDDEN_BUILD_OPTIONS[option]} for every file in the bundle,`,\n \"including workspace packages that were compiled under their own tsconfig.\",\n \"Options such as `verbatimModuleSyntax` then apply to sources that never\",\n \"opted into them, and the build succeeds but crashes at import time with\",\n \"`Class extends value undefined`.\",\n \"\",\n `Remove \\`${option}\\` from the \\`build\\` block of your warlock config. The builder`,\n \"already reads the app's tsconfig for the parts it needs (path aliases); to\",\n \"change how your own sources compile, edit that tsconfig.json instead.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"ForbiddenBuildOptionError\";\n }\n}\n\n/**\n * Resolve the build config with framework defaults applied.\n *\n * Both the production builder and `warlock start` call this so they\n * agree on where the bundle lives — previously each had its own local\n * fallbacks and they drifted (`.warlock/production` vs `dist`),\n * letting `build` and `start` look at different paths.\n */\nexport function resolveBuildConfig(): ResolvedBuildConfig {\n // Normalised here rather than only in `defineConfig` because a project may\n // export a plain config object that never went through it.\n const userBuild = normalizeBuildConfig(warlockConfigManager.get(\"build\") ?? {});\n\n // Before the merge, so the option cannot reach the esbuild spread in\n // production-builder — which overrides framework defaults with user config.\n for (const option of Object.keys(FORBIDDEN_BUILD_OPTIONS) as Array<\n keyof typeof FORBIDDEN_BUILD_OPTIONS\n >) {\n if (option in userBuild) {\n throw new ForbiddenBuildOptionError(option);\n }\n }\n\n const defaults = defaultWarlockConfigurations.build!;\n const merged = { ...defaults, ...userBuild } as ResolvedBuildConfig;\n\n return {\n ...merged,\n routeRegistrationTimeoutMs: resolveRouteRegistrationTimeoutMs(\n merged.routeRegistrationTimeoutMs,\n ),\n entryPath: path.resolve(merged.outdir, merged.outFile),\n };\n}\n\nconst DEFAULT_ROUTE_REGISTRATION_TIMEOUT_MS = 30_000;\nconst ROUTE_REGISTRATION_TIMEOUT_ENV = \"WARLOCK_ROUTE_REGISTRATION_TIMEOUT_MS\";\n\nfunction resolveRouteRegistrationTimeoutMs(configured: unknown): number {\n const environment = process.env[ROUTE_REGISTRATION_TIMEOUT_ENV];\n const value = environment === undefined ? configured : environment;\n const source =\n environment === undefined ? \"build.routeRegistrationTimeoutMs\" : ROUTE_REGISTRATION_TIMEOUT_ENV;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value > 0) return value;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed) && parsed > 0) return parsed;\n }\n\n console.warn(\n `Invalid ${source} value ${JSON.stringify(value)}; using ${DEFAULT_ROUTE_REGISTRATION_TIMEOUT_MS}ms.`,\n );\n return DEFAULT_ROUTE_REGISTRATION_TIMEOUT_MS;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,MAAM,0BAA0B;CAC9B,UAAU;CACV,aAAa;AACf;;;;;;;;;AAUA,IAAa,4BAAb,cAA+C,MAAM;CAInD,AAAO,YAAY,AAAgB,QAA8C;EAC/E,MACE;GACE,SAAS,OAAO;GAChB;GACA,cAAc,wBAAwB,QAAQ;GAC9C;GACA;GACA;GACA;GACA;GACA,YAAY,OAAO;GACnB;GACA;EACF,CAAC,CAAC,KAAK,IAAI,CACb;EAfiC;cAFZ;EAmBrB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,SAAgB,qBAA0C;CAGxD,MAAM,YAAY,qBAAqB,qBAAqB,IAAI,OAAO,KAAK,CAAC,CAAC;CAI9E,KAAK,MAAM,UAAU,OAAO,KAAK,uBAAuB,GAGtD,IAAI,UAAU,WACZ,MAAM,IAAI,0BAA0B,MAAM;CAK9C,MAAM,SAAS;EAAE,GADA,6BAA6B;EAChB,GAAG;CAAU;CAE3C,OAAO;EACL,GAAG;EACH,4BAA4B,kCAC1B,OAAO,0BACT;EACA,WAAW,KAAK,QAAQ,OAAO,QAAQ,OAAO,OAAO;CACvD;AACF;AAEA,MAAM,wCAAwC;AAC9C,MAAM,iCAAiC;AAEvC,SAAS,kCAAkC,YAA6B;CACtE,MAAM,cAAc,QAAQ,IAAI;CAChC,MAAM,QAAQ,gBAAgB,SAAY,aAAa;CACvD,MAAM,SACJ,gBAAgB,SAAY,qCAAqC;CAEnE,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG,OAAO;CAC7E,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,IAAI;EACpD,MAAM,SAAS,OAAO,KAAK;EAC3B,IAAI,OAAO,SAAS,MAAM,KAAK,SAAS,GAAG,OAAO;CACpD;CAEA,QAAQ,KACN,WAAW,OAAO,SAAS,KAAK,UAAU,KAAK,EAAE,UAAU,sCAAsC,IACnG;CACA,OAAO;AACT"}
@@ -1,9 +1,9 @@
1
1
  import { Response } from "../http/response.mjs";
2
2
  import { Request } from "../http/request.mjs";
3
+ import { RepositoryManager } from "../repositories/repository.manager.mjs";
3
4
  import "../http/index.mjs";
4
5
  import { HttpContext, RestfulMiddleware, RouteResource } from "../router/types.mjs";
5
6
  import "../router/index.mjs";
6
- import { RepositoryManager } from "../repositories/repository.manager.mjs";
7
7
  import "../repositories/index.mjs";
8
8
  import { Model } from "@warlock.js/cascade";
9
9
  import { GenericObject } from "@mongez/reinforcements";
@@ -18,7 +18,9 @@ import { StorageDriverName } from "../../storage/types.mjs";
18
18
  */
19
19
  export declare const storageFake: {
20
20
  /** Re-register every driver as a local one under the temp root. */
21
- install(): Promise<void>;
21
+ install(options?: {
22
+ isolated?: boolean;
23
+ }): Promise<void>;
22
24
  /** Drop the fake drivers; the real configuration is read again on next use. */
23
25
  restore(): Promise<void>;
24
26
  isInstalled(): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"storage-fake.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/storage-fake.ts"],"mappings":";;;;;;;;;;;;;;;;;;qBA2Da;;EAEL,WAAW;;EAuCX,WAAW;EAoBjB;;EAKA;;EAKA,MAAK,SAAU;;EAQT,aAAY,kBAAiB,SAAW,oBAAoB;;EAa5D,cAAa,kBAAiB,SAAW,oBAAoB"}
1
+ {"version":3,"file":"storage-fake.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/storage-fake.ts"],"mappings":";;;;;;;;;;;;;;;;;;qBA2Da;;EAEL,QAAO;IAAa;MAAuB;;EAuC3C,WAAW;EAoBjB;;EAKA;;EAKA,MAAK,SAAU;;EAQT,aAAY,kBAAiB,SAAW,oBAAoB;;EAa5D,cAAa,kBAAiB,SAAW,oBAAoB"}
@@ -47,20 +47,20 @@ function listFiles(directory, base) {
47
47
  */
48
48
  const storageFake = {
49
49
  /** Re-register every driver as a local one under the temp root. */
50
- async install() {
50
+ async install(options) {
51
51
  if (!installed) {
52
52
  wasInitialized = storage.isInitialized;
53
53
  installed = true;
54
54
  }
55
55
  if (!root) {
56
- const shared = process.env[TEST_STORAGE_ROOT_ENV_KEY];
56
+ const shared = options?.isolated ? void 0 : process.env[TEST_STORAGE_ROOT_ENV_KEY];
57
57
  if (shared) {
58
58
  root = shared;
59
59
  ownsRoot = false;
60
60
  } else {
61
61
  root = mkdtempSync(path.join(os.tmpdir(), "warlock-test-storage-"));
62
62
  ownsRoot = true;
63
- process.env[TEST_STORAGE_ROOT_ENV_KEY] = root;
63
+ if (!options?.isolated) process.env[TEST_STORAGE_ROOT_ENV_KEY] = root;
64
64
  }
65
65
  }
66
66
  await storage.init();
@@ -1 +1 @@
1
- {"version":3,"file":"storage-fake.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/storage-fake.ts"],"sourcesContent":["import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { storage } from \"../../storage\";\nimport { storageConfigurations } from \"../../storage/config\";\nimport type { StorageDriverName } from \"../../storage/types\";\nimport { FakeAssertionError } from \"./fake-assertion-error\";\n\n/**\n * The env var that carries the fake storage root from the process that\n * created it (the HTTP test server, in `globalSetup`) to the test workers it\n * spawns, so both sides read and write the same files. Like\n * `WARLOCK_TEST_SERVER_PORT`, it is plumbing between the kit's own processes.\n */\nexport const TEST_STORAGE_ROOT_ENV_KEY = \"WARLOCK_TEST_STORAGE_ROOT\";\n\nlet root: string | undefined;\nlet ownsRoot = false;\nlet installed = false;\nlet wasInitialized = false;\n\nfunction currentRoot(): string {\n if (!root) {\n throw new FakeAssertionError(\n \"storageFake is not installed. It installs by default in the test environment; check `tests.fakes` in src/config/tests.ts, or call storageFake.install().\",\n );\n }\n\n return root;\n}\n\nfunction listFiles(directory: string, base: string): string[] {\n if (!existsSync(directory)) return [];\n\n return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {\n const absolute = path.join(directory, entry.name);\n\n return entry.isDirectory()\n ? listFiles(absolute, base)\n : [path.relative(base, absolute).split(path.sep).join(\"/\")];\n });\n}\n\n/**\n * Points every configured storage driver — local, S3, R2, Spaces — at a\n * local temporary directory.\n *\n * Installed by default in the test environment: uploads and `storage.put()`\n * calls land on disk under one temp root (a folder per driver name), never in\n * a bucket and never in the app's real `storage/` folder. The root is shared\n * with the HTTP test server, so a file an HTTP request stored is visible to\n * the test that sent it. The process that created the root deletes it on\n * restore.\n *\n * @example\n * await uploadAvatar(user, file);\n *\n * await storageFake.assertExists(`avatars/${user.id}.png`);\n */\nexport const storageFake = {\n /** Re-register every driver as a local one under the temp root. */\n async install(): Promise<void> {\n if (!installed) {\n wasInitialized = storage.isInitialized;\n installed = true;\n }\n\n if (!root) {\n const shared = process.env[TEST_STORAGE_ROOT_ENV_KEY];\n\n if (shared) {\n root = shared;\n ownsRoot = false;\n } else {\n root = mkdtempSync(path.join(os.tmpdir(), \"warlock-test-storage-\"));\n ownsRoot = true;\n process.env[TEST_STORAGE_ROOT_ENV_KEY] = root;\n }\n }\n\n await storage.init();\n\n const fakeRoot = root;\n\n for (const name of storage.driverNames()) {\n const driverRoot = path.join(fakeRoot, name);\n\n mkdirSync(driverRoot, { recursive: true });\n storage.register(\n name,\n storageConfigurations.local({ root: driverRoot, urlPrefix: `/test-storage/${name}` }),\n );\n }\n\n const defaultName = storage.getDefaultName();\n\n if (defaultName) storage.setDefault(defaultName);\n },\n\n /** Drop the fake drivers; the real configuration is read again on next use. */\n async restore(): Promise<void> {\n if (!installed) return;\n\n installed = false;\n storage.reset();\n\n if (wasInitialized) await storage.init();\n\n if (root && ownsRoot) {\n rmSync(root, { recursive: true, force: true });\n\n if (process.env[TEST_STORAGE_ROOT_ENV_KEY] === root) {\n delete process.env[TEST_STORAGE_ROOT_ENV_KEY];\n }\n }\n\n root = undefined;\n ownsRoot = false;\n },\n\n isInstalled(): boolean {\n return installed;\n },\n\n /** The temp directory every fake driver lives under. */\n root(): string {\n return currentRoot();\n },\n\n /** Every stored file, as `<driver>/<path>`, sorted. */\n files(driver?: StorageDriverName): string[] {\n const base = currentRoot();\n const directory = driver ? path.join(base, driver) : base;\n\n return listFiles(directory, directory).sort();\n },\n\n /** Assert a file exists, on the default driver unless `driver` is given. */\n async assertExists(location: string, driver?: StorageDriverName): Promise<void> {\n currentRoot();\n\n const target = driver ? storage.use(driver) : storage;\n\n if (!(await target.exists(location))) {\n throw new FakeAssertionError(\n `Expected ${JSON.stringify(location)} to be stored${driver ? ` on \"${driver}\"` : \"\"}. Stored files: ${JSON.stringify(storageFake.files())}.`,\n );\n }\n },\n\n /** Assert a file does not exist, on the default driver unless `driver` is given. */\n async assertMissing(location: string, driver?: StorageDriverName): Promise<void> {\n currentRoot();\n\n const target = driver ? storage.use(driver) : storage;\n\n if (await target.exists(location)) {\n throw new FakeAssertionError(\n `Expected ${JSON.stringify(location)} not to be stored${driver ? ` on \"${driver}\"` : \"\"}, but it is.`,\n );\n }\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;AAcA,MAAa,4BAA4B;AAEzC,IAAI;AACJ,IAAI,WAAW;AACf,IAAI,YAAY;AAChB,IAAI,iBAAiB;AAErB,SAAS,cAAsB;CAC7B,IAAI,CAAC,MACH,MAAM,IAAI,mBACR,0JACF;CAGF,OAAO;AACT;AAEA,SAAS,UAAU,WAAmB,MAAwB;CAC5D,IAAI,CAAC,WAAW,SAAS,GAAG,OAAO,CAAC;CAEpC,OAAO,YAAY,WAAW,EAAE,eAAe,KAAK,CAAC,CAAC,CAAC,SAAS,UAAU;EACxE,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,IAAI;EAEhD,OAAO,MAAM,YAAY,IACrB,UAAU,UAAU,IAAI,IACxB,CAAC,KAAK,SAAS,MAAM,QAAQ,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;CAC9D,CAAC;AACH;;;;;;;;;;;;;;;;;AAkBA,MAAa,cAAc;;CAEzB,MAAM,UAAyB;EAC7B,IAAI,CAAC,WAAW;GACd,iBAAiB,QAAQ;GACzB,YAAY;EACd;EAEA,IAAI,CAAC,MAAM;GACT,MAAM,SAAS,QAAQ,IAAI;GAE3B,IAAI,QAAQ;IACV,OAAO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YAAY,MAAM,CAAC,EAAE,EAC5I;CAEJ;;CAGA,MAAM,cAAc,UAAkB,QAA2C;EAC/E,YAAY;EAIZ,IAAI,OAFW,SAAS,QAAQ,IAAI,MAAM,IAAI,QAE9B,CAAC,OAAO,QAAQ,GAC9B,MAAM,IAAI,mBACR,YAAY,KAAK,UAAU,QAAQ,EAAE,mBAAmB,SAAS,QAAQ,OAAO,KAAK,GAAG,aAC1F;CAEJ;AACF"}
1
+ {"version":3,"file":"storage-fake.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/storage-fake.ts"],"sourcesContent":["import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { storage } from \"../../storage\";\nimport { storageConfigurations } from \"../../storage/config\";\nimport type { StorageDriverName } from \"../../storage/types\";\nimport { FakeAssertionError } from \"./fake-assertion-error\";\n\n/**\n * The env var that carries the fake storage root from the process that\n * created it (the HTTP test server, in `globalSetup`) to the test workers it\n * spawns, so both sides read and write the same files. Like\n * `WARLOCK_TEST_SERVER_PORT`, it is plumbing between the kit's own processes.\n */\nexport const TEST_STORAGE_ROOT_ENV_KEY = \"WARLOCK_TEST_STORAGE_ROOT\";\n\nlet root: string | undefined;\nlet ownsRoot = false;\nlet installed = false;\nlet wasInitialized = false;\n\nfunction currentRoot(): string {\n if (!root) {\n throw new FakeAssertionError(\n \"storageFake is not installed. It installs by default in the test environment; check `tests.fakes` in src/config/tests.ts, or call storageFake.install().\",\n );\n }\n\n return root;\n}\n\nfunction listFiles(directory: string, base: string): string[] {\n if (!existsSync(directory)) return [];\n\n return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {\n const absolute = path.join(directory, entry.name);\n\n return entry.isDirectory()\n ? listFiles(absolute, base)\n : [path.relative(base, absolute).split(path.sep).join(\"/\")];\n });\n}\n\n/**\n * Points every configured storage driver — local, S3, R2, Spaces — at a\n * local temporary directory.\n *\n * Installed by default in the test environment: uploads and `storage.put()`\n * calls land on disk under one temp root (a folder per driver name), never in\n * a bucket and never in the app's real `storage/` folder. The root is shared\n * with the HTTP test server, so a file an HTTP request stored is visible to\n * the test that sent it. The process that created the root deletes it on\n * restore.\n *\n * @example\n * await uploadAvatar(user, file);\n *\n * await storageFake.assertExists(`avatars/${user.id}.png`);\n */\nexport const storageFake = {\n /** Re-register every driver as a local one under the temp root. */\n async install(options?: { isolated?: boolean }): Promise<void> {\n if (!installed) {\n wasInitialized = storage.isInitialized;\n installed = true;\n }\n\n if (!root) {\n const shared = options?.isolated ? undefined : process.env[TEST_STORAGE_ROOT_ENV_KEY];\n\n if (shared) {\n root = shared;\n ownsRoot = false;\n } else {\n root = mkdtempSync(path.join(os.tmpdir(), \"warlock-test-storage-\"));\n ownsRoot = true;\n if (!options?.isolated) process.env[TEST_STORAGE_ROOT_ENV_KEY] = root;\n }\n }\n\n await storage.init();\n\n const fakeRoot = root;\n\n for (const name of storage.driverNames()) {\n const driverRoot = path.join(fakeRoot, name);\n\n mkdirSync(driverRoot, { recursive: true });\n storage.register(\n name,\n storageConfigurations.local({ root: driverRoot, urlPrefix: `/test-storage/${name}` }),\n );\n }\n\n const defaultName = storage.getDefaultName();\n\n if (defaultName) storage.setDefault(defaultName);\n },\n\n /** Drop the fake drivers; the real configuration is read again on next use. */\n async restore(): Promise<void> {\n if (!installed) return;\n\n installed = false;\n storage.reset();\n\n if (wasInitialized) await storage.init();\n\n if (root && ownsRoot) {\n rmSync(root, { recursive: true, force: true });\n\n if (process.env[TEST_STORAGE_ROOT_ENV_KEY] === root) {\n delete process.env[TEST_STORAGE_ROOT_ENV_KEY];\n }\n }\n\n root = undefined;\n ownsRoot = false;\n },\n\n isInstalled(): boolean {\n return installed;\n },\n\n /** The temp directory every fake driver lives under. */\n root(): string {\n return currentRoot();\n },\n\n /** Every stored file, as `<driver>/<path>`, sorted. */\n files(driver?: StorageDriverName): string[] {\n const base = currentRoot();\n const directory = driver ? path.join(base, driver) : base;\n\n return listFiles(directory, directory).sort();\n },\n\n /** Assert a file exists, on the default driver unless `driver` is given. */\n async assertExists(location: string, driver?: StorageDriverName): Promise<void> {\n currentRoot();\n\n const target = driver ? storage.use(driver) : storage;\n\n if (!(await target.exists(location))) {\n throw new FakeAssertionError(\n `Expected ${JSON.stringify(location)} to be stored${driver ? ` on \"${driver}\"` : \"\"}. Stored files: ${JSON.stringify(storageFake.files())}.`,\n );\n }\n },\n\n /** Assert a file does not exist, on the default driver unless `driver` is given. */\n async assertMissing(location: string, driver?: StorageDriverName): Promise<void> {\n currentRoot();\n\n const target = driver ? storage.use(driver) : storage;\n\n if (await target.exists(location)) {\n throw new FakeAssertionError(\n `Expected ${JSON.stringify(location)} not to be stored${driver ? ` on \"${driver}\"` : \"\"}, but it is.`,\n );\n }\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;AAcA,MAAa,4BAA4B;AAEzC,IAAI;AACJ,IAAI,WAAW;AACf,IAAI,YAAY;AAChB,IAAI,iBAAiB;AAErB,SAAS,cAAsB;CAC7B,IAAI,CAAC,MACH,MAAM,IAAI,mBACR,0JACF;CAGF,OAAO;AACT;AAEA,SAAS,UAAU,WAAmB,MAAwB;CAC5D,IAAI,CAAC,WAAW,SAAS,GAAG,OAAO,CAAC;CAEpC,OAAO,YAAY,WAAW,EAAE,eAAe,KAAK,CAAC,CAAC,CAAC,SAAS,UAAU;EACxE,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,IAAI;EAEhD,OAAO,MAAM,YAAY,IACrB,UAAU,UAAU,IAAI,IACxB,CAAC,KAAK,SAAS,MAAM,QAAQ,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;CAC9D,CAAC;AACH;;;;;;;;;;;;;;;;;AAkBA,MAAa,cAAc;;CAEzB,MAAM,QAAQ,SAAiD;EAC7D,IAAI,CAAC,WAAW;GACd,iBAAiB,QAAQ;GACzB,YAAY;EACd;EAEA,IAAI,CAAC,MAAM;GACT,MAAM,SAAS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Y,KAAK,UAAU,QAAQ,EAAE,eAAe,SAAS,QAAQ,OAAO,KAAK,GAAG,kBAAkB,KAAK,UAAU,YAAY,MAAM,CAAC,EAAE,EAC5I;CAEJ;;CAGA,MAAM,cAAc,UAAkB,QAA2C;EAC/E,YAAY;EAIZ,IAAI,OAFW,SAAS,QAAQ,IAAI,MAAM,IAAI,QAE9B,CAAC,OAAO,QAAQ,GAC9B,MAAM,IAAI,mBACR,YAAY,KAAK,UAAU,QAAQ,EAAE,mBAAmB,SAAS,QAAQ,OAAO,KAAK,GAAG,aAC1F;CAEJ;AACF"}
@@ -26,7 +26,9 @@ export declare function resolveTestFakes(explicit?: TestFakesSelection): TestFak
26
26
  *
27
27
  * @returns the fakes that are now installed.
28
28
  */
29
- export declare function installTestFakes(explicit?: TestFakesSelection): Promise<TestFakeName[]>;
29
+ export declare function installTestFakes(explicit?: TestFakesSelection, options?: {
30
+ isolatedStorage?: boolean;
31
+ }): Promise<TestFakeName[]>;
30
32
  /**
31
33
  * Restore every installed fake, in reverse order. Every fake is restored even
32
34
  * when one fails; the failures are rethrown together afterwards.
@@ -1 +1 @@
1
- {"version":3,"file":"test-fakes.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"mappings":";;qBAWa;YAUD,uBAAuB;;;;;;;;;YAUvB,+BAA+B,QAAQ,OAAO;;wBAkB1C,uBAAuB;;;;;;wBA0CvB,iBAAiB,WAAW,qBAAqB;;;;;;;;wBAiB3C,iBAAiB,WAAW,qBAAqB,QAAQ;;;;;wBAgBzD,oBAAoB;;wBAiB1B,sBAAsB"}
1
+ {"version":3,"file":"test-fakes.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"mappings":";;qBAWa;YAUD,uBAAuB;;;;;;;;;YAUvB,+BAA+B,QAAQ,OAAO;;wBAkB1C,uBAAuB;;;;;;wBA0CvB,iBAAiB,WAAW,qBAAqB;;;;;;;;wBAiB3C,iBACpB,WAAW,oBACX;EAAY;IACX,QAAQ;;;;;wBAiBW,oBAAoB;;wBAiB1B,sBAAsB"}
@@ -63,9 +63,10 @@ function resolveTestFakes(explicit) {
63
63
  *
64
64
  * @returns the fakes that are now installed.
65
65
  */
66
- async function installTestFakes(explicit) {
66
+ async function installTestFakes(explicit, options) {
67
67
  const selected = resolveTestFakes(explicit);
68
- for (const name of selected) await fakes[name].install();
68
+ for (const name of selected) if (name === "storage") await storageFake.install({ isolated: options?.isolatedStorage });
69
+ else await fakes[name].install();
69
70
  active = [.../* @__PURE__ */ new Set([...active, ...selected])];
70
71
  return selected;
71
72
  }
@@ -1 +1 @@
1
- {"version":3,"file":"test-fakes.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"sourcesContent":["import type { GenericObject } from \"@mongez/reinforcements\";\nimport { config } from \"../../config\";\nimport { cacheFake } from \"./cache-fake\";\nimport { clockFake } from \"./clock-fake\";\nimport { idsFake } from \"./ids-fake\";\nimport { mailFake } from \"./mail-fake\";\nimport { queueFake } from \"./queue-fake\";\nimport { secretsFake } from \"./secrets-fake\";\nimport { storageFake } from \"./storage-fake\";\n\n/** The fakes the test kit installs. */\nexport const TEST_FAKE_NAMES = [\n \"mail\",\n \"queue\",\n \"cache\",\n \"storage\",\n \"clock\",\n \"ids\",\n \"secrets\",\n] as const;\n\nexport type TestFakeName = (typeof TEST_FAKE_NAMES)[number];\n\n/**\n * Which fakes to install.\n *\n * - `true` (the default) — all of them.\n * - `false` — none: real drivers, real clock, real ids, real secret storage.\n * - an object — all of them except the ones set to `false`, e.g.\n * `{ cache: false }` keeps the configured cache driver.\n */\nexport type TestFakesSelection = boolean | Partial<Record<TestFakeName, boolean>>;\n\nconst fakes: Record<\n TestFakeName,\n { install(): void | Promise<void>; restore(): void | Promise<void> }\n> = {\n mail: mailFake,\n queue: queueFake,\n cache: cacheFake,\n storage: storageFake,\n clock: clockFake,\n ids: idsFake,\n secrets: secretsFake,\n};\n\nlet active: TestFakeName[] = [];\n\n/** Read `tests.fakes` from `src/config/tests.ts`, or `undefined` when unset. */\nexport function readConfiguredFakes(): TestFakesSelection | undefined {\n // `config.get` resolves an absent key to `null`, not to its default's shape.\n const testsConfig = config.get<GenericObject>(\"tests\", {}) ?? {};\n\n return validateSelection(testsConfig.fakes as unknown, \"tests.fakes\");\n}\n\nfunction validateSelection(value: unknown, source: string): TestFakesSelection | undefined {\n if (value === undefined || typeof value === \"boolean\") return value;\n\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\n `${source} must be true, false, or an object such as { cache: false }; got ${JSON.stringify(value)}.`,\n );\n }\n\n const selection: Partial<Record<TestFakeName, boolean>> = {};\n\n for (const [key, flag] of Object.entries(value)) {\n const name = TEST_FAKE_NAMES.find((candidate) => candidate === key);\n\n if (!name) {\n throw new Error(\n `${source} has an unknown fake \"${key}\". Known fakes: ${TEST_FAKE_NAMES.join(\", \")}.`,\n );\n }\n\n if (typeof flag !== \"boolean\") {\n throw new Error(`${source}.${key} must be true or false; got ${JSON.stringify(flag)}.`);\n }\n\n selection[name] = flag;\n }\n\n return selection;\n}\n\n/**\n * The fakes to install. Precedence: an explicit selection (the `fakes`\n * option of `setupTest()` / `startHttpTestServer()`) > `tests.fakes` in\n * `src/config/tests.ts` > all on.\n */\nexport function resolveTestFakes(explicit?: TestFakesSelection): TestFakeName[] {\n const selection =\n explicit !== undefined ? validateSelection(explicit, \"fakes\") : readConfiguredFakes();\n\n if (selection === undefined || selection === true) return [...TEST_FAKE_NAMES];\n if (selection === false) return [];\n\n return TEST_FAKE_NAMES.filter((name) => selection[name] !== false);\n}\n\n/**\n * Install the selected fakes. Called by `setupTest()` and\n * `startHttpTestServer()` once their connectors are up; call it yourself only\n * when you bootstrap the framework without them.\n *\n * @returns the fakes that are now installed.\n */\nexport async function installTestFakes(explicit?: TestFakesSelection): Promise<TestFakeName[]> {\n const selected = resolveTestFakes(explicit);\n\n for (const name of selected) {\n await fakes[name].install();\n }\n\n active = [...new Set([...active, ...selected])];\n\n return selected;\n}\n\n/**\n * Restore every installed fake, in reverse order. Every fake is restored even\n * when one fails; the failures are rethrown together afterwards.\n */\nexport async function restoreTestFakes(): Promise<void> {\n const errors: unknown[] = [];\n\n for (const name of [...active].reverse()) {\n try {\n await fakes[name].restore();\n } catch (error) {\n errors.push(error);\n }\n }\n\n active = [];\n\n if (errors.length > 0) throw new AggregateError(errors, \"Restoring the test fakes failed.\");\n}\n\n/** The fakes installed right now. */\nexport function installedTestFakes(): TestFakeName[] {\n return [...active];\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAcA,MAAM,QAGF;CACF,MAAM;CACN,OAAO;CACP,OAAO;CACP,SAAS;CACT,OAAO;CACP,KAAK;CACL,SAAS;AACX;AAEA,IAAI,SAAyB,CAAC;;AAG9B,SAAgB,sBAAsD;CAIpE,OAAO,mBAFa,OAAO,IAAmB,SAAS,CAAC,CAAC,KAAK,CAAC,EAE3B,CAAC,OAAkB,aAAa;AACtE;AAEA,SAAS,kBAAkB,OAAgB,QAAgD;CACzF,IAAI,UAAU,UAAa,OAAO,UAAU,WAAW,OAAO;CAE9D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MACR,GAAG,OAAO,mEAAmE,KAAK,UAAU,KAAK,EAAE,EACrG;CAGF,MAAM,YAAoD,CAAC;CAE3D,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAK,GAAG;EAC/C,MAAM,OAAO,gBAAgB,MAAM,cAAc,cAAc,GAAG;EAElE,IAAI,CAAC,MACH,MAAM,IAAI,MACR,GAAG,OAAO,wBAAwB,IAAI,kBAAkB,gBAAgB,KAAK,IAAI,EAAE,EACrF;EAGF,IAAI,OAAO,SAAS,WAClB,MAAM,IAAI,MAAM,GAAG,OAAO,GAAG,IAAI,8BAA8B,KAAK,UAAU,IAAI,EAAE,EAAE;EAGxF,UAAU,QAAQ;CACpB;CAEA,OAAO;AACT;;;;;;AAOA,SAAgB,iBAAiB,UAA+C;CAC9E,MAAM,YACJ,aAAa,SAAY,kBAAkB,UAAU,OAAO,IAAI,oBAAoB;CAEtF,IAAI,cAAc,UAAa,cAAc,MAAM,OAAO,CAAC,GAAG,eAAe;CAC7E,IAAI,cAAc,OAAO,OAAO,CAAC;CAEjC,OAAO,gBAAgB,QAAQ,SAAS,UAAU,UAAU,KAAK;AACnE;;;;;;;;AASA,eAAsB,iBAAiB,UAAwD;CAC7F,MAAM,WAAW,iBAAiB,QAAQ;CAE1C,KAAK,MAAM,QAAQ,UACjB,MAAM,MAAM,KAAK,CAAC,QAAQ;CAG5B,SAAS,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,QAAQ,GAAG,QAAQ,CAAC,CAAC;CAE9C,OAAO;AACT;;;;;AAMA,eAAsB,mBAAkC;CACtD,MAAM,SAAoB,CAAC;CAE3B,KAAK,MAAM,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,GACrC,IAAI;EACF,MAAM,MAAM,KAAK,CAAC,QAAQ;CAC5B,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAGF,SAAS,CAAC;CAEV,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,kCAAkC;AAC5F;;AAGA,SAAgB,qBAAqC;CACnD,OAAO,CAAC,GAAG,MAAM;AACnB"}
1
+ {"version":3,"file":"test-fakes.mjs","names":[],"sources":["../../../../../../../../../packages/core/src/tests/fakes/test-fakes.ts"],"sourcesContent":["import type { GenericObject } from \"@mongez/reinforcements\";\nimport { config } from \"../../config\";\nimport { cacheFake } from \"./cache-fake\";\nimport { clockFake } from \"./clock-fake\";\nimport { idsFake } from \"./ids-fake\";\nimport { mailFake } from \"./mail-fake\";\nimport { queueFake } from \"./queue-fake\";\nimport { secretsFake } from \"./secrets-fake\";\nimport { storageFake } from \"./storage-fake\";\n\n/** The fakes the test kit installs. */\nexport const TEST_FAKE_NAMES = [\n \"mail\",\n \"queue\",\n \"cache\",\n \"storage\",\n \"clock\",\n \"ids\",\n \"secrets\",\n] as const;\n\nexport type TestFakeName = (typeof TEST_FAKE_NAMES)[number];\n\n/**\n * Which fakes to install.\n *\n * - `true` (the default) — all of them.\n * - `false` — none: real drivers, real clock, real ids, real secret storage.\n * - an object — all of them except the ones set to `false`, e.g.\n * `{ cache: false }` keeps the configured cache driver.\n */\nexport type TestFakesSelection = boolean | Partial<Record<TestFakeName, boolean>>;\n\nconst fakes: Record<\n TestFakeName,\n { install(): void | Promise<void>; restore(): void | Promise<void> }\n> = {\n mail: mailFake,\n queue: queueFake,\n cache: cacheFake,\n storage: storageFake,\n clock: clockFake,\n ids: idsFake,\n secrets: secretsFake,\n};\n\nlet active: TestFakeName[] = [];\n\n/** Read `tests.fakes` from `src/config/tests.ts`, or `undefined` when unset. */\nexport function readConfiguredFakes(): TestFakesSelection | undefined {\n // `config.get` resolves an absent key to `null`, not to its default's shape.\n const testsConfig = config.get<GenericObject>(\"tests\", {}) ?? {};\n\n return validateSelection(testsConfig.fakes as unknown, \"tests.fakes\");\n}\n\nfunction validateSelection(value: unknown, source: string): TestFakesSelection | undefined {\n if (value === undefined || typeof value === \"boolean\") return value;\n\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\n `${source} must be true, false, or an object such as { cache: false }; got ${JSON.stringify(value)}.`,\n );\n }\n\n const selection: Partial<Record<TestFakeName, boolean>> = {};\n\n for (const [key, flag] of Object.entries(value)) {\n const name = TEST_FAKE_NAMES.find((candidate) => candidate === key);\n\n if (!name) {\n throw new Error(\n `${source} has an unknown fake \"${key}\". Known fakes: ${TEST_FAKE_NAMES.join(\", \")}.`,\n );\n }\n\n if (typeof flag !== \"boolean\") {\n throw new Error(`${source}.${key} must be true or false; got ${JSON.stringify(flag)}.`);\n }\n\n selection[name] = flag;\n }\n\n return selection;\n}\n\n/**\n * The fakes to install. Precedence: an explicit selection (the `fakes`\n * option of `setupTest()` / `startHttpTestServer()`) > `tests.fakes` in\n * `src/config/tests.ts` > all on.\n */\nexport function resolveTestFakes(explicit?: TestFakesSelection): TestFakeName[] {\n const selection =\n explicit !== undefined ? validateSelection(explicit, \"fakes\") : readConfiguredFakes();\n\n if (selection === undefined || selection === true) return [...TEST_FAKE_NAMES];\n if (selection === false) return [];\n\n return TEST_FAKE_NAMES.filter((name) => selection[name] !== false);\n}\n\n/**\n * Install the selected fakes. Called by `setupTest()` and\n * `startHttpTestServer()` once their connectors are up; call it yourself only\n * when you bootstrap the framework without them.\n *\n * @returns the fakes that are now installed.\n */\nexport async function installTestFakes(\n explicit?: TestFakesSelection,\n options?: { isolatedStorage?: boolean },\n): Promise<TestFakeName[]> {\n const selected = resolveTestFakes(explicit);\n\n for (const name of selected) {\n if (name === \"storage\") await storageFake.install({ isolated: options?.isolatedStorage });\n else await fakes[name].install();\n }\n\n active = [...new Set([...active, ...selected])];\n\n return selected;\n}\n\n/**\n * Restore every installed fake, in reverse order. Every fake is restored even\n * when one fails; the failures are rethrown together afterwards.\n */\nexport async function restoreTestFakes(): Promise<void> {\n const errors: unknown[] = [];\n\n for (const name of [...active].reverse()) {\n try {\n await fakes[name].restore();\n } catch (error) {\n errors.push(error);\n }\n }\n\n active = [];\n\n if (errors.length > 0) throw new AggregateError(errors, \"Restoring the test fakes failed.\");\n}\n\n/** The fakes installed right now. */\nexport function installedTestFakes(): TestFakeName[] {\n return [...active];\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAcA,MAAM,QAGF;CACF,MAAM;CACN,OAAO;CACP,OAAO;CACP,SAAS;CACT,OAAO;CACP,KAAK;CACL,SAAS;AACX;AAEA,IAAI,SAAyB,CAAC;;AAG9B,SAAgB,sBAAsD;CAIpE,OAAO,mBAFa,OAAO,IAAmB,SAAS,CAAC,CAAC,KAAK,CAAC,EAE3B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AsB,mBAAkC;CACtD,MAAM,SAAoB,CAAC;CAE3B,KAAK,MAAM,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,GACrC,IAAI;EACF,MAAM,MAAM,KAAK,CAAC,QAAQ;CAC5B,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAGF,SAAS,CAAC;CAEV,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,kCAAkC;AAC5F;;AAGA,SAAgB,qBAAqC;CACnD,OAAO,CAAC,GAAG,MAAM;AACnB"}
@@ -4,7 +4,7 @@ import { StartHttpTestServerOptions, isTestServerRunning, startHttpTestServer, s
4
4
  import { TestRequestClient, createTestRequestClient, expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
5
5
  import { AuthenticatedTestClient, TestAuthenticableUser, actingAs } from "./authenticated-test-client.mjs";
6
6
  import { TestConnectorsSelection } from "./test-connectors-selection.mjs";
7
- import { TestLifecycleError, TestSetupOptions, setupTest, teardownTest, warnMissingImportModule } from "./vitest-setup.mjs";
7
+ import { TestLifecycleError, TestRuntimeConfiguration, TestSetupOptions, setupTest, teardownTest, warnMissingImportModule } from "./vitest-setup.mjs";
8
8
  import { cacheFake } from "./fakes/cache-fake.mjs";
9
9
  import { DEFAULT_FAKE_NOW, clockFake } from "./fakes/clock-fake.mjs";
10
10
  import { FakeAssertionError, describeRecorded } from "./fakes/fake-assertion-error.mjs";
@@ -17,4 +17,6 @@ import "./fakes/index.mjs";
17
17
  import { Factory, FactoryAttributes, FactoryOverrides, FactorySeed, FactoryState, defineFactory, resetFactorySequences } from "./factories.mjs";
18
18
  import { CreateTestHttpServerOptions, TestHttpServer, createTestHttpServer } from "./test-http-server.mjs";
19
19
  import { REDACTED, ResponseSnapshot, SnapshotResponseOptions, snapshotResponse } from "./snapshot-response.mjs";
20
- export { AuthenticatedTestClient, CreateTestHttpServerOptions, DEFAULT_FAKE_NOW, Factory, FactoryAttributes, FactoryOverrides, FactorySeed, FactoryState, FakeAssertionError, JobReference, MailMatcher, PushedJob, PushedJobMatcher, REDACTED, ResponseSnapshot, SnapshotResponseOptions, StartHttpTestServerOptions, TEST_FAKE_NAMES, TestAuthenticableUser, type TestConnectorsSelection, TestFakeName, TestFakesSelection, TestHttpServer, TestLifecycleError, TestRequestClient, TestSetupOptions, actingAs, assertPortIsAvailable, cacheFake, clockFake, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, secretsFake, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
20
+ import { ResponseContractCase, ResponseContractOptions, ResponseContractRoute, assertResponseContracts } from "./response-contract.mjs";
21
+ import { TestWorkerConfiguration, configureTestWorker, getTestRuntimeStats } from "./test-runtime-scope.mjs";
22
+ export { AuthenticatedTestClient, CreateTestHttpServerOptions, DEFAULT_FAKE_NOW, Factory, FactoryAttributes, FactoryOverrides, FactorySeed, FactoryState, FakeAssertionError, JobReference, MailMatcher, PushedJob, PushedJobMatcher, REDACTED, ResponseContractCase, ResponseContractOptions, ResponseContractRoute, ResponseSnapshot, SnapshotResponseOptions, StartHttpTestServerOptions, TEST_FAKE_NAMES, TestAuthenticableUser, type TestConnectorsSelection, TestFakeName, TestFakesSelection, TestHttpServer, TestLifecycleError, TestRequestClient, TestRuntimeConfiguration, TestSetupOptions, type TestWorkerConfiguration, actingAs, assertPortIsAvailable, assertResponseContracts, cacheFake, clockFake, configureTestWorker, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestRuntimeStats, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, secretsFake, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
@@ -11,10 +11,12 @@ import { TEST_FAKE_NAMES, installTestFakes, installedTestFakes, readConfiguredFa
11
11
  import { isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
12
12
  import { createTestRequestClient, expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
13
13
  import { actingAs } from "./authenticated-test-client.mjs";
14
+ import { configureTestWorker, getTestRuntimeStats } from "./test-runtime-scope.mjs";
14
15
  import { TestLifecycleError, setupTest, teardownTest, warnMissingImportModule } from "./vitest-setup.mjs";
15
16
  import "./fakes/index.mjs";
16
17
  import { defineFactory, resetFactorySequences } from "./factories.mjs";
17
18
  import { createTestHttpServer } from "./test-http-server.mjs";
18
19
  import { REDACTED, snapshotResponse } from "./snapshot-response.mjs";
20
+ import { assertResponseContracts } from "./response-contract.mjs";
19
21
 
20
- export { DEFAULT_FAKE_NOW, FakeAssertionError, REDACTED, TEST_FAKE_NAMES, TestLifecycleError, actingAs, assertPortIsAvailable, cacheFake, clockFake, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, secretsFake, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
22
+ export { DEFAULT_FAKE_NOW, FakeAssertionError, REDACTED, TEST_FAKE_NAMES, TestLifecycleError, actingAs, assertPortIsAvailable, assertResponseContracts, cacheFake, clockFake, configureTestWorker, createTestHttpServer, createTestRequestClient, defineFactory, describeRecorded, expectJson, getTestRuntimeStats, getTestServerUrl, idsFake, installTestFakes, installedTestFakes, isPortAvailable, isTestServerRunning, mailFake, parseJsonResponse, queueFake, readConfiguredFakes, resetFactorySequences, resolveTestFakes, restoreTestFakes, secretsFake, setupTest, snapshotResponse, startHttpTestServer, stopHttpTestServer, storageFake, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
@@ -0,0 +1,24 @@
1
+ import { setConfig } from "../config/config-setter.mjs";
2
+ import { srcPath } from "../utils/paths.mjs";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { readdir } from "node:fs/promises";
6
+
7
+ //#region ../../packages/core/src/tests/load-unit-config.ts
8
+ /** Unit mode registers values only: no special handlers or connector side effects. */
9
+ async function loadUnitConfig(importModule) {
10
+ const directory = srcPath("config");
11
+ const files = await readdir(directory, { withFileTypes: true }).catch((error) => {
12
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
13
+ throw error;
14
+ });
15
+ for (const file of files.sort((left, right) => left.name.localeCompare(right.name))) {
16
+ if (!file.isFile() || !/\.(?:ts|mjs|js)$/.test(file.name) || file.name.endsWith(".d.ts")) continue;
17
+ const loaded = await importModule(pathToFileURL(path.join(directory, file.name)).href);
18
+ if (typeof loaded === "object" && loaded !== null && "default" in loaded) setConfig(file.name.replace(/\.(?:ts|mjs|js)$/, ""), loaded.default);
19
+ }
20
+ }
21
+
22
+ //#endregion
23
+ export { loadUnitConfig };
24
+ //# sourceMappingURL=load-unit-config.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-unit-config.mjs","names":[],"sources":["../../../../../../../../packages/core/src/tests/load-unit-config.ts"],"sourcesContent":["import { readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { setConfig } from \"../config/config-setter\";\nimport type { AppModuleImporter } from \"../loader/app-module-importer\";\nimport { srcPath } from \"../utils/paths\";\n\n/** Unit mode registers values only: no special handlers or connector side effects. */\nexport async function loadUnitConfig(importModule: AppModuleImporter): Promise<void> {\n const directory = srcPath(\"config\");\n const files = await readdir(directory, { withFileTypes: true }).catch((error: unknown) => {\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\")\n return [];\n throw error;\n });\n for (const file of files.sort((left, right) => left.name.localeCompare(right.name))) {\n if (!file.isFile() || !/\\.(?:ts|mjs|js)$/.test(file.name) || file.name.endsWith(\".d.ts\"))\n continue;\n const loaded = await importModule(pathToFileURL(path.join(directory, file.name)).href);\n if (typeof loaded === \"object\" && loaded !== null && \"default\" in loaded) {\n setConfig(file.name.replace(/\\.(?:ts|mjs|js)$/, \"\"), loaded.default);\n }\n }\n}\n"],"mappings":";;;;;;;;AAQA,eAAsB,eAAe,cAAgD;CACnF,MAAM,YAAY,QAAQ,QAAQ;CAClC,MAAM,QAAQ,MAAM,QAAQ,WAAW,EAAE,eAAe,KAAK,CAAC,CAAC,CAAC,OAAO,UAAmB;EACxF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,MAAM,SAAS,UACnF,OAAO,CAAC;EACV,MAAM;CACR,CAAC;CACD,KAAK,MAAM,QAAQ,MAAM,MAAM,MAAM,UAAU,KAAK,KAAK,cAAc,MAAM,IAAI,CAAC,GAAG;EACnF,IAAI,CAAC,KAAK,OAAO,KAAK,CAAC,mBAAmB,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK,SAAS,OAAO,GACrF;EACF,MAAM,SAAS,MAAM,aAAa,cAAc,KAAK,KAAK,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI;EACrF,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,aAAa,QAChE,UAAU,KAAK,KAAK,QAAQ,oBAAoB,EAAE,GAAG,OAAO,OAAO;CAEvE;AACF"}
@@ -0,0 +1,32 @@
1
+ import { RequestMethod, Route } from "../router/types.mjs";
2
+ //#region ../../packages/core/src/tests/response-contract.d.ts
3
+ export type ResponseContractRoute = Pick<Route, "method" | "path" | "handler">;
4
+ export type ResponseContractCase = {
5
+ /** Concrete HTTP method for an `all` route. */
6
+ method?: Exclude<RequestMethod, "all">;
7
+ /** Concrete path, including query values, for parameterized routes. */
8
+ path?: string;
9
+ init?: Omit<RequestInit, "method">;
10
+ /** Assert the intended scenario's status as well as its body. */
11
+ status?: number;
12
+ };
13
+ export type ResponseContractOptions = {
14
+ /** Defaults to registered routes with responseSchema in this process. */
15
+ routes?: readonly ResponseContractRoute[];
16
+ /** Required for parameterized routes and methods other than GET. No cases are skipped. */
17
+ cases?: (route: ResponseContractRoute) => readonly ResponseContractCase[];
18
+ /** Use an in-process server or an authenticated client; defaults to testRequest. */
19
+ client?: {
20
+ request(path: string, init?: RequestInit): Promise<Response>;
21
+ };
22
+ /** Require fixtures to exercise every declared status. Defaults to false. */
23
+ requireAllStatuses?: boolean;
24
+ };
25
+ /**
26
+ * Call real HTTP routes and check their serialized bodies against responseSchema.
27
+ * Throws on undeclared statuses, mismatches, empty discovery or unsupported shapes.
28
+ * Additional response fields are allowed, as in Core's OpenAPI declarations.
29
+ */
30
+ export declare function assertResponseContracts(options?: ResponseContractOptions): Promise<void>;
31
+ //#endregion
32
+ //# sourceMappingURL=response-contract.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-contract.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/tests/response-contract.ts"],"mappings":";;YAOY,wBAAwB,KAAK;YAC7B;;EAEV,SAAS,QAAQ;;EAEjB;EACA,OAAO,KAAK;;EAEZ;;YAEU;;EAEV,kBAAkB;;EAElB,SAAS,OAAO,mCAAmC;;EAEnD;IAAW,QAAQ,cAAc,OAAO,cAAc,QAAQ;;;EAE9D;;;;;;;wBA4EoB,wBACpB,UAAS,0BACR"}