@warlock.js/core 5.10.0 → 5.12.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 (130) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/esm/application/app.d.mts +3 -3
  3. package/esm/application/app.mjs +6 -6
  4. package/esm/application/app.mjs.map +1 -1
  5. package/esm/cli/cli-commands.utils.mjs +7 -3
  6. package/esm/cli/cli-commands.utils.mjs.map +1 -1
  7. package/esm/cli/commands/doctor/checks/health.check.mjs +1 -1
  8. package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -1
  9. package/esm/connectors/socket-connector.mjs +13 -16
  10. package/esm/connectors/socket-connector.mjs.map +1 -1
  11. package/esm/container/index.d.mts +20 -7
  12. package/esm/container/index.d.mts.map +1 -1
  13. package/esm/container/index.mjs +8 -5
  14. package/esm/container/index.mjs.map +1 -1
  15. package/esm/dev-server/dev-logger.mjs +15 -3
  16. package/esm/dev-server/dev-logger.mjs.map +1 -1
  17. package/esm/dev-server/development-server.mjs +1 -1
  18. package/esm/dev-server/development-server.mjs.map +1 -1
  19. package/esm/dev-server/file-event-handler.mjs +50 -9
  20. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  21. package/esm/dev-server/file-manager.d.mts +8 -0
  22. package/esm/dev-server/file-manager.d.mts.map +1 -1
  23. package/esm/dev-server/file-manager.mjs +26 -4
  24. package/esm/dev-server/file-manager.mjs.map +1 -1
  25. package/esm/dev-server/files-orchestrator.mjs +3 -3
  26. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  27. package/esm/dev-server/files-watcher.mjs +16 -2
  28. package/esm/dev-server/files-watcher.mjs.map +1 -1
  29. package/esm/dev-server/flags.mjs +16 -1
  30. package/esm/dev-server/flags.mjs.map +1 -1
  31. package/esm/dev-server/layer-executor.mjs +27 -3
  32. package/esm/dev-server/layer-executor.mjs.map +1 -1
  33. package/esm/errors/container-key-missing-error.mjs +18 -6
  34. package/esm/errors/container-key-missing-error.mjs.map +1 -1
  35. package/esm/generations/stubs.mjs +10 -10
  36. package/esm/generations/stubs.mjs.map +1 -1
  37. package/esm/http/context/request-context.d.mts +14 -11
  38. package/esm/http/context/request-context.d.mts.map +1 -1
  39. package/esm/http/context/request-context.mjs +13 -9
  40. package/esm/http/context/request-context.mjs.map +1 -1
  41. package/esm/http/createHttpApplication.d.mts.map +1 -1
  42. package/esm/http/createHttpApplication.mjs +2 -0
  43. package/esm/http/createHttpApplication.mjs.map +1 -1
  44. package/esm/http/csp.d.mts +139 -0
  45. package/esm/http/csp.d.mts.map +1 -0
  46. package/esm/http/csp.mjs +134 -0
  47. package/esm/http/csp.mjs.map +1 -0
  48. package/esm/http/errors/errors.d.mts +17 -1
  49. package/esm/http/errors/errors.d.mts.map +1 -1
  50. package/esm/http/errors/errors.mjs +20 -1
  51. package/esm/http/errors/errors.mjs.map +1 -1
  52. package/esm/http/index.d.mts +8 -3
  53. package/esm/http/index.mjs +6 -1
  54. package/esm/http/middleware/concurrency-limit.middleware.d.mts +2 -2
  55. package/esm/http/middleware/concurrency-limit.middleware.mjs +1 -1
  56. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  57. package/esm/http/middleware/inject-request-context.d.mts +1 -1
  58. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  59. package/esm/http/middleware/inject-request-context.mjs +10 -0
  60. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  61. package/esm/http/middleware/rate-limit.middleware.d.mts +1 -1
  62. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  63. package/esm/http/middleware/utils/idempotency-key.d.mts.map +1 -1
  64. package/esm/http/middleware/utils/idempotency-key.mjs +13 -13
  65. package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
  66. package/esm/http/request-controller.d.mts +1 -1
  67. package/esm/http/request.d.mts +32 -44
  68. package/esm/http/request.d.mts.map +1 -1
  69. package/esm/http/request.mjs +52 -44
  70. package/esm/http/request.mjs.map +1 -1
  71. package/esm/http/response.d.mts +18 -0
  72. package/esm/http/response.d.mts.map +1 -1
  73. package/esm/http/response.mjs +31 -0
  74. package/esm/http/response.mjs.map +1 -1
  75. package/esm/http/stream-react-response.d.mts +65 -0
  76. package/esm/http/stream-react-response.d.mts.map +1 -0
  77. package/esm/http/stream-react-response.mjs +46 -0
  78. package/esm/http/stream-react-response.mjs.map +1 -0
  79. package/esm/http/tracing/index.mjs +4 -0
  80. package/esm/http/tracing/trace-id.d.mts +14 -0
  81. package/esm/http/tracing/trace-id.d.mts.map +1 -0
  82. package/esm/http/tracing/trace-id.mjs +37 -0
  83. package/esm/http/tracing/trace-id.mjs.map +1 -0
  84. package/esm/http/tracing/tracing-dispatcher.d.mts +42 -0
  85. package/esm/http/tracing/tracing-dispatcher.d.mts.map +1 -0
  86. package/esm/http/tracing/tracing-dispatcher.mjs +94 -0
  87. package/esm/http/tracing/tracing-dispatcher.mjs.map +1 -0
  88. package/esm/http/tracing/tracing.type.d.mts +66 -0
  89. package/esm/http/tracing/tracing.type.d.mts.map +1 -0
  90. package/esm/http/types.d.mts +27 -21
  91. package/esm/http/types.d.mts.map +1 -1
  92. package/esm/index.d.mts +9 -4
  93. package/esm/index.mjs +6 -2
  94. package/esm/production/esbuild-preflight.mjs +47 -0
  95. package/esm/production/esbuild-preflight.mjs.map +1 -0
  96. package/esm/production/production-builder.mjs +19 -15
  97. package/esm/production/production-builder.mjs.map +1 -1
  98. package/esm/restful/restful.d.mts +1 -1
  99. package/esm/router/log-request-lifecycle.mjs +12 -2
  100. package/esm/router/log-request-lifecycle.mjs.map +1 -1
  101. package/esm/router/router.d.mts.map +1 -1
  102. package/esm/router/router.mjs +10 -0
  103. package/esm/router/router.mjs.map +1 -1
  104. package/esm/router/types.d.mts +1 -1
  105. package/esm/socket/utils.mjs +1 -2
  106. package/esm/socket/utils.mjs.map +1 -1
  107. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  108. package/esm/storage/drivers/cloud-driver.mjs +2 -5
  109. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  110. package/esm/warlock-config/types.d.mts +12 -0
  111. package/esm/warlock-config/types.d.mts.map +1 -1
  112. package/llms-full.txt +315 -25
  113. package/llms.txt +1 -0
  114. package/package.json +12 -12
  115. package/skills/add-connector/SKILL.md +1 -1
  116. package/skills/build-restful/SKILL.md +2 -2
  117. package/skills/configure-app/SKILL.md +31 -0
  118. package/skills/create-controller/SKILL.md +4 -4
  119. package/skills/request-tracing/SKILL.md +208 -0
  120. package/skills/send-response/SKILL.md +16 -0
  121. package/skills/store-file/SKILL.md +1 -1
  122. package/skills/upload-file/SKILL.md +14 -2
  123. package/skills/use-app-context/SKILL.md +2 -2
  124. package/skills/use-middleware/SKILL.md +2 -2
  125. package/skills/use-repository/SKILL.md +1 -1
  126. package/skills/use-request-locals/SKILL.md +1 -1
  127. package/skills/validate-input/SKILL.md +13 -0
  128. package/skills/wire-socket/SKILL.md +3 -3
  129. package/skills/write-middleware/SKILL.md +11 -5
  130. package/skills/write-use-case/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n ensureDirectoryAsync,\r\n fileExistsAsync,\r\n getFileAsync,\r\n getJsonFileAsync,\r\n putFileAsync,\r\n removeDirectoryAsync,\r\n} from \"@warlock.js/fs\";\r\nimport esbuild from \"esbuild\";\r\nimport glob from \"fast-glob\";\r\nimport path from \"path\";\r\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\r\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\r\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\r\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\r\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\r\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport {\r\n commitDistAsync,\r\n createTempOutputDir,\r\n rollbackDistAsync,\r\n stageDistAsync,\r\n type StagedDist,\r\n} from \"./promote-dist\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\r\n\r\n/**\r\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\r\n *\r\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\r\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\r\n * esbuild substitutes a stub that throws — **after the build has reported\r\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\r\n * firing, and it is the defect this shim removes.\r\n *\r\n * `__dirname` matters as much as `require`: without it a dependency resolving\r\n * an asset path silently gets `undefined` and fails later, further from the\r\n * cause.\r\n *\r\n * Written as one line because esbuild inserts a banner verbatim above the\r\n * bundle and a multi-line string here would shift every mapped line.\r\n */\r\nconst ESM_INTEROP_SHIM =\r\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\r\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\r\n \"import{dirname as __wlDirname}from'node:path';\" +\r\n \"const require=__wlCreateRequire(import.meta.url);\" +\r\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\r\n \"const __dirname=__wlDirname(__filename);\";\r\n\r\n/**\r\n * Combine the framework's banner with the user's, keeping both.\r\n *\r\n * esbuild's `banner` is an object keyed by output type, and every merge in the\r\n * path to it — the config merge and the options spread — REPLACES that object\r\n * rather than merging it. So whichever is applied second silently deletes the\r\n * other. This is the only place the two can coexist.\r\n *\r\n * The shim goes first: it defines `require`, which a user banner may use.\r\n *\r\n * @param userBanner banner from `warlock.config.ts`, if any\r\n * @param shim the interop shim, or undefined when it does not apply\r\n */\r\nfunction mergeBanner(\r\n userBanner: Record<string, string> | undefined,\r\n shim: string | undefined,\r\n): Record<string, string> | undefined {\r\n if (!shim) return userBanner;\r\n\r\n const userJs = userBanner?.js;\r\n\r\n return {\r\n ...userBanner,\r\n js: userJs ? `${shim}${userJs}` : shim,\r\n };\r\n}\r\n\r\n/**\r\n * Prefix every generated file uses to reach the app root.\r\n *\r\n * Generated sources are written into `.warlock/production/`, two levels below\r\n * the app root, so `../../` lands back on it — the same hop already spelled\r\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\r\n * config-loader generators emit. Named once so a generator that needs a new\r\n * app-root file (`warlock.config`) cannot pick a different depth.\r\n */\r\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\r\n\r\n/**\r\n * Production Builder\r\n * Generates production-ready files and bundles them for deployment\r\n * Build options are loaded from warlock.config.ts\r\n */\r\nexport class ProductionBuilder {\r\n private options!: ResolvedBuildConfig;\r\n private readonly productionDir = warlockPath(\"production\");\r\n\r\n /**\r\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\r\n * never calls `boot()`/`start()` on them; it only\r\n * drains their `build` contributions.\r\n */\r\n private connectors: readonly Connector[] = [];\r\n\r\n /**\r\n * The contributors' merged esbuild patch, produced by the `generate` pass\r\n * and consumed by {@link bundle}.\r\n */\r\n private contributedEsbuild: ConnectorEsbuildPatch = {};\r\n\r\n /**\r\n * Main build entry point\r\n *\r\n * The esbuild bundle is written into a TEMP directory next to the real\r\n * output directory, never into it, and that directory is renamed over\r\n * `outdir` as one filesystem operation — so `outdir` is never observed as\r\n * a mix of the old build and the new one, and a build that fails before\r\n * that rename never touches `outdir` at all.\r\n *\r\n * `this.options.outdir` is NOT repointed at the temp directory while that\r\n * happens, and must never be. It is not merely a write target: consumers\r\n * BAKE it into runtime output — `web`'s build contribution derives the\r\n * `clientDir` recorded in its pages manifest from it\r\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\r\n * produces an artifact whose browser paths point at a directory promotion\r\n * has since renamed away. The temp path is passed explicitly, as a\r\n * parameter, to the one operation that writes into it ({@link bundle});\r\n * everything else, `buildContext()` included, keeps reading the final\r\n * destination.\r\n *\r\n * That is also why promotion is STAGED rather than done at the very end.\r\n * Connector `emit` hooks write real artifacts (the web client bundle) and\r\n * see the final `outdir`, so they must run when `outdir` genuinely holds\r\n * this build — after the rename, not before it, or promotion would replace\r\n * the directory they just wrote into. The previous build is kept parked\r\n * aside until they finish: `emit` throwing rolls the whole promotion back,\r\n * and the build-success marker `warlock start` checks is written last of\r\n * all, so a failure at any point leaves no `dist` that start will boot.\r\n */\r\n public async build(): Promise<void> {\r\n console.log(colors.cyan(\"Building for production...\\n\"));\r\n\r\n // Step 1: Initialize options from config\r\n await this.initializeOptions();\r\n\r\n const finalOutDir = this.options.outdir!;\r\n const tempOutDir = createTempOutputDir(finalOutDir);\r\n\r\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\r\n // presence is what tells the catch below whether a failure has a\r\n // promotion to undo or only a temp directory to discard.\r\n let staged: StagedDist | undefined;\r\n\r\n try {\r\n // Step 2: Generate combined files\r\n await this.generateCombinedFiles();\r\n\r\n // Step 3: Generate entry point\r\n await this.generateEntryPoint();\r\n\r\n // Step 4: Refuse to bundle code the app could not resolve at runtime\r\n await this.assertGeneratedImports();\r\n\r\n // Step 4.5: Drain the connectors' `generate` contributions\r\n const contributed = await this.runGenerateContributions();\r\n\r\n // Step 4.6: Re-assert over what the contributors just wrote.\r\n //\r\n // Step 4 only saw core's own generated files; a contributor writes its\r\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\r\n // specifier in it reaches the bundle unchecked. Under\r\n // `packages: \"external\"` that specifier survives verbatim into the\r\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\r\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\r\n // and re-reading the production dir is pure cost in the common case.\r\n if (contributed) {\r\n await this.assertGeneratedImports();\r\n }\r\n\r\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\r\n // operation handed that path — it is a write target, not config.\r\n await this.bundle(tempOutDir);\r\n\r\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\r\n // build parked aside. `outdir` now holds exactly this build, so the\r\n // steps below write into — and record — the real destination.\r\n staged = await stageDistAsync(tempOutDir, finalOutDir);\r\n\r\n // Step 5.6: Drain the connectors' `emit` contributions — after the\r\n // bundle is in place (so what they write survives promotion and the\r\n // paths they bake in resolve), and BEFORE step 6 deletes the\r\n // production directory they may still read.\r\n await runEmitContributions(this.connectors, this.buildContext());\r\n\r\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\r\n // `warlock start` trusts. Written LAST on purpose: every earlier step\r\n // can still fail, and until this file exists nothing will boot what\r\n // they left behind.\r\n await writeDistBuildManifestAsync(finalOutDir);\r\n\r\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\r\n await commitDistAsync(staged);\r\n } catch (error) {\r\n if (staged) {\r\n // The promotion already happened; put the previous build back and\r\n // take this half-finished one out of `outdir`.\r\n await rollbackDistAsync(staged);\r\n } else {\r\n // Nothing this build produced ever reached `outdir` — discard the\r\n // temp directory and leave `outdir` exactly as it was.\r\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\r\n }\r\n\r\n throw error;\r\n }\r\n\r\n // Step 6: Remove production folder\r\n await removeDirectoryAsync(this.productionDir);\r\n\r\n console.log(colors.green(\"Build complete!\"));\r\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\r\n }\r\n\r\n /**\r\n * Initialize options from warlock.config.ts\r\n */\r\n private async initializeOptions(): Promise<void> {\r\n this.options = resolveBuildConfig();\r\n // Same config object `resolveBuildConfig` just read — `warlock build`\r\n // preloads warlock.config.ts, so no additional load happens here.\r\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\r\n\r\n // Checked here, where the array is first read, so nothing downstream has\r\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\r\n // a name listed twice would write its files and merge its esbuild options\r\n // twice into an artifact the runtime then boots that name only once from.\r\n // A build that half-applied a connector and reported success is worse than\r\n // one that never started.\r\n assertUniqueConnectorNames([...connectors]);\r\n\r\n // And here rather than only at boot, for the same reason: a name a built-in\r\n // already owns is skipped by the runtime, so an artifact built from it\r\n // carries the custom connector's generated files and esbuild patches while\r\n // the server boots the built-in instead. Refusing it at boot alone would\r\n // mean the build had already emitted that artifact — the failure has to\r\n // land on the developer running `warlock build`, not on whoever starts the\r\n // server. Same assertion the registration half calls, over the same names.\r\n assertNoReservedConnectorNames([...connectors]);\r\n\r\n this.connectors = connectors;\r\n\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\r\n }\r\n\r\n /**\r\n * The context handed to every build contribution.\r\n */\r\n private buildContext(): ConnectorBuildContext {\r\n return {\r\n productionDir: this.productionDir,\r\n appRoot: rootPath(),\r\n options: this.options,\r\n };\r\n }\r\n\r\n /**\r\n * Drain the `generate` hooks and fold what they returned back into the\r\n * build.\r\n *\r\n * The entry point is REGENERATED here rather than generated later. The\r\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\r\n * bundles that the app could not resolve) and before `bundle` — while\r\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\r\n * generated code the assertion has to see; moving it past the assertion\r\n * would silently drop the entry from that check. Rewriting one small file\r\n * is cheaper than losing either guarantee, and the write is pure\r\n * (`generatedFiles` + these imports), so doing it twice is not a\r\n * correctness risk.\r\n *\r\n * @returns whether any connector ran a `generate` hook — the caller uses it\r\n * to decide if the import assertion is worth a second pass. Keyed on the\r\n * hook EXISTING, not on what it returned: a hook that returns nothing may\r\n * still have written files into `productionDir`, and those are exactly the\r\n * files the second pass is there to read.\r\n */\r\n private async runGenerateContributions(): Promise<boolean> {\r\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\r\n\r\n const { entryImports, esbuild } = await runGenerateContributions(\r\n this.connectors,\r\n this.buildContext(),\r\n );\r\n\r\n this.contributedEsbuild = esbuild;\r\n\r\n if (entryImports.length > 0) {\r\n await this.generateEntryPoint(entryImports);\r\n }\r\n\r\n return contributed;\r\n }\r\n\r\n /**\r\n * Track which special files were generated\r\n */\r\n private generatedFiles = {\r\n locales: false,\r\n events: false,\r\n main: false,\r\n routes: false,\r\n };\r\n\r\n /**\r\n * Generate all combined files\r\n */\r\n private async generateCombinedFiles(): Promise<void> {\r\n console.log(colors.yellow(\" Generating production files...\"));\r\n\r\n // Generate bootstrap.ts file\r\n await this.generateBootstrap();\r\n\r\n // Generate config loader\r\n await this.generateConfigLoader();\r\n\r\n // Generate special files and track which ones have content\r\n const [locales, events, main, routes] = await Promise.all([\r\n this.generateLocales(),\r\n this.generateEvents(),\r\n this.generateMain(),\r\n this.generateRoutes(),\r\n ]);\r\n\r\n this.generatedFiles = { locales, events, main, routes };\r\n }\r\n\r\n /**\r\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\r\n */\r\n private async generateBootstrap(): Promise<void> {\r\n let content = `import { bootstrap, Application } from \"@warlock.js/core\";\r\n\r\n// Set production environment\r\nApplication.setRuntimeStrategy(\"production\");\r\nApplication.setEnvironment(\"production\");\r\n\r\n// Bootstrap the application\r\nbootstrap();\r\n`;\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n content += \"import './../../src/app/bootstrap';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\r\n }\r\n\r\n /**\r\n * Fail the build when generated code imports a package the app does not\r\n * declare.\r\n *\r\n * The bundler is configured `packages: \"external\"`, so every bare specifier\r\n * written above survives verbatim into an artifact that resolves against the\r\n * **consuming app's** node_modules. A framework-internal dependency imported\r\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\r\n * which is how a production app shipped that could not boot. Rewriting the\r\n * offending import fixes today's bundle; this check is what stops the next\r\n * change to the generator from quietly reintroducing it.\r\n */\r\n private async assertGeneratedImports(): Promise<void> {\r\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\r\n cwd: this.productionDir,\r\n absolute: false,\r\n });\r\n\r\n const [files, appPackage] = await Promise.all([\r\n Promise.all(\r\n generatedPaths.map(async (file) => ({\r\n file,\r\n content: await getFileAsync(path.join(this.productionDir, file)),\r\n })),\r\n ),\r\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\r\n ]);\r\n\r\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\r\n }\r\n\r\n /**\r\n * Glob for module files matching a pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModule(fileName: string): Promise<string[]> {\r\n const pattern = `**/${fileName}.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n // Convert to relative paths from .warlock/production/ to src/app/\r\n // e.g., \"users/main\" -> \"../../src/app/users/main\"\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Glob for files in a specific directory pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModuleDirectory(directory: string): Promise<string[]> {\r\n const pattern = `**/${directory}/*.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Generate config-loader.ts\r\n */\r\n private async generateConfigLoader(): Promise<void> {\r\n const configDirectory = path.join(process.cwd(), \"src/config\");\r\n\r\n const files = await glob(\"*.{ts,tsx}\", {\r\n cwd: configDirectory,\r\n absolute: false,\r\n });\r\n\r\n const configNames = files.map((f) => f.replace(/\\.(ts|tsx)$/, \"\"));\r\n\r\n // Only `@warlock.js/core` — the one package the app itself declares. See\r\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\r\n // dependency, so a bare import of it resolved by luck under npm/yarn\r\n // hoisting and died under pnpm's strict layout.\r\n const imports: string[] = [\r\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\r\n ];\r\n const configImports: string[] = [];\r\n const configSetCalls: string[] = [];\r\n const executors: string[] = [];\r\n\r\n for (const configName of configNames) {\r\n const properConfigName = toCamelCase(configName);\r\n const varName = `${properConfigName}Config`;\r\n configImports.push(`import ${varName} from \"../../src/config/${configName}\";`);\r\n configSetCalls.push(`setConfig(\"${properConfigName}\", ${varName});`);\r\n executors.push(`await configSpecialHandlers.execute(\"${properConfigName}\", ${varName});`);\r\n }\r\n\r\n let content = [\r\n ...imports,\r\n \"\",\r\n \"// Config imports\",\r\n ...configImports,\r\n \"\",\r\n \"// Register configs\",\r\n ...configSetCalls,\r\n \"\",\r\n \"// Special handlers\",\r\n ...executors,\r\n \"\",\r\n ].join(\"\\n\");\r\n\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n content += \"import './../../src/app/prestart';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\r\n }\r\n\r\n /**\r\n * Generate locales.ts (only if there are locale files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateLocales(): Promise<boolean> {\r\n const files = await this.globModule(\"utils/locales\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"locales.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate events.ts (only if there are event files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateEvents(): Promise<boolean> {\r\n const files = await this.globModuleDirectory(\"events\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"events.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate main.ts (only if there are main files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateMain(): Promise<boolean> {\r\n const files = await this.globModule(\"main\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"main.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate routes.ts (only if there are route files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateRoutes(): Promise<boolean> {\r\n const files = await this.globModule(\"routes\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"routes.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate a file with imports from all given files\r\n */\r\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\r\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, outputFile), content);\r\n }\r\n\r\n /**\r\n * Generate the main entry point (app.ts)\r\n *\r\n * @param contributedImports lines from connector `generate` hooks, appended\r\n * to section 4 after `./routes`\r\n */\r\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\r\n\r\n // The names this build resolved, baked in as a literal. The entry imports\r\n // the config source, and that source is re-evaluated at startup — an\r\n // env-conditional `connectors` array can hand the boot a different list\r\n // than the one drained here. A literal is the only part of the array that\r\n // survives into the artifact unchanged, so it is what the boot compares\r\n // against.\r\n const expectedNames = this.connectors\r\n .map((connector) => JSON.stringify(connector.name))\r\n .join(\", \");\r\n\r\n // Build imports based on which files were generated\r\n const imports: string[] = [\r\n \"// 1. Bootstrap (loads .env, initializes framework)\",\r\n 'import \"./bootstrap\";',\r\n \"\",\r\n \"// 2. Load configs\",\r\n 'import \"./config-loader\";',\r\n \"\",\r\n // Registration has to sit between the config being available and the\r\n // first phase starting: the connectors listed in `connectors` are the\r\n // same ones this build drained contributions from, so the bundle boots\r\n // exactly what it was built for. Register any later and an early-phase\r\n // connector would miss its own start.\r\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\r\n \"// build read its contributions from, so built-for and boots-with match).\",\r\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\r\n \"// and the array is handed over explicitly — an artifact has no\",\r\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\r\n \"// that quietly found nothing to register is the exact drift this\",\r\n \"// section exists to prevent.\",\r\n \"// `expectedNames` is the list this build resolved, in order — boot\",\r\n \"// refuses to start when the config hands over a different set or order.\",\r\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\r\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\r\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\r\n \"\",\r\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\r\n \"// own preflight is not reached until the database and cache have\",\r\n \"// connected and every app module has been imported — seconds of work\",\r\n \"// thrown away before anyone learns the port was taken. This probe is\",\r\n \"// a bind-and-release on a socket that is never served, and it reports\",\r\n \"// on stderr because no log channel is configured this early.\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\r\n \"await preflightConfiguredHttpPort();\",\r\n \"\",\r\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\r\n ];\r\n\r\n // App code uses dynamic `await import(...)` so each module's side\r\n // effects fire at THIS point in execution. Static imports would be\r\n // hoisted to module-instantiation time (before the early-phase await\r\n // resolves), which is exactly the bug this split is meant to fix.\r\n //\r\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\r\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\r\n // it at the await, not at instantiation. It does NOT come from\r\n // `splitting: true`, which only decides one-file-vs-chunks. This\r\n // previously said splitting was required; it is not, and `singleBundle`\r\n // (splitting: false) preserves the ordering.\r\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\r\n\r\n if (this.generatedFiles.events) {\r\n imports.push('await import(\"./events\");');\r\n }\r\n if (this.generatedFiles.locales) {\r\n imports.push('await import(\"./locales\");');\r\n }\r\n if (this.generatedFiles.main) {\r\n imports.push('await import(\"./main\");');\r\n }\r\n if (this.generatedFiles.routes) {\r\n imports.push('await import(\"./routes\");');\r\n }\r\n\r\n // Contributor imports come AFTER `./routes`, never before: a connector\r\n // that registers pages needs the routes app code already collected —\r\n // the same ordering dev uses (routes first, then the connector installs\r\n // on top of them). Emitted verbatim; the contributor writes the whole\r\n // statement (e.g. `await import(\"./pages\");`).\r\n imports.push(...contributedImports);\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port.\r\n imports.push(\r\n \"\",\r\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\r\n \"await Application.runStartupValidators();\",\r\n );\r\n\r\n // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\r\n \"// listeners registered by app code are now ready to bind\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\r\n \"\",\r\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\r\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\r\n \"connectorsManager.shutdownOnProcessKill();\",\r\n );\r\n\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\r\n }\r\n\r\n /**\r\n * Bundle with esbuild\r\n *\r\n * @param writeOutDir the directory esbuild writes into — the build's\r\n * private temp directory, NOT `options.outdir`. Taken as a parameter\r\n * rather than read off `this.options` because the two are different paths\r\n * with different meanings: `options.outdir` is the final destination every\r\n * consumer bakes into the artifact, and this is only where bytes land\r\n * before promotion moves them there.\r\n */\r\n private async bundle(writeOutDir: string): Promise<void> {\r\n console.log(colors.magenta(\" Bundling with esbuild...\"));\r\n\r\n const entryPoint = path.join(this.productionDir, \"app.ts\");\r\n const outFileName = this.options.outFile!;\r\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\r\n const entryName = path.basename(outFileName, path.extname(outFileName));\r\n\r\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\r\n // unknown keys, and the user options are spread into its call verbatim.\r\n const singleBundle = this.options.singleBundle === true;\r\n const esmShim = this.options.esmShim !== false;\r\n // Read before deleting: the merged banner is applied AFTER the user\r\n // spread, so a user banner must not be lost to it or clobber the shim.\r\n const userBanner = this.options.banner;\r\n\r\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\r\n // resolve-build-config.ts documents that widening them pushed a lie downstream\r\n // into start-production.command.ts, which then could not trust its own config.\r\n // This is the one place they must be absent - the object is spread into esbuild's\r\n // call verbatim and esbuild throws on unknown keys. Strip them through a local\r\n // optional view rather than weakening the type every other caller relies on; both\r\n // were already read into locals above.\r\n const strippable = this.options as Partial<ResolvedBuildConfig>;\r\n\r\n delete strippable.outFile;\r\n delete strippable.entryPath;\r\n delete this.options.singleBundle;\r\n delete this.options.esmShim;\r\n delete this.options.banner;\r\n\r\n await ensureDirectoryAsync(writeOutDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\r\n\r\n // Whether this build decides externality per import EDGE\r\n // (`bundle-framework-dependencies.ts`, which explains the rule at\r\n // length) or keeps the blunt `packages: \"external\"`.\r\n //\r\n // Not in `singleBundle` mode: that bundles everything by definition, and\r\n // a plugin that can only ever ADD an external would silently narrow it.\r\n // Not when the user set `packages` themselves: their value has always\r\n // won over the default below, and it must keep winning — the plugin is\r\n // the default's implementation, not a new policy layered on top.\r\n const perEdgeExternals = !singleBundle && (this.options as any).packages === undefined;\r\n\r\n // The user can override `format`, so gate the shim on the EFFECTIVE\r\n // format rather than on the default below. A CJS build already has\r\n // `require` and friends; injecting them there would be a redefinition.\r\n const isEsm = (this.options.format ?? \"esm\") === \"esm\";\r\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\r\n\r\n // Contributor patch, split into the part that can ride the spread order\r\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\r\n // BEFORE the user spread below, which gives the ruled precedence for\r\n // free: builder defaults < contributor < user config.\r\n //\r\n // `define`, `external` and `loader` are pulled out because a spread\r\n // REPLACES them wholesale — the same trap `banner` documents. Two\r\n // contributors' env defines, a contributor's optional peers plus the\r\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\r\n // must both survive, so they are merged by key/by set and re-applied\r\n // after the spread with the user still winning per key.\r\n const {\r\n define: contributedDefine,\r\n external: contributedExternal,\r\n loader: contributedLoader,\r\n ...contributedOptions\r\n } = this.contributedEsbuild;\r\n\r\n const userDefine: Record<string, string> | undefined = this.options.define;\r\n const userExternal: string[] | undefined = this.options.external;\r\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = this.options.loader;\r\n\r\n const define =\r\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\r\n\r\n const loader =\r\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\r\n\r\n const external =\r\n contributedExternal || userExternal\r\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\r\n : undefined;\r\n\r\n if (singleBundle) {\r\n console.log(\r\n colors.magenta(\r\n \" Single-bundle mode — one JS file\" +\r\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\r\n \". Native .node addons are still emitted alongside it.\",\r\n ),\r\n );\r\n }\r\n\r\n try {\r\n await esbuild.build({\r\n platform: \"node\",\r\n entryPoints: [entryPoint],\r\n bundle: true,\r\n // Both are DEFAULTS the user can override — they sit before the\r\n // `...this.options` spread deliberately. `singleBundle` moves them,\r\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\r\n //\r\n // Phase ordering does not depend on `splitting`: it comes from the\r\n // generated app.ts using dynamic `await import(...)` (see\r\n // generateAppEntry above), which esbuild defers to the call site in\r\n // either mode. Splitting only decides one file vs chunks.\r\n splitting: !singleBundle,\r\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\r\n // the plugin below returns `external: true` for every bare specifier\r\n // this build must not bundle, which is all of them bar the framework's\r\n // own declared dependencies. Saying `\"external\"` here instead would\r\n // externalise them before the plugin could rule.\r\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\r\n minify: this.options!.minify,\r\n sourcemap: this.options!.sourcemap === true ? \"linked\" : this.options!.sourcemap,\r\n format: \"esm\",\r\n // Targeting a concrete Node version (not \"esnext\") so esbuild\r\n // transpiles TC39 stage 3 decorators into helpers — Node does not\r\n // implement them natively yet.\r\n target: [\"node22\"],\r\n entryNames: entryName,\r\n alias,\r\n plugins: [\r\n nativeNodeModulesPlugin,\r\n // BEFORE the framework-dependency plugin, and the order is\r\n // load-bearing: the first `onResolve` callback to answer wins, and\r\n // `app/users/...` is a bare specifier the other one would rule\r\n // external.\r\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\r\n ...(perEdgeExternals\r\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\r\n : []),\r\n ],\r\n // Between the defaults and the user spread — the ruled precedence.\r\n ...contributedOptions,\r\n ...(this.options as any),\r\n // AFTER the spread, and NOT overridable: `this.options.outdir` rides\r\n // that spread carrying the FINAL destination, which is exactly where\r\n // this build must not write yet. The final path is the user's setting\r\n // and stays authoritative for everyone reading the config — it is only\r\n // this one esbuild call that is redirected, and only until promotion\r\n // moves the result onto that very path.\r\n outdir: writeOutDir,\r\n // AFTER the spread for the same reason `banner` is: a spread replaces\r\n // these objects instead of merging them, so the merged values are\r\n // re-applied here. The user still wins — they were merged in last.\r\n ...(define ? { define } : {}),\r\n ...(external ? { external } : {}),\r\n ...(loader ? { loader } : {}),\r\n // AFTER the spread, and intentionally so: `banner` is an object, and\r\n // both the config merge and this spread REPLACE it wholesale rather\r\n // than merging. Left as a default above, any user banner would delete\r\n // the shim; left to the spread, the shim would delete theirs. The\r\n // merge is the only form that keeps both.\r\n ...(banner ? { banner } : {}),\r\n });\r\n } catch (e) {\r\n console.log(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * The WILDCARD half of the same tsconfig `paths` map that\r\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\r\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\r\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\r\n * so the entries it skips have to be resolved by a plugin instead of being\r\n * left to no one.\r\n */\r\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\r\n tsconfigManager.init();\r\n\r\n return {\r\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\r\n paths: tsconfigManager.aliases as Record<string, string[]>,\r\n };\r\n }\r\n\r\n /**\r\n * Build an alias map from tsconfig `paths` so esbuild resolves local\r\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\r\n * folders during bundling. Without this, `packages: \"external\"` would\r\n * leave those bare specifiers as raw imports and Node would fail to\r\n * resolve them at runtime (they aren't installed in node_modules).\r\n *\r\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\r\n * option doesn't support glob-style mappings. The wildcard half is not\r\n * dropped, it is handled elsewhere: see\r\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\r\n */\r\n private buildAliasMapFromTsconfig(): Record<string, string> {\r\n tsconfigManager.init();\r\n\r\n const alias: Record<string, string> = {};\r\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\r\n\r\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\r\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\r\n continue;\r\n }\r\n\r\n alias[from] = path.resolve(baseUrl, to[0]);\r\n }\r\n\r\n return alias;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,M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AAO,IAAI,CAAC;IAM3B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC7B,CAAC;EACH,SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;CAUA,AAAQ,0BAAgF;EACtF,gBAAgB,KAAK;EAErB,OAAO;GACL,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;GAC5D,OAAO,gBAAgB;EACzB;CACF;;;;;;;;;;;;;CAcA,AAAQ,4BAAoD;EAC1D,gBAAgB,KAAK;EAErB,MAAM,QAAgC,CAAC;EACvC,MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;EAEnE,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,GAAG,EAAE;EAC3C;EAEA,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n ensureDirectoryAsync,\r\n fileExistsAsync,\r\n getFileAsync,\r\n getJsonFileAsync,\r\n putFileAsync,\r\n removeDirectoryAsync,\r\n} from \"@warlock.js/fs\";\r\nimport esbuild from \"esbuild\";\r\nimport glob from \"fast-glob\";\r\nimport path from \"path\";\r\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\r\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\r\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\r\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\r\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\r\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\r\nimport {\r\n commitDistAsync,\r\n createTempOutputDir,\r\n rollbackDistAsync,\r\n stageDistAsync,\r\n type StagedDist,\r\n} from \"./promote-dist\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\r\n\r\n/**\r\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\r\n *\r\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\r\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\r\n * esbuild substitutes a stub that throws — **after the build has reported\r\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\r\n * firing, and it is the defect this shim removes.\r\n *\r\n * `__dirname` matters as much as `require`: without it a dependency resolving\r\n * an asset path silently gets `undefined` and fails later, further from the\r\n * cause.\r\n *\r\n * Written as one line because esbuild inserts a banner verbatim above the\r\n * bundle and a multi-line string here would shift every mapped line.\r\n */\r\nconst ESM_INTEROP_SHIM =\r\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\r\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\r\n \"import{dirname as __wlDirname}from'node:path';\" +\r\n \"const require=__wlCreateRequire(import.meta.url);\" +\r\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\r\n \"const __dirname=__wlDirname(__filename);\";\r\n\r\n/**\r\n * Combine the framework's banner with the user's, keeping both.\r\n *\r\n * esbuild's `banner` is an object keyed by output type, and every merge in the\r\n * path to it — the config merge and the options spread — REPLACES that object\r\n * rather than merging it. So whichever is applied second silently deletes the\r\n * other. This is the only place the two can coexist.\r\n *\r\n * The shim goes first: it defines `require`, which a user banner may use.\r\n *\r\n * @param userBanner banner from `warlock.config.ts`, if any\r\n * @param shim the interop shim, or undefined when it does not apply\r\n */\r\nfunction mergeBanner(\r\n userBanner: Record<string, string> | undefined,\r\n shim: string | undefined,\r\n): Record<string, string> | undefined {\r\n if (!shim) return userBanner;\r\n\r\n const userJs = userBanner?.js;\r\n\r\n return {\r\n ...userBanner,\r\n js: userJs ? `${shim}${userJs}` : shim,\r\n };\r\n}\r\n\r\n/**\r\n * Prefix every generated file uses to reach the app root.\r\n *\r\n * Generated sources are written into `.warlock/production/`, two levels below\r\n * the app root, so `../../` lands back on it — the same hop already spelled\r\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\r\n * config-loader generators emit. Named once so a generator that needs a new\r\n * app-root file (`warlock.config`) cannot pick a different depth.\r\n */\r\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\r\n\r\n/**\r\n * Production Builder\r\n * Generates production-ready files and bundles them for deployment\r\n * Build options are loaded from warlock.config.ts\r\n */\r\nexport class ProductionBuilder {\r\n private options!: ResolvedBuildConfig;\r\n private readonly productionDir = warlockPath(\"production\");\r\n\r\n /**\r\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\r\n * never calls `boot()`/`start()` on them; it only\r\n * drains their `build` contributions.\r\n */\r\n private connectors: readonly Connector[] = [];\r\n\r\n /**\r\n * The contributors' merged esbuild patch, produced by the `generate` pass\r\n * and consumed by {@link bundle}.\r\n */\r\n private contributedEsbuild: ConnectorEsbuildPatch = {};\r\n\r\n /**\r\n * Main build entry point\r\n *\r\n * The esbuild bundle is written into a TEMP directory next to the real\r\n * output directory, never into it, and that directory is renamed over\r\n * `outdir` as one filesystem operation — so `outdir` is never observed as\r\n * a mix of the old build and the new one, and a build that fails before\r\n * that rename never touches `outdir` at all.\r\n *\r\n * `this.options.outdir` is NOT repointed at the temp directory while that\r\n * happens, and must never be. It is not merely a write target: consumers\r\n * BAKE it into runtime output — `web`'s build contribution derives the\r\n * `clientDir` recorded in its pages manifest from it\r\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\r\n * produces an artifact whose browser paths point at a directory promotion\r\n * has since renamed away. The temp path is passed explicitly, as a\r\n * parameter, to the one operation that writes into it ({@link bundle});\r\n * everything else, `buildContext()` included, keeps reading the final\r\n * destination.\r\n *\r\n * That is also why promotion is STAGED rather than done at the very end.\r\n * Connector `emit` hooks write real artifacts (the web client bundle) and\r\n * see the final `outdir`, so they must run when `outdir` genuinely holds\r\n * this build — after the rename, not before it, or promotion would replace\r\n * the directory they just wrote into. The previous build is kept parked\r\n * aside until they finish: `emit` throwing rolls the whole promotion back,\r\n * and the build-success marker `warlock start` checks is written last of\r\n * all, so a failure at any point leaves no `dist` that start will boot.\r\n */\r\n public async build(): Promise<void> {\r\n console.log(colors.cyan(\"Building for production...\\n\"));\r\n\r\n // Step 0: Fail fast when esbuild's native binary never got linked (the\r\n // state pnpm leaves a project in when its build-script approval gate\r\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\r\n // own cryptic \"package could not be found\" error several steps from now.\r\n assertEsbuildBinaryIsLinked();\r\n\r\n // Step 1: Initialize options from config\r\n await this.initializeOptions();\r\n\r\n const finalOutDir = this.options.outdir!;\r\n const tempOutDir = createTempOutputDir(finalOutDir);\r\n\r\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\r\n // presence is what tells the catch below whether a failure has a\r\n // promotion to undo or only a temp directory to discard.\r\n let staged: StagedDist | undefined;\r\n\r\n try {\r\n // Step 2: Generate combined files\r\n await this.generateCombinedFiles();\r\n\r\n // Step 3: Generate entry point\r\n await this.generateEntryPoint();\r\n\r\n // Step 4: Refuse to bundle code the app could not resolve at runtime\r\n await this.assertGeneratedImports();\r\n\r\n // Step 4.5: Drain the connectors' `generate` contributions\r\n const contributed = await this.runGenerateContributions();\r\n\r\n // Step 4.6: Re-assert over what the contributors just wrote.\r\n //\r\n // Step 4 only saw core's own generated files; a contributor writes its\r\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\r\n // specifier in it reaches the bundle unchecked. Under\r\n // `packages: \"external\"` that specifier survives verbatim into the\r\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\r\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\r\n // and re-reading the production dir is pure cost in the common case.\r\n if (contributed) {\r\n await this.assertGeneratedImports();\r\n }\r\n\r\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\r\n // operation handed that path — it is a write target, not config.\r\n await this.bundle(tempOutDir);\r\n\r\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\r\n // build parked aside. `outdir` now holds exactly this build, so the\r\n // steps below write into — and record — the real destination.\r\n staged = await stageDistAsync(tempOutDir, finalOutDir);\r\n\r\n // Step 5.6: Drain the connectors' `emit` contributions — after the\r\n // bundle is in place (so what they write survives promotion and the\r\n // paths they bake in resolve), and BEFORE step 6 deletes the\r\n // production directory they may still read.\r\n await runEmitContributions(this.connectors, this.buildContext());\r\n\r\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\r\n // `warlock start` trusts. Written LAST on purpose: every earlier step\r\n // can still fail, and until this file exists nothing will boot what\r\n // they left behind.\r\n await writeDistBuildManifestAsync(finalOutDir);\r\n\r\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\r\n await commitDistAsync(staged);\r\n } catch (error) {\r\n if (staged) {\r\n // The promotion already happened; put the previous build back and\r\n // take this half-finished one out of `outdir`.\r\n await rollbackDistAsync(staged);\r\n } else {\r\n // Nothing this build produced ever reached `outdir` — discard the\r\n // temp directory and leave `outdir` exactly as it was.\r\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\r\n }\r\n\r\n throw error;\r\n }\r\n\r\n // Step 6: Remove production folder\r\n await removeDirectoryAsync(this.productionDir);\r\n\r\n console.log(colors.green(\"Build complete!\"));\r\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\r\n }\r\n\r\n /**\r\n * Initialize options from warlock.config.ts\r\n */\r\n private async initializeOptions(): Promise<void> {\r\n this.options = resolveBuildConfig();\r\n // Same config object `resolveBuildConfig` just read — `warlock build`\r\n // preloads warlock.config.ts, so no additional load happens here.\r\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\r\n\r\n // Checked here, where the array is first read, so nothing downstream has\r\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\r\n // a name listed twice would write its files and merge its esbuild options\r\n // twice into an artifact the runtime then boots that name only once from.\r\n // A build that half-applied a connector and reported success is worse than\r\n // one that never started.\r\n assertUniqueConnectorNames([...connectors]);\r\n\r\n // And here rather than only at boot, for the same reason: a name a built-in\r\n // already owns is skipped by the runtime, so an artifact built from it\r\n // carries the custom connector's generated files and esbuild patches while\r\n // the server boots the built-in instead. Refusing it at boot alone would\r\n // mean the build had already emitted that artifact — the failure has to\r\n // land on the developer running `warlock build`, not on whoever starts the\r\n // server. Same assertion the registration half calls, over the same names.\r\n assertNoReservedConnectorNames([...connectors]);\r\n\r\n this.connectors = connectors;\r\n\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\r\n }\r\n\r\n /**\r\n * The context handed to every build contribution.\r\n */\r\n private buildContext(): ConnectorBuildContext {\r\n return {\r\n productionDir: this.productionDir,\r\n appRoot: rootPath(),\r\n options: this.options,\r\n };\r\n }\r\n\r\n /**\r\n * Drain the `generate` hooks and fold what they returned back into the\r\n * build.\r\n *\r\n * The entry point is REGENERATED here rather than generated later. The\r\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\r\n * bundles that the app could not resolve) and before `bundle` — while\r\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\r\n * generated code the assertion has to see; moving it past the assertion\r\n * would silently drop the entry from that check. Rewriting one small file\r\n * is cheaper than losing either guarantee, and the write is pure\r\n * (`generatedFiles` + these imports), so doing it twice is not a\r\n * correctness risk.\r\n *\r\n * @returns whether any connector ran a `generate` hook — the caller uses it\r\n * to decide if the import assertion is worth a second pass. Keyed on the\r\n * hook EXISTING, not on what it returned: a hook that returns nothing may\r\n * still have written files into `productionDir`, and those are exactly the\r\n * files the second pass is there to read.\r\n */\r\n private async runGenerateContributions(): Promise<boolean> {\r\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\r\n\r\n const { entryImports, esbuild } = await runGenerateContributions(\r\n this.connectors,\r\n this.buildContext(),\r\n );\r\n\r\n this.contributedEsbuild = esbuild;\r\n\r\n if (entryImports.length > 0) {\r\n await this.generateEntryPoint(entryImports);\r\n }\r\n\r\n return contributed;\r\n }\r\n\r\n /**\r\n * Track which special files were generated\r\n */\r\n private generatedFiles = {\r\n locales: false,\r\n events: false,\r\n main: false,\r\n routes: false,\r\n };\r\n\r\n /**\r\n * Generate all combined files\r\n */\r\n private async generateCombinedFiles(): Promise<void> {\r\n console.log(colors.yellow(\" Generating production files...\"));\r\n\r\n // Generate bootstrap.ts file\r\n await this.generateBootstrap();\r\n\r\n // Generate config loader\r\n await this.generateConfigLoader();\r\n\r\n // Generate special files and track which ones have content\r\n const [locales, events, main, routes] = await Promise.all([\r\n this.generateLocales(),\r\n this.generateEvents(),\r\n this.generateMain(),\r\n this.generateRoutes(),\r\n ]);\r\n\r\n this.generatedFiles = { locales, events, main, routes };\r\n }\r\n\r\n /**\r\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\r\n */\r\n private async generateBootstrap(): Promise<void> {\r\n let content = `import { bootstrap, Application } from \"@warlock.js/core\";\r\n\r\n// Set production environment\r\nApplication.setRuntimeStrategy(\"production\");\r\nApplication.setEnvironment(\"production\");\r\n\r\n// Bootstrap the application\r\nbootstrap();\r\n`;\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n content += \"import './../../src/app/bootstrap';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\r\n }\r\n\r\n /**\r\n * Fail the build when generated code imports a package the app does not\r\n * declare.\r\n *\r\n * The bundler is configured `packages: \"external\"`, so every bare specifier\r\n * written above survives verbatim into an artifact that resolves against the\r\n * **consuming app's** node_modules. A framework-internal dependency imported\r\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\r\n * which is how a production app shipped that could not boot. Rewriting the\r\n * offending import fixes today's bundle; this check is what stops the next\r\n * change to the generator from quietly reintroducing it.\r\n */\r\n private async assertGeneratedImports(): Promise<void> {\r\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\r\n cwd: this.productionDir,\r\n absolute: false,\r\n });\r\n\r\n const [files, appPackage] = await Promise.all([\r\n Promise.all(\r\n generatedPaths.map(async (file) => ({\r\n file,\r\n content: await getFileAsync(path.join(this.productionDir, file)),\r\n })),\r\n ),\r\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\r\n ]);\r\n\r\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\r\n }\r\n\r\n /**\r\n * Glob for module files matching a pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModule(fileName: string): Promise<string[]> {\r\n const pattern = `**/${fileName}.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n // Convert to relative paths from .warlock/production/ to src/app/\r\n // e.g., \"users/main\" -> \"../../src/app/users/main\"\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Glob for files in a specific directory pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModuleDirectory(directory: string): Promise<string[]> {\r\n const pattern = `**/${directory}/*.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Generate config-loader.ts\r\n */\r\n private async generateConfigLoader(): Promise<void> {\r\n const configDirectory = path.join(process.cwd(), \"src/config\");\r\n\r\n const files = await glob(\"*.{ts,tsx}\", {\r\n cwd: configDirectory,\r\n absolute: false,\r\n });\r\n\r\n const configNames = files.map((f) => f.replace(/\\.(ts|tsx)$/, \"\"));\r\n\r\n // Only `@warlock.js/core` — the one package the app itself declares. See\r\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\r\n // dependency, so a bare import of it resolved by luck under npm/yarn\r\n // hoisting and died under pnpm's strict layout.\r\n const imports: string[] = [\r\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\r\n ];\r\n const configImports: string[] = [];\r\n const configSetCalls: string[] = [];\r\n const executors: string[] = [];\r\n\r\n for (const configName of configNames) {\r\n const properConfigName = toCamelCase(configName);\r\n const varName = `${properConfigName}Config`;\r\n configImports.push(`import ${varName} from \"../../src/config/${configName}\";`);\r\n configSetCalls.push(`setConfig(\"${properConfigName}\", ${varName});`);\r\n executors.push(`await configSpecialHandlers.execute(\"${properConfigName}\", ${varName});`);\r\n }\r\n\r\n let content = [\r\n ...imports,\r\n \"\",\r\n \"// Config imports\",\r\n ...configImports,\r\n \"\",\r\n \"// Register configs\",\r\n ...configSetCalls,\r\n \"\",\r\n \"// Special handlers\",\r\n ...executors,\r\n \"\",\r\n ].join(\"\\n\");\r\n\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n content += \"import './../../src/app/prestart';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\r\n }\r\n\r\n /**\r\n * Generate locales.ts (only if there are locale files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateLocales(): Promise<boolean> {\r\n const files = await this.globModule(\"utils/locales\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"locales.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate events.ts (only if there are event files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateEvents(): Promise<boolean> {\r\n const files = await this.globModuleDirectory(\"events\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"events.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate main.ts (only if there are main files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateMain(): Promise<boolean> {\r\n const files = await this.globModule(\"main\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"main.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate routes.ts (only if there are route files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateRoutes(): Promise<boolean> {\r\n const files = await this.globModule(\"routes\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"routes.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate a file with imports from all given files\r\n */\r\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\r\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, outputFile), content);\r\n }\r\n\r\n /**\r\n * Generate the main entry point (app.ts)\r\n *\r\n * @param contributedImports lines from connector `generate` hooks, appended\r\n * to section 4 after `./routes`\r\n */\r\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\r\n\r\n // The names this build resolved, baked in as a literal. The entry imports\r\n // the config source, and that source is re-evaluated at startup — an\r\n // env-conditional `connectors` array can hand the boot a different list\r\n // than the one drained here. A literal is the only part of the array that\r\n // survives into the artifact unchanged, so it is what the boot compares\r\n // against.\r\n const expectedNames = this.connectors\r\n .map((connector) => JSON.stringify(connector.name))\r\n .join(\", \");\r\n\r\n // Build imports based on which files were generated\r\n const imports: string[] = [\r\n \"// 1. Bootstrap (loads .env, initializes framework)\",\r\n 'import \"./bootstrap\";',\r\n \"\",\r\n \"// 2. Load configs\",\r\n 'import \"./config-loader\";',\r\n \"\",\r\n // Registration has to sit between the config being available and the\r\n // first phase starting: the connectors listed in `connectors` are the\r\n // same ones this build drained contributions from, so the bundle boots\r\n // exactly what it was built for. Register any later and an early-phase\r\n // connector would miss its own start.\r\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\r\n \"// build read its contributions from, so built-for and boots-with match).\",\r\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\r\n \"// and the array is handed over explicitly — an artifact has no\",\r\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\r\n \"// that quietly found nothing to register is the exact drift this\",\r\n \"// section exists to prevent.\",\r\n \"// `expectedNames` is the list this build resolved, in order — boot\",\r\n \"// refuses to start when the config hands over a different set or order.\",\r\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\r\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\r\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\r\n \"\",\r\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\r\n \"// own preflight is not reached until the database and cache have\",\r\n \"// connected and every app module has been imported — seconds of work\",\r\n \"// thrown away before anyone learns the port was taken. This probe is\",\r\n \"// a bind-and-release on a socket that is never served, and it reports\",\r\n \"// on stderr because no log channel is configured this early.\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\r\n \"await preflightConfiguredHttpPort();\",\r\n \"\",\r\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\r\n ];\r\n\r\n // App code uses dynamic `await import(...)` so each module's side\r\n // effects fire at THIS point in execution. Static imports would be\r\n // hoisted to module-instantiation time (before the early-phase await\r\n // resolves), which is exactly the bug this split is meant to fix.\r\n //\r\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\r\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\r\n // it at the await, not at instantiation. It does NOT come from\r\n // `splitting: true`, which only decides one-file-vs-chunks. This\r\n // previously said splitting was required; it is not, and `singleBundle`\r\n // (splitting: false) preserves the ordering.\r\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\r\n\r\n if (this.generatedFiles.events) {\r\n imports.push('await import(\"./events\");');\r\n }\r\n if (this.generatedFiles.locales) {\r\n imports.push('await import(\"./locales\");');\r\n }\r\n if (this.generatedFiles.main) {\r\n imports.push('await import(\"./main\");');\r\n }\r\n if (this.generatedFiles.routes) {\r\n imports.push('await import(\"./routes\");');\r\n }\r\n\r\n // Contributor imports come AFTER `./routes`, never before: a connector\r\n // that registers pages needs the routes app code already collected —\r\n // the same ordering dev uses (routes first, then the connector installs\r\n // on top of them). Emitted verbatim; the contributor writes the whole\r\n // statement (e.g. `await import(\"./pages\");`).\r\n imports.push(...contributedImports);\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port.\r\n imports.push(\r\n \"\",\r\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\r\n \"await Application.runStartupValidators();\",\r\n );\r\n\r\n // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\r\n \"// listeners registered by app code are now ready to bind\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\r\n \"\",\r\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\r\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\r\n \"connectorsManager.shutdownOnProcessKill();\",\r\n );\r\n\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\r\n }\r\n\r\n /**\r\n * Bundle with esbuild\r\n *\r\n * @param writeOutDir the directory esbuild writes into — the build's\r\n * private temp directory, NOT `options.outdir`. Taken as a parameter\r\n * rather than read off `this.options` because the two are different paths\r\n * with different meanings: `options.outdir` is the final destination every\r\n * consumer bakes into the artifact, and this is only where bytes land\r\n * before promotion moves them there.\r\n */\r\n private async bundle(writeOutDir: string): Promise<void> {\r\n console.log(colors.magenta(\" Bundling with esbuild...\"));\r\n\r\n const entryPoint = path.join(this.productionDir, \"app.ts\");\r\n const outFileName = this.options.outFile!;\r\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\r\n const entryName = path.basename(outFileName, path.extname(outFileName));\r\n\r\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\r\n // unknown keys, and the user options are spread into its call verbatim.\r\n const singleBundle = this.options.singleBundle === true;\r\n const esmShim = this.options.esmShim !== false;\r\n // Read before deleting: the merged banner is applied AFTER the user\r\n // spread, so a user banner must not be lost to it or clobber the shim.\r\n const userBanner = this.options.banner;\r\n\r\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\r\n // resolve-build-config.ts documents that widening them pushed a lie downstream\r\n // into start-production.command.ts, which then could not trust its own config.\r\n // This is the one place they must be absent - the object is spread into esbuild's\r\n // call verbatim and esbuild throws on unknown keys.\r\n //\r\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\r\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\r\n // contribution hook, including the `emit` pass that runs AFTER this method\r\n // returns (`build()` step 5.6). Deleting these keys from the shared object\r\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\r\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\r\n // types them as present. A shallow copy is enough — every field this method\r\n // reads off it is either scalar or already re-merged below (`define`,\r\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\r\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\r\n\r\n delete esbuildOptions.outFile;\r\n delete esbuildOptions.entryPath;\r\n delete esbuildOptions.singleBundle;\r\n delete esbuildOptions.esmShim;\r\n delete esbuildOptions.banner;\r\n\r\n await ensureDirectoryAsync(writeOutDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\r\n\r\n // Whether this build decides externality per import EDGE\r\n // (`bundle-framework-dependencies.ts`, which explains the rule at\r\n // length) or keeps the blunt `packages: \"external\"`.\r\n //\r\n // Not in `singleBundle` mode: that bundles everything by definition, and\r\n // a plugin that can only ever ADD an external would silently narrow it.\r\n // Not when the user set `packages` themselves: their value has always\r\n // won over the default below, and it must keep winning — the plugin is\r\n // the default's implementation, not a new policy layered on top.\r\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\r\n\r\n // The user can override `format`, so gate the shim on the EFFECTIVE\r\n // format rather than on the default below. A CJS build already has\r\n // `require` and friends; injecting them there would be a redefinition.\r\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\r\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\r\n\r\n // Contributor patch, split into the part that can ride the spread order\r\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\r\n // BEFORE the user spread below, which gives the ruled precedence for\r\n // free: builder defaults < contributor < user config.\r\n //\r\n // `define`, `external` and `loader` are pulled out because a spread\r\n // REPLACES them wholesale — the same trap `banner` documents. Two\r\n // contributors' env defines, a contributor's optional peers plus the\r\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\r\n // must both survive, so they are merged by key/by set and re-applied\r\n // after the spread with the user still winning per key.\r\n const {\r\n define: contributedDefine,\r\n external: contributedExternal,\r\n loader: contributedLoader,\r\n ...contributedOptions\r\n } = this.contributedEsbuild;\r\n\r\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\r\n const userExternal: string[] | undefined = esbuildOptions.external;\r\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\r\n\r\n const define =\r\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\r\n\r\n const loader =\r\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\r\n\r\n const external =\r\n contributedExternal || userExternal\r\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\r\n : undefined;\r\n\r\n if (singleBundle) {\r\n console.log(\r\n colors.magenta(\r\n \" Single-bundle mode — one JS file\" +\r\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\r\n \". Native .node addons are still emitted alongside it.\",\r\n ),\r\n );\r\n }\r\n\r\n try {\r\n await esbuild.build({\r\n platform: \"node\",\r\n entryPoints: [entryPoint],\r\n bundle: true,\r\n // Both are DEFAULTS the user can override — they sit before the\r\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\r\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\r\n //\r\n // Phase ordering does not depend on `splitting`: it comes from the\r\n // generated app.ts using dynamic `await import(...)` (see\r\n // generateAppEntry above), which esbuild defers to the call site in\r\n // either mode. Splitting only decides one file vs chunks.\r\n splitting: !singleBundle,\r\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\r\n // the plugin below returns `external: true` for every bare specifier\r\n // this build must not bundle, which is all of them bar the framework's\r\n // own declared dependencies. Saying `\"external\"` here instead would\r\n // externalise them before the plugin could rule.\r\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\r\n minify: esbuildOptions.minify,\r\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\r\n format: \"esm\",\r\n // Targeting a concrete Node version (not \"esnext\") so esbuild\r\n // transpiles TC39 stage 3 decorators into helpers — Node does not\r\n // implement them natively yet.\r\n target: [\"node22\"],\r\n entryNames: entryName,\r\n alias,\r\n plugins: [\r\n nativeNodeModulesPlugin,\r\n // BEFORE the framework-dependency plugin, and the order is\r\n // load-bearing: the first `onResolve` callback to answer wins, and\r\n // `app/users/...` is a bare specifier the other one would rule\r\n // external.\r\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\r\n ...(perEdgeExternals\r\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\r\n : []),\r\n ],\r\n // Between the defaults and the user spread — the ruled precedence.\r\n ...contributedOptions,\r\n ...(esbuildOptions as any),\r\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\r\n // that spread carrying the FINAL destination, which is exactly where\r\n // this build must not write yet. The final path is the user's setting\r\n // and stays authoritative for everyone reading the config — it is only\r\n // this one esbuild call that is redirected, and only until promotion\r\n // moves the result onto that very path.\r\n outdir: writeOutDir,\r\n // AFTER the spread for the same reason `banner` is: a spread replaces\r\n // these objects instead of merging them, so the merged values are\r\n // re-applied here. The user still wins — they were merged in last.\r\n ...(define ? { define } : {}),\r\n ...(external ? { external } : {}),\r\n ...(loader ? { loader } : {}),\r\n // AFTER the spread, and intentionally so: `banner` is an object, and\r\n // both the config merge and this spread REPLACE it wholesale rather\r\n // than merging. Left as a default above, any user banner would delete\r\n // the shim; left to the spread, the shim would delete theirs. The\r\n // merge is the only form that keeps both.\r\n ...(banner ? { banner } : {}),\r\n });\r\n } catch (e) {\r\n console.log(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * The WILDCARD half of the same tsconfig `paths` map that\r\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\r\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\r\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\r\n * so the entries it skips have to be resolved by a plugin instead of being\r\n * left to no one.\r\n */\r\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\r\n tsconfigManager.init();\r\n\r\n return {\r\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\r\n paths: tsconfigManager.aliases as Record<string, string[]>,\r\n };\r\n }\r\n\r\n /**\r\n * Build an alias map from tsconfig `paths` so esbuild resolves local\r\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\r\n * folders during bundling. Without this, `packages: \"external\"` would\r\n * leave those bare specifiers as raw imports and Node would fail to\r\n * resolve them at runtime (they aren't installed in node_modules).\r\n *\r\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\r\n * option doesn't support glob-style mappings. The wildcard half is not\r\n * dropped, it is handled elsewhere: see\r\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\r\n */\r\n private buildAliasMapFromTsconfig(): Record<string, string> {\r\n tsconfigManager.init();\r\n\r\n const alias: Record<string, string> = {};\r\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\r\n\r\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\r\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\r\n continue;\r\n }\r\n\r\n const target = to[0];\r\n\r\n if (target === undefined) {\r\n continue;\r\n }\r\n\r\n alias[from] = path.resolve(baseUrl, target);\r\n }\r\n\r\n return alias;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,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;wBA4M5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAlLA,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,mB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AAI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
@@ -1,5 +1,5 @@
1
- import { Request } from "../http/request.mjs";
2
1
  import { Response } from "../http/response.mjs";
2
+ import { Request } from "../http/request.mjs";
3
3
  import { HttpContext, RestfulMiddleware, RouteResource } from "../router/types.mjs";
4
4
  import { RepositoryManager } from "../repositories/repository.manager.mjs";
5
5
  import { Model } from "@warlock.js/cascade";
@@ -1,3 +1,6 @@
1
+ import { buildTracingContext, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled } from "../http/tracing/tracing-dispatcher.mjs";
2
+ import "../http/tracing/index.mjs";
3
+
1
4
  //#region ../core/src/router/log-request-lifecycle.ts
2
5
  function levelForStatus(statusCode) {
3
6
  if (statusCode === void 0) return "info";
@@ -7,13 +10,15 @@ function levelForStatus(statusCode) {
7
10
  }
8
11
  async function logRequestLifecycle(ports, descriptor, run) {
9
12
  const startedAt = ports.now();
13
+ const tracingEnabled = isTracingEnabled();
10
14
  ports.info({
11
15
  module: descriptor.module,
12
16
  action: descriptor.action,
13
17
  message: `Starting Request: ${descriptor.requestId}`,
14
18
  context: descriptor.context
15
19
  });
16
- const finish = (level, outcome) => {
20
+ if (tracingEnabled && descriptor.request) dispatchRequestStart(buildTracingContext(descriptor.request));
21
+ const finish = (level, outcome, error) => {
17
22
  const duration = Math.round(ports.now() - startedAt);
18
23
  ports[level]({
19
24
  module: descriptor.module,
@@ -21,6 +26,11 @@ async function logRequestLifecycle(ports, descriptor, run) {
21
26
  message: `Completed Request: ${descriptor.requestId} — ${outcome} in ${duration}ms`,
22
27
  context: descriptor.context
23
28
  });
29
+ if (tracingEnabled && descriptor.request) dispatchRequestEnd(buildTracingContext(descriptor.request), {
30
+ status: descriptor.statusCode(),
31
+ durationMs: duration,
32
+ error
33
+ });
24
34
  };
25
35
  try {
26
36
  const result = await run();
@@ -28,7 +38,7 @@ async function logRequestLifecycle(ports, descriptor, run) {
28
38
  finish(levelForStatus(statusCode), statusCode === void 0 ? "no status" : String(statusCode));
29
39
  return result;
30
40
  } catch (error) {
31
- finish("error", `threw ${error instanceof Error ? error.name : typeof error}`);
41
+ finish("error", `threw ${error instanceof Error ? error.name : typeof error}`, error);
32
42
  throw error;
33
43
  }
34
44
  }
@@ -1 +1 @@
1
- {"version":3,"file":"log-request-lifecycle.mjs","names":[],"sources":["../../../../../../../core/src/router/log-request-lifecycle.ts"],"sourcesContent":["/**\n * Both ends of a request's log entry.\n *\n * ## Why the completion line exists\n *\n * The router logged `Starting Request: <id>` and nothing else. A request that\n * hung for thirty seconds and one that returned in two milliseconds produced\n * **byte-identical output**, so the log could not answer the one question\n * anyone opens it to ask.\n *\n * Note what \"detecting a hang\" actually means. Nothing can log the completion\n * of a request that never completes — the mechanism is the **absence** of a\n * completion line beside a start line that has one. That only works if the\n * completion line is emitted on every settled path, **including a throw**,\n * which is why the error path here is not an afterthought.\n *\n * ## Why the level tracks the status\n *\n * A handled 500 does not throw; it returns a response. Logging it at `info`\n * would bury the exact entries someone scanning the log is hunting for, so the\n * level is derived from the outcome: informational below 400, a warning for\n * client errors, an error for server errors and for anything that threw.\n *\n * ## Ports rather than a direct `log` import\n *\n * The behaviour worth pinning down is *which lines come out, in which order,\n * at which level, when the run throws*. Injecting the sink and the clock makes\n * that assertable without a server, a socket or a fake timer.\n */\n\nexport type RequestLogEntry = {\n module: string;\n action: string;\n message: string;\n /**\n * Typed as the logger accepts it, not as `unknown`. These entries exist to be\n * handed to `log.info` / `warn` / `error`, whose parameter is\n * `Record<string, any>` — `unknown` was not assignable, so the adapter in\n * router.ts could not compile even though every real caller passes an object.\n */\n context?: Record<string, any>;\n};\n\nexport type RequestLogPorts = {\n info(entry: RequestLogEntry): void;\n warn(entry: RequestLogEntry): void;\n error(entry: RequestLogEntry): void;\n /** Monotonic milliseconds. Called exactly twice per request. */\n now(): number;\n};\n\nexport type RequestLogDescriptor = {\n module: string;\n action: string;\n requestId: string;\n /**\n * Typed as the logger accepts it, not as `unknown`. These entries exist to be\n * handed to `log.info` / `warn` / `error`, whose parameter is\n * `Record<string, any>` — `unknown` was not assignable, so the adapter in\n * router.ts could not compile even though every real caller passes an object.\n */\n context?: Record<string, any>;\n /**\n * Read AFTER the run settles — the status is decided during the request, so\n * capturing it up front would report the default on every entry.\n */\n statusCode(): number | undefined;\n};\n\ntype Level = \"info\" | \"warn\" | \"error\";\n\nfunction levelForStatus(statusCode: number | undefined): Level {\n // An unknown status is not evidence of a problem; saying \"error\" because we\n // failed to read a number would be inventing a defect.\n if (statusCode === undefined) return \"info\";\n\n if (statusCode >= 500) return \"error\";\n\n if (statusCode >= 400) return \"warn\";\n\n return \"info\";\n}\n\nexport async function logRequestLifecycle<TResult>(\n ports: RequestLogPorts,\n descriptor: RequestLogDescriptor,\n run: () => Promise<TResult>,\n): Promise<TResult> {\n const startedAt = ports.now();\n\n ports.info({\n module: descriptor.module,\n action: descriptor.action,\n message: `Starting Request: ${descriptor.requestId}`,\n context: descriptor.context,\n });\n\n const finish = (level: Level, outcome: string): void => {\n const duration = Math.round(ports.now() - startedAt);\n\n ports[level]({\n module: descriptor.module,\n action: descriptor.action,\n message: `Completed Request: ${descriptor.requestId} — ${outcome} in ${duration}ms`,\n context: descriptor.context,\n });\n };\n\n try {\n const result = await run();\n\n const statusCode = descriptor.statusCode();\n\n finish(levelForStatus(statusCode), statusCode === undefined ? \"no status\" : String(statusCode));\n\n return result;\n } catch (error) {\n // The throw is reported and then re-thrown untouched: this function\n // observes the request, it does not own its error handling.\n finish(\"error\", `threw ${error instanceof Error ? error.name : typeof error}`);\n\n throw error;\n }\n}\n"],"mappings":";AAuEA,SAAS,eAAe,YAAuC;CAG7D,IAAI,eAAe,QAAW,OAAO;CAErC,IAAI,cAAc,KAAK,OAAO;CAE9B,IAAI,cAAc,KAAK,OAAO;CAE9B,OAAO;AACT;AAEA,eAAsB,oBACpB,OACA,YACA,KACkB;CAClB,MAAM,YAAY,MAAM,IAAI;CAE5B,MAAM,KAAK;EACT,QAAQ,WAAW;EACnB,QAAQ,WAAW;EACnB,SAAS,qBAAqB,WAAW;EACzC,SAAS,WAAW;CACtB,CAAC;CAED,MAAM,UAAU,OAAc,YAA0B;EACtD,MAAM,WAAW,KAAK,MAAM,MAAM,IAAI,IAAI,SAAS;EAEnD,MAAM,MAAM,CAAC;GACX,QAAQ,WAAW;GACnB,QAAQ,WAAW;GACnB,SAAS,sBAAsB,WAAW,UAAU,KAAK,QAAQ,MAAM,SAAS;GAChF,SAAS,WAAW;EACtB,CAAC;CACH;CAEA,IAAI;EACF,MAAM,SAAS,MAAM,IAAI;EAEzB,MAAM,aAAa,WAAW,WAAW;EAEzC,OAAO,eAAe,UAAU,GAAG,eAAe,SAAY,cAAc,OAAO,UAAU,CAAC;EAE9F,OAAO;CACT,SAAS,OAAO;EAGd,OAAO,SAAS,SAAS,iBAAiB,QAAQ,MAAM,OAAO,OAAO,OAAO;EAE7E,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"log-request-lifecycle.mjs","names":[],"sources":["../../../../../../../core/src/router/log-request-lifecycle.ts"],"sourcesContent":["/**\n * Both ends of a request's log entry.\n *\n * ## Why the completion line exists\n *\n * The router logged `Starting Request: <id>` and nothing else. A request that\n * hung for thirty seconds and one that returned in two milliseconds produced\n * **byte-identical output**, so the log could not answer the one question\n * anyone opens it to ask.\n *\n * Note what \"detecting a hang\" actually means. Nothing can log the completion\n * of a request that never completes — the mechanism is the **absence** of a\n * completion line beside a start line that has one. That only works if the\n * completion line is emitted on every settled path, **including a throw**,\n * which is why the error path here is not an afterthought.\n *\n * ## Why the level tracks the status\n *\n * A handled 500 does not throw; it returns a response. Logging it at `info`\n * would bury the exact entries someone scanning the log is hunting for, so the\n * level is derived from the outcome: informational below 400, a warning for\n * client errors, an error for server errors and for anything that threw.\n *\n * ## Ports rather than a direct `log` import\n *\n * The behaviour worth pinning down is *which lines come out, in which order,\n * at which level, when the run throws*. Injecting the sink and the clock makes\n * that assertable without a server, a socket or a fake timer.\n *\n * ## Tracing\n *\n * This function is the single funnel for both the success and throw paths\n * (the try/catch below), and it already reads the settled status via\n * `descriptor.statusCode()` after the run settles — the natural place to\n * fire `onRequestStart` / `onRequestEnd`, since that is when the response is\n * actually written and a trace can record what really happened. Gated on\n * `isTracingEnabled()` before building any context object, so a disabled app\n * pays one boolean check and allocates nothing extra.\n */\nimport type { Request } from \"../http/request\";\nimport { buildTracingContext, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled } from \"../http/tracing\";\n\nexport type RequestLogEntry = {\n module: string;\n action: string;\n message: string;\n /**\n * Typed as the logger accepts it, not as `unknown`. These entries exist to be\n * handed to `log.info` / `warn` / `error`, whose parameter is\n * `Record<string, any>` — `unknown` was not assignable, so the adapter in\n * router.ts could not compile even though every real caller passes an object.\n */\n context?: Record<string, any>;\n};\n\nexport type RequestLogPorts = {\n info(entry: RequestLogEntry): void;\n warn(entry: RequestLogEntry): void;\n error(entry: RequestLogEntry): void;\n /** Monotonic milliseconds. Called exactly twice per request. */\n now(): number;\n};\n\nexport type RequestLogDescriptor = {\n module: string;\n action: string;\n requestId: string;\n /**\n * Typed as the logger accepts it, not as `unknown`. These entries exist to be\n * handed to `log.info` / `warn` / `error`, whose parameter is\n * `Record<string, any>` — `unknown` was not assignable, so the adapter in\n * router.ts could not compile even though every real caller passes an object.\n */\n context?: Record<string, any>;\n /**\n * Read AFTER the run settles — the status is decided during the request, so\n * capturing it up front would report the default on every entry.\n */\n statusCode(): number | undefined;\n /**\n * The `Request` instance, when tracing needs it to build\n * the `TracingContext` for `onRequestStart` / `onRequestEnd`. Optional —\n * absent, tracing dispatch for this request is skipped, which is correct\n * for any non-HTTP caller of this same lifecycle wrapper.\n */\n request?: Request;\n};\n\ntype Level = \"info\" | \"warn\" | \"error\";\n\nfunction levelForStatus(statusCode: number | undefined): Level {\n // An unknown status is not evidence of a problem; saying \"error\" because we\n // failed to read a number would be inventing a defect.\n if (statusCode === undefined) return \"info\";\n\n if (statusCode >= 500) return \"error\";\n\n if (statusCode >= 400) return \"warn\";\n\n return \"info\";\n}\n\nexport async function logRequestLifecycle<TResult>(\n ports: RequestLogPorts,\n descriptor: RequestLogDescriptor,\n run: () => Promise<TResult>,\n): Promise<TResult> {\n const startedAt = ports.now();\n const tracingEnabled = isTracingEnabled();\n\n ports.info({\n module: descriptor.module,\n action: descriptor.action,\n message: `Starting Request: ${descriptor.requestId}`,\n context: descriptor.context,\n });\n\n if (tracingEnabled && descriptor.request) {\n dispatchRequestStart(buildTracingContext(descriptor.request));\n }\n\n const finish = (level: Level, outcome: string, error?: unknown): void => {\n const duration = Math.round(ports.now() - startedAt);\n\n ports[level]({\n module: descriptor.module,\n action: descriptor.action,\n message: `Completed Request: ${descriptor.requestId} — ${outcome} in ${duration}ms`,\n context: descriptor.context,\n });\n\n if (tracingEnabled && descriptor.request) {\n dispatchRequestEnd(buildTracingContext(descriptor.request), {\n status: descriptor.statusCode(),\n durationMs: duration,\n error,\n });\n }\n };\n\n try {\n const result = await run();\n\n const statusCode = descriptor.statusCode();\n\n finish(levelForStatus(statusCode), statusCode === undefined ? \"no status\" : String(statusCode));\n\n return result;\n } catch (error) {\n // The throw is reported and then re-thrown untouched: this function\n // observes the request, it does not own its error handling.\n finish(\"error\", `threw ${error instanceof Error ? error.name : typeof error}`, error);\n\n throw error;\n }\n}\n"],"mappings":";;;;AA0FA,SAAS,eAAe,YAAuC;CAG7D,IAAI,eAAe,QAAW,OAAO;CAErC,IAAI,cAAc,KAAK,OAAO;CAE9B,IAAI,cAAc,KAAK,OAAO;CAE9B,OAAO;AACT;AAEA,eAAsB,oBACpB,OACA,YACA,KACkB;CAClB,MAAM,YAAY,MAAM,IAAI;CAC5B,MAAM,iBAAiB,iBAAiB;CAExC,MAAM,KAAK;EACT,QAAQ,WAAW;EACnB,QAAQ,WAAW;EACnB,SAAS,qBAAqB,WAAW;EACzC,SAAS,WAAW;CACtB,CAAC;CAED,IAAI,kBAAkB,WAAW,SAC/B,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,QAAgB,CAAA,GAAI,OAAA,CAAQ,CAAA,IAC3B,OAAA,CAAQ,CAAA;EAxOG;;;;;EAyQP,wBAAA,CAAyB,UAAA;EAlQnB;;;;;;;;EA4RA,0BAAA,IACX,WAAA,EAAa,QAAA,UACb,OAAA,QAAe,CAAA,GAAI,OAAA,CAAQ,CAAA,IAC1B,OAAA,CAAQ,CAAA;EAxRqD;;;EAAA,QAsUxD,gBAAA;EA/T8B;;;EA2Y/B,IAAA,IAAI,KAAA;EApYJ;;;;;;;;EAgZA,UAAA;EA/XI;;;EAsYJ,IAAA,CAAK,MAAA,EAAQ,eAAA;EApYP;;;;EAibN,aAAA,CAAc,MAAA,EAAQ,eAAA;EAhbgB;;;EAuiBtC,QAAA,CAAS,IAAA,UAAc,MAAA;EAhcvB;;;EAAA,QAqdC,WAAA;AAAA;AAAA,cA8DG,MAAA,EAAM,MAAuB"}
@@ -1,3 +1,5 @@
1
+ import { buildTracingContext, dispatchPhase, isTracingEnabled } from "../http/tracing/tracing-dispatcher.mjs";
2
+ import "../http/tracing/index.mjs";
1
3
  import { normalizeRoutePath } from "./normalize-route-path.mjs";
2
4
  import { forgetPositionalHandlerSuspects, inspectHandlerSignature, reportPositionalHandlerSuspects } from "./positional-handler-diagnostics.mjs";
3
5
  import { routeNameMethodSuffix } from "./route-name-method-suffix.mjs";
@@ -605,7 +607,14 @@ var Router = class Router {
605
607
  response.setResponse(fastifyResponse);
606
608
  request.response = response;
607
609
  response.request = request;
610
+ const tracingEnabled = isTracingEnabled();
611
+ const routeMatchStartedAt = tracingEnabled ? performance.now() : 0;
608
612
  request.setRequest(fastifyRequest).setRoute(route);
613
+ if (tracingEnabled) dispatchPhase(buildTracingContext(request), {
614
+ name: "route.match",
615
+ durationMs: performance.now() - routeMatchStartedAt,
616
+ attrs: { route: route.path }
617
+ });
609
618
  return {
610
619
  output: await logRequestLifecycle({
611
620
  info: (entry) => log.info(entry),
@@ -620,6 +629,7 @@ var Router = class Router {
620
629
  request,
621
630
  response
622
631
  },
632
+ request,
623
633
  statusCode: () => fastifyResponse.statusCode
624
634
  }, () => request.execute()),
625
635
  response,