@forinda/kickjs 10.7.0 → 10.9.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.
- package/dist/{adapter-9sPr_5xt.d.mts → adapter-DLjn8q0c.d.mts} +14 -8
- package/dist/adapter-DLjn8q0c.d.mts.map +1 -0
- package/dist/{app-module-Cuu-Ma_E.d.mts → app-module-Bk3glnPP.d.mts} +3 -3
- package/dist/{app-module-Cuu-Ma_E.d.mts.map → app-module-Bk3glnPP.d.mts.map} +1 -1
- package/dist/application-2cqnmnMR.mjs +14 -0
- package/dist/application-2cqnmnMR.mjs.map +1 -0
- package/dist/{application-BZjDmsWb.d.mts → application-w0Xnc35j.d.mts} +54 -14
- package/dist/application-w0Xnc35j.d.mts.map +1 -0
- package/dist/{background-BJjLKrnK.mjs → background-X_AU4qmI.mjs} +3 -3
- package/dist/{background-BJjLKrnK.mjs.map → background-X_AU4qmI.mjs.map} +1 -1
- package/dist/{reply-BVdki3Z4.mjs → body-policy-BkjZt30w.mjs} +3 -3
- package/dist/body-policy-BkjZt30w.mjs.map +1 -0
- package/dist/{bootstrap-Dxax6Mcp.mjs → bootstrap-CF5TB3dt.mjs} +3 -3
- package/dist/{bootstrap-Dxax6Mcp.mjs.map → bootstrap-CF5TB3dt.mjs.map} +1 -1
- package/dist/{bounded-counters-_6sdDRhT.mjs → bounded-counters-BdHZ2tZ9.mjs} +2 -2
- package/dist/{bounded-counters-_6sdDRhT.mjs.map → bounded-counters-BdHZ2tZ9.mjs.map} +1 -1
- package/dist/{cache-C0qL0NSD.d.mts → cache-CdRHSXow.d.mts} +10 -7
- package/dist/cache-CdRHSXow.d.mts.map +1 -0
- package/dist/{client-ip-CrO5ktYs.mjs → client-ip-Db1WMxl6.mjs} +2 -2
- package/dist/{client-ip-CrO5ktYs.mjs.map → client-ip-Db1WMxl6.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-CWKj0Z66.mjs → config-DeWWBNz5.mjs} +3 -3
- package/dist/config-DeWWBNz5.mjs.map +1 -0
- package/dist/{context-BlJRkMyq.mjs → context-CfGBpRlD.mjs} +3 -3
- package/dist/{context-BlJRkMyq.mjs.map → context-CfGBpRlD.mjs.map} +1 -1
- package/dist/{context-errors-ykpXYECS.mjs → context-errors-QfmGMX4-.mjs} +2 -2
- package/dist/{context-errors-ykpXYECS.mjs.map → context-errors-QfmGMX4-.mjs.map} +1 -1
- package/dist/{contributor-runner-BM-5Wr19.mjs → contributor-runner-DmHsL9iD.mjs} +3 -3
- package/dist/{contributor-runner-BM-5Wr19.mjs.map → contributor-runner-DmHsL9iD.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.d.mts +1 -1
- package/dist/core/cache.mjs +2 -2
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.d.mts +2 -2
- package/dist/core/reactivity.mjs +2 -2
- package/dist/core/reactivity.mjs.map +1 -1
- package/dist/core-DaYy5tKw.mjs +12 -0
- package/dist/{core-DlrlhjF4.mjs.map → core-DaYy5tKw.mjs.map} +1 -1
- package/dist/{csrf-ZFOrJZhJ.d.mts → csrf-w5bc-PGs.d.mts} +2 -2
- package/dist/{csrf-ZFOrJZhJ.d.mts.map → csrf-w5bc-PGs.d.mts.map} +1 -1
- package/dist/{decorate-BHhpOfEF.mjs → decorate-8MLQUvoW.mjs} +4 -4
- package/dist/{decorate-BHhpOfEF.mjs.map → decorate-8MLQUvoW.mjs.map} +1 -1
- package/dist/{decorators-Dvy0JZ5L.d.mts → decorators-DxNb5mWw.d.mts} +15 -2
- package/dist/{decorators-Dvy0JZ5L.d.mts.map → decorators-DxNb5mWw.d.mts.map} +1 -1
- package/dist/{define-adapter-CF-DJRq9.mjs → define-adapter-By20TI53.mjs} +2 -2
- package/dist/{define-adapter-CF-DJRq9.mjs.map → define-adapter-By20TI53.mjs.map} +1 -1
- package/dist/{di-hooks-CCKeiLT-.mjs → di-hooks-CGr13ce2.mjs} +7 -5
- package/dist/{di-hooks-CCKeiLT-.mjs.map → di-hooks-CGr13ce2.mjs.map} +1 -1
- package/dist/{disposables-bnkL4rG7.mjs → disposables-V3Xlgvgk.mjs} +1 -1
- package/dist/{error-handler-CH4PPZCK.d.mts → error-handler-BrihKETE.d.mts} +2 -2
- package/dist/{error-handler-CH4PPZCK.d.mts.map → error-handler-BrihKETE.d.mts.map} +1 -1
- package/dist/express-CZHu70JR.mjs +12 -0
- package/dist/express-CZHu70JR.mjs.map +1 -0
- package/dist/{express-lazy-D9MZnma8.mjs → express-lazy-BixrSsYx.mjs} +3 -3
- package/dist/{express-lazy-D9MZnma8.mjs.map → express-lazy-BixrSsYx.mjs.map} +1 -1
- package/dist/handler-DFZIsJH1.mjs +12 -0
- package/dist/handler-DFZIsJH1.mjs.map +1 -0
- package/dist/{host-CtpcIKcA.mjs → host-CJdqJGsr.mjs} +2 -2
- package/dist/{host-CtpcIKcA.mjs.map → host-CJdqJGsr.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +2 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +2 -2
- package/dist/http/runtimes/express.d.mts.map +1 -1
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +4 -2
- package/dist/http/runtimes/fastify.d.mts.map +1 -1
- package/dist/http/runtimes/fastify.mjs +3 -3
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/{index-B4aOLoId.d.mts → index-CNBYZDto.d.mts} +4 -4
- package/dist/{index-B4aOLoId.d.mts.map → index-CNBYZDto.d.mts.map} +1 -1
- package/dist/index.d.mts +15 -15
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{is-production-BfIKY2Sw.mjs → is-production-CMJW948J.mjs} +2 -2
- package/dist/{is-production-BfIKY2Sw.mjs.map → is-production-CMJW948J.mjs.map} +1 -1
- package/dist/{jobs-BJfIOWUT.mjs → jobs-d2j_7_9R.mjs} +3 -3
- package/dist/{jobs-BJfIOWUT.mjs.map → jobs-d2j_7_9R.mjs.map} +1 -1
- package/dist/{kv-stores-C1sQs2Rb.d.mts → kv-stores-DJBnGQsJ.d.mts} +3 -3
- package/dist/{kv-stores-C1sQs2Rb.d.mts.map → kv-stores-DJBnGQsJ.d.mts.map} +1 -1
- package/dist/{kv-stores-BeDHfiyW.mjs → kv-stores-u0V_K-2O.mjs} +3 -3
- package/dist/{kv-stores-BeDHfiyW.mjs.map → kv-stores-u0V_K-2O.mjs.map} +1 -1
- package/dist/{lazy-serve-static-BUMcYDMn.mjs → lazy-serve-static-kB1m23xS.mjs} +3 -3
- package/dist/{lazy-serve-static-BUMcYDMn.mjs.map → lazy-serve-static-kB1m23xS.mjs.map} +1 -1
- package/dist/{metadata-x0eCJRTl.mjs → metadata-c1TNXrm_.mjs} +1 -1
- package/dist/{observers-Ss6-7Si7.mjs → observers-vX5EpqCX.mjs} +2 -2
- package/dist/{observers-Ss6-7Si7.mjs.map → observers-vX5EpqCX.mjs.map} +1 -1
- package/dist/{precompressed-BBXQUDXp.mjs → precompressed-DIkilvFq.mjs} +2 -2
- package/dist/{precompressed-BBXQUDXp.mjs.map → precompressed-DIkilvFq.mjs.map} +1 -1
- package/dist/{query-DIS_2QiJ.mjs → query-BIGYogvJ.mjs} +2 -2
- package/dist/{query-DIS_2QiJ.mjs.map → query-BIGYogvJ.mjs.map} +1 -1
- package/dist/{reactivity-BkMNA0kp.d.mts → reactivity-DZrc3Yhu.d.mts} +50 -15
- package/dist/reactivity-DZrc3Yhu.d.mts.map +1 -0
- package/dist/reply-CtSYYFK5.mjs +12 -0
- package/dist/reply-CtSYYFK5.mjs.map +1 -0
- package/dist/{request-scope-BTdpkAqv.mjs → request-scope-B1GH3d99.mjs} +3 -3
- package/dist/{request-scope-BTdpkAqv.mjs.map → request-scope-B1GH3d99.mjs.map} +1 -1
- package/dist/{respond-BUWP_L0Y.mjs → respond-D8cMACHW.mjs} +2 -2
- package/dist/{respond-BUWP_L0Y.mjs.map → respond-D8cMACHW.mjs.map} +1 -1
- package/dist/{rolldown-runtime-Dp0gGuQG.mjs → rolldown-runtime-CSRdE5Vk.mjs} +1 -1
- package/dist/{route-flag-p89Wzt0D.mjs → route-flag-Ce2FkkeT.mjs} +3 -3
- package/dist/{route-flag-p89Wzt0D.mjs.map → route-flag-Ce2FkkeT.mjs.map} +1 -1
- package/dist/{route-policy-DJMiiTrD.mjs → route-policy-BRcI3gmZ.mjs} +2 -2
- package/dist/{route-policy-DJMiiTrD.mjs.map → route-policy-BRcI3gmZ.mjs.map} +1 -1
- package/dist/{router-builder-dCWA4pdK.mjs → router-builder-BgxacQbc.mjs} +3 -3
- package/dist/router-builder-BgxacQbc.mjs.map +1 -0
- package/dist/{router-builder-BfbEdxew.d.mts → router-builder-CPJHwoL1.d.mts} +2 -2
- package/dist/{router-builder-BfbEdxew.d.mts.map → router-builder-CPJHwoL1.d.mts.map} +1 -1
- package/dist/{settings-BnE75hnr.d.mts → settings-BFQisfqG.d.mts} +2 -2
- package/dist/{settings-BnE75hnr.d.mts.map → settings-BFQisfqG.d.mts.map} +1 -1
- package/dist/{settings-BHYpcj_p.mjs → settings-hE0ewJKF.mjs} +3 -3
- package/dist/{settings-BHYpcj_p.mjs.map → settings-hE0ewJKF.mjs.map} +1 -1
- package/dist/token-0ZP--xsp.d.mts +3 -0
- package/dist/{token-Cz4YKuL-.mjs → token-DNQnEuMJ.mjs} +2 -2
- package/dist/{upload-Jgs9BFC4.d.mts → upload-DtQ1pdQw.d.mts} +3 -3
- package/dist/upload-DtQ1pdQw.d.mts.map +1 -0
- package/dist/upload-config-ikC1nZgF.mjs +12 -0
- package/dist/upload-config-ikC1nZgF.mjs.map +1 -0
- package/dist/{url-for-CDxa8ik-.mjs → url-for-Bh43Ax1C.mjs} +3 -3
- package/dist/{url-for-CDxa8ik-.mjs.map → url-for-Bh43Ax1C.mjs.map} +1 -1
- package/dist/{web-crypto-Bijc63tB.mjs → web-crypto-Dx8Nmh16.mjs} +2 -2
- package/dist/{web-crypto-Bijc63tB.mjs.map → web-crypto-Dx8Nmh16.mjs.map} +1 -1
- package/dist/web.d.mts +5 -5
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +11 -11
- package/dist/adapter-9sPr_5xt.d.mts.map +0 -1
- package/dist/application-BSzwuTQ6.mjs +0 -14
- package/dist/application-BSzwuTQ6.mjs.map +0 -1
- package/dist/application-BZjDmsWb.d.mts.map +0 -1
- package/dist/cache-C0qL0NSD.d.mts.map +0 -1
- package/dist/config-CWKj0Z66.mjs.map +0 -1
- package/dist/core-DlrlhjF4.mjs +0 -12
- package/dist/express-4fvuMB5q.mjs +0 -12
- package/dist/express-4fvuMB5q.mjs.map +0 -1
- package/dist/handler-TzaD8jPN.mjs +0 -12
- package/dist/handler-TzaD8jPN.mjs.map +0 -1
- package/dist/reactivity-BkMNA0kp.d.mts.map +0 -1
- package/dist/reply-BVdki3Z4.mjs.map +0 -1
- package/dist/router-builder-dCWA4pdK.mjs.map +0 -1
- package/dist/token-D6jfTQLA.d.mts +0 -3
- package/dist/upload-Jgs9BFC4.d.mts.map +0 -1
- package/dist/upload-config-CkMQ5bW5.mjs +0 -12
- package/dist/upload-config-CkMQ5bW5.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"application-2cqnmnMR.mjs","names":["log"],"sources":["../src/core/mount-sort.ts","../src/http/tracing.ts","../src/http/startup-timeline.ts","../src/core/adapter-conditions.ts","../src/core/failure-analysis.ts","../src/http/startup-checks.ts","../src/http/health-module.ts","../src/http/loopback.ts","../src/http/application.ts"],"sourcesContent":["/**\n * Topological sort for plugins and adapters with `dependsOn` declarations.\n *\n * Mirrors the algorithm used by the Context Contributor pipeline\n * (`contributor-pipeline.ts:topoSort`) but operates on a name-keyed\n * `MountSortItem` shape rather than a `ContributorRegistration`. Kept\n * standalone instead of factored generic so that:\n *\n * 1. The contributor pipeline doesn't need refactoring (risk reduction).\n * 2. The error classes can carry plugin/adapter-specific diagnostic\n * fields (`kind`, `dependent`) without bending the contributor types.\n */\n\n/**\n * A plugin or adapter that participates in dependency-ordered mounting.\n * Both `KickPlugin` and `AppAdapter` satisfy this shape via their `name`\n * and `dependsOn` fields.\n */\nexport interface MountSortItem {\n /** Unique mount name within the plugin/adapter set being sorted. */\n name: string\n /**\n * Other plugin/adapter names that must mount before this one. Cycles\n * and missing names fail at boot — same fail-fast contract as the\n * Context Contributor pipeline (architecture.md §20.4).\n */\n dependsOn?: readonly string[]\n}\n\n/** What kind of mount set the sort is operating on — surfaces in error messages. */\nexport type MountKind = 'plugin' | 'adapter'\n\n/**\n * Two items in the same mount set declared the same `name`. Plugin/adapter\n * names must be unique so `dependsOn` references resolve unambiguously.\n */\nexport class DuplicateMountNameError extends Error {\n readonly kind: MountKind\n readonly mountName: string\n\n constructor(kind: MountKind, mountName: string) {\n super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`)\n this.name = 'DuplicateMountNameError'\n this.kind = kind\n this.mountName = mountName\n }\n}\n\n/**\n * A `dependsOn` entry references a plugin/adapter that isn't in the\n * current set. The dependency might not be installed, might be misspelled,\n * or might live in a different mount set (plugin referencing an adapter,\n * or vice versa — they sort independently).\n */\nexport class MissingMountDepError extends Error {\n readonly kind: MountKind\n readonly missing: string\n readonly dependent: string\n\n constructor(kind: MountKind, missing: string, dependent: string) {\n super(\n `Missing ${kind} dependency '${missing}' required by '${dependent}' — ` +\n `is the ${kind} installed and named correctly?`,\n )\n this.name = 'MissingMountDepError'\n this.kind = kind\n this.missing = missing\n this.dependent = dependent\n }\n}\n\n/**\n * The `dependsOn` declarations form a cycle. Boot fails so the cycle\n * can't poison live traffic. The `cycle` field reports one path through\n * the offending nodes for diagnostics — formatted `A → B → C → A`.\n */\nexport class MountCycleError extends Error {\n readonly kind: MountKind\n readonly cycle: readonly string[]\n\n constructor(kind: MountKind, cycle: readonly string[]) {\n super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(' → ')}`)\n this.name = 'MountCycleError'\n this.kind = kind\n this.cycle = Object.freeze([...cycle])\n }\n}\n\n/**\n * Topologically sort `items` so every item with `dependsOn: ['X']` mounts\n * after `X`. Items without `dependsOn` keep their input order via Kahn's\n * algorithm with a FIFO queue seeded in input order — preserves the\n * historical \"plugins/adapters mount in declaration order\" behaviour for\n * any set that doesn't use `dependsOn`.\n *\n * @param items - mountable items, e.g. plugins or adapters\n * @param kind - 'plugin' | 'adapter', used in error messages\n * @returns a new array in valid mount order\n * @throws {DuplicateMountNameError} two items share a name\n * @throws {MissingMountDepError} a `dependsOn` references an unknown name\n * @throws {MountCycleError} the dep graph contains a cycle\n */\nexport function mountSort<T extends MountSortItem>(items: readonly T[], kind: MountKind): T[] {\n const byName = new Map<string, T>()\n for (const item of items) {\n if (byName.has(item.name)) {\n throw new DuplicateMountNameError(kind, item.name)\n }\n byName.set(item.name, item)\n }\n\n // indegree[name] = number of unresolved deps for that item\n const indegree = new Map<string, number>()\n // dependents[depName] = items that depend on depName\n const dependents = new Map<string, T[]>()\n\n for (const item of items) {\n indegree.set(item.name, item.dependsOn?.length ?? 0)\n }\n for (const item of items) {\n for (const dep of item.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new MissingMountDepError(kind, dep, item.name)\n }\n const list = dependents.get(dep) ?? []\n list.push(item)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: items with zero indegree, preserving input order.\n const queue: T[] = []\n for (const item of items) {\n if (indegree.get(item.name) === 0) queue.push(item)\n }\n\n const sorted: T[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.name) ?? []) {\n const next = (indegree.get(dependent.name) ?? 0) - 1\n indegree.set(dependent.name, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== items.length) {\n const remaining = items.filter((it) => (indegree.get(it.name) ?? 0) > 0)\n throw new MountCycleError(kind, reconstructCycle(remaining, byName))\n }\n\n return sorted\n}\n\n/**\n * Walk the residual graph to find one cycle path for diagnostics.\n * Starts from the first remaining node and follows the first dep that's\n * still in the residual set until we revisit a node. Returns a path\n * starting and ending with the same name so the message reads naturally\n * (`A → B → C → A`).\n */\nfunction reconstructCycle<T extends MountSortItem>(\n residual: readonly T[],\n byName: ReadonlyMap<string, T>,\n): string[] {\n const residualNames = new Set(residual.map((r) => r.name))\n const start = residual[0].name\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor = start\n\n while (true) {\n const item = byName.get(cursor)!\n const nextDep = item.dependsOn?.find((d) => residualNames.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n return path\n}\n","/**\n * `diagnostics_channel` publishing for the Node server — how APM agents,\n * OpenTelemetry instrumentations and the DevTools subscribe without being an\n * adapter or plugin. Every channel is free when nobody subscribes: each\n * publish is guarded by `hasSubscribers`.\n *\n * | Channel | Kind | Payload |\n * | --- | --- | --- |\n * | `kickjs:handler` | tracing channel (`start` / `end` / `asyncStart` / `asyncEnd` / `error`) | {@link HandlerTraceContext} |\n * | `kickjs:error` | channel | `{ error, ...ErrorInfo }` |\n * | `kickjs:response` | channel | `ResponseInfo` |\n *\n * `kickjs:handler` wraps the controller method itself, so a span started on\n * `start` covers the handler and follows its async work.\n *\n * Node-only (imported by the Application, never by the web entry).\n *\n * @module @forinda/kickjs/http/tracing\n */\nimport diagnostics from 'node:diagnostics_channel'\nimport { setObserverPublisher, type ErrorInfo, type ResponseInfo } from '../core/observers'\nimport type { CtxHandler } from './runtime'\nimport type { RequestContext } from './context'\n\nexport const HANDLER_CHANNEL = 'kickjs:handler'\nexport const ERROR_CHANNEL = 'kickjs:error'\nexport const RESPONSE_CHANNEL = 'kickjs:response'\n\n/** What subscribers to `kickjs:handler` receive. */\nexport interface HandlerTraceContext {\n method: string\n /** The route pattern, e.g. `/api/v1/users/:id` — the span name APMs want. */\n route: string\n controller?: string\n handler?: string\n requestId?: string\n ctx: RequestContext\n}\n\nconst handlerChannel = diagnostics.tracingChannel<HandlerTraceContext>(HANDLER_CHANNEL)\nconst errorChannel = diagnostics.channel(ERROR_CHANNEL)\nconst responseChannel = diagnostics.channel(RESPONSE_CHANNEL)\n\n/** Feed the error / response channels from the observer funnel. Idempotent. */\nexport function installChannelPublisher(): void {\n setObserverPublisher(\n {\n name: 'diagnostics_channel',\n onError(error: unknown, info: ErrorInfo) {\n if (errorChannel.hasSubscribers) errorChannel.publish({ error, ...info })\n },\n onResponse(info: ResponseInfo) {\n if (responseChannel.hasSubscribers) responseChannel.publish(info)\n },\n },\n () => responseChannel.hasSubscribers,\n )\n}\n\n/**\n * Wrap a route's terminal handler in the `kickjs:handler` tracing channel.\n * With no subscriber the original handler runs untouched (same return value,\n * sync or async).\n */\nexport function traceHandler(\n handler: CtxHandler,\n meta: Omit<HandlerTraceContext, 'ctx' | 'requestId'>,\n): CtxHandler {\n return (ctx) => {\n if (!handlerChannel.hasSubscribers) return handler(ctx)\n return handlerChannel.tracePromise(async () => handler(ctx), {\n ...meta,\n requestId: ctx.requestId,\n ctx,\n })\n }\n}\n","/**\n * Where startup time goes: each phase of `setup()` / `start()`, and each\n * adapter hook on its own, so \"boot got slow\" points at a name.\n *\n * @module @forinda/kickjs/http/startup-timeline\n */\n\n/** One timed step, in the order it ran. */\nexport interface StartupStep {\n /** A phase (`'modules'`, `'routes'`, `'listen'`) or `'<Adapter>.<hook>'`. */\n name: string\n ms: number\n}\n\nexport interface StartupTimelineSnapshot {\n totalMs: number\n steps: readonly StartupStep[]\n}\n\nconst round = (ms: number) => Math.round(ms * 10) / 10\n\nexport class StartupTimeline {\n private readonly began = performance.now()\n private last = this.began\n private readonly steps: StartupStep[] = []\n /** Set by complete(): later snapshots stop counting idle runtime. */\n private completedAt: number | undefined\n\n /** Close a phase: the time since the previous step ended. */\n mark(name: string): void {\n const now = performance.now()\n this.steps.push({ name, ms: round(now - this.last) })\n this.last = now\n }\n\n /** Time one unit of work (an adapter hook) as its own step. */\n async time<T>(name: string, run: () => T | Promise<T>): Promise<T> {\n // Whatever ran since the last step belongs to the enclosing phase, which\n // the next mark() closes — so it is not charged to this step.\n const started = performance.now()\n const before = this.last\n try {\n return await run()\n } finally {\n const now = performance.now()\n this.steps.push({ name, ms: round(now - started) })\n // The phase resumes after this step: keep its time before the step.\n this.last = now - (started - before)\n }\n }\n\n /** Startup is over: freeze the total. */\n complete(): void {\n this.completedAt ??= performance.now()\n }\n\n snapshot(): StartupTimelineSnapshot {\n const end = this.completedAt ?? performance.now()\n return { totalMs: round(end - this.began), steps: [...this.steps] }\n }\n\n /** The `count` slowest steps, slowest first. */\n slowest(count: number): StartupStep[] {\n return this.steps.toSorted((a, b) => b.ms - a.ms).slice(0, count)\n }\n}\n","/**\n * Conditions that switch an adapter on or off at startup, with the reason\n * recorded — so \"why isn't Redis connected?\" has an answer in the boot report\n * rather than in the adapter's code.\n *\n * @module @forinda/kickjs/core/adapter-conditions\n */\nimport { createRequire } from 'node:module'\nimport { join } from 'node:path'\n\n/**\n * `true` keeps the adapter; `false` or a string (the reason) leaves it out.\n * Runs once at startup — keep it synchronous and free of side effects.\n */\nexport type AdapterCondition = () => boolean | string\n\n/** One adapter's outcome, as `app.getConditionReport()` lists it. */\nexport interface ConditionOutcome {\n adapter: string\n enabled: boolean\n /** Why it was left out; absent when enabled. */\n reason?: string\n}\n\n/**\n * On when the env variable is set (non-empty) — or equals `value`.\n *\n * when: onEnv('REDIS_URL')\n * when: onEnv('QUEUE_DRIVER', 'redis')\n */\nexport function onEnv(name: string, value?: string): AdapterCondition {\n return () => {\n const actual = process.env[name]\n if (value === undefined) return actual ? true : `${name} is not set`\n if (actual === value) return true\n // Never the value itself: reasons are logged and served by DevTools, and\n // the variable may hold a secret. The expected value is the app's own.\n return actual === undefined ? `${name} is not set` : `${name} is not '${value}'`\n }\n}\n\n/**\n * On when the app can import `name` — for an adapter that needs an optional\n * dependency.\n *\n * when: onPackage('ioredis')\n */\nexport function onPackage(name: string): AdapterCondition {\n return () => {\n // From the app's entry file first — the working directory can sit outside\n // the app's package tree (a process manager, a monorepo root) — then from\n // the working directory.\n const bases = [process.argv[1], join(process.cwd(), 'package.json')].filter(\n (base): base is string => typeof base === 'string' && base.length > 0,\n )\n for (const base of bases) {\n try {\n createRequire(base).resolve(name)\n return true\n } catch {\n // Try the next base.\n }\n }\n return `package '${name}' is not installed`\n }\n}\n\n/** On only when every condition is — the first that fails gives the reason. */\nexport function allOf(...conditions: AdapterCondition[]): AdapterCondition {\n return () => {\n for (const condition of conditions) {\n const result = condition()\n if (result !== true) return result\n }\n return true\n }\n}\n\n/**\n * `true`, or the reason it is off. A throwing condition is off; its error goes\n * to `onError` (the server log), not into the reason, which DevTools serves —\n * error messages can carry connection strings.\n */\nexport function evaluateCondition(\n condition: AdapterCondition,\n onError?: (err: unknown) => void,\n): true | string {\n try {\n const result = condition()\n if (result === true) return true\n return typeof result === 'string' && result.length > 0 ? result : 'its condition returned false'\n } catch (err) {\n onError?.(err)\n return 'its condition threw (see the server log)'\n }\n}\n","/**\n * Turn a startup failure into advice: what went wrong in words, and what to\n * change — instead of a driver's stack trace that names a socket.\n *\n * @module @forinda/kickjs/core/failure-analysis\n */\n\n/** What an analyzer says about an error it recognises. */\nexport interface FailureAdvice {\n summary: string\n cause?: string\n fix: string\n}\n\ntype ErrnoLike = {\n code?: unknown\n address?: unknown\n port?: unknown\n hostname?: unknown\n message?: unknown\n}\n\n/** The error, or the first error in its `cause` chain / AggregateError, with this errno code. */\nfunction findCode(err: unknown, codes: readonly string[], depth = 0): ErrnoLike | undefined {\n if (!err || typeof err !== 'object' || depth > 5) return undefined\n const e = err as ErrnoLike & { cause?: unknown; errors?: unknown[] }\n if (typeof e.code === 'string' && codes.includes(e.code)) return e\n for (const inner of [e.cause, ...(Array.isArray(e.errors) ? e.errors : [])]) {\n const found = findCode(inner, codes, depth + 1)\n if (found) return found\n }\n return undefined\n}\n\n/** Whether the error, or one in its `cause` chain / AggregateError, has a matching message. */\nfunction findMessage(err: unknown, pattern: RegExp, depth = 0): boolean {\n if (!err || typeof err !== 'object' || depth > 5) return false\n const e = err as { message?: unknown; cause?: unknown; errors?: unknown[] }\n if (typeof e.message === 'string' && pattern.test(e.message)) return true\n return [e.cause, ...(Array.isArray(e.errors) ? e.errors : [])].some((inner) =>\n findMessage(inner, pattern, depth + 1),\n )\n}\n\nconst CREDENTIALS_REJECTED =\n /password authentication failed|access denied for user|authentication failed|NOAUTH|WRONGPASS/i\n\nconst target = (e: ErrnoLike) =>\n typeof e.address === 'string'\n ? `${e.address}${typeof e.port === 'number' ? `:${e.port}` : ''}`\n : typeof e.hostname === 'string'\n ? e.hostname\n : 'the service'\n\n/** The framework's own analyzers, tried after the failing adapter's. */\nexport function builtInAdvice(err: unknown, where: string): FailureAdvice | undefined {\n const refused = findCode(err, ['ECONNREFUSED'])\n if (refused) {\n return {\n summary: `${where} could not connect to ${target(refused)}: connection refused`,\n cause:\n 'Nothing is listening at that address — the service is down, not started yet, or the URL points at the wrong host or port.',\n fix: 'Start the service, or check the connection URL in your env (localhost inside a container is the container itself).',\n }\n }\n const dns = findCode(err, ['ENOTFOUND', 'EAI_AGAIN'])\n if (dns) {\n return {\n summary: `${where} could not resolve the host ${target(dns)}`,\n cause: 'The host name in the connection URL does not resolve from here.',\n fix: 'Check the host name in your env — a typo, or a name that only resolves inside another network (a compose service name used from the host).',\n }\n }\n const timeout = findCode(err, ['ETIMEDOUT', 'ECONNRESET'])\n if (timeout) {\n return {\n summary: `${where} lost the connection to ${target(timeout)} (${String(timeout.code)})`,\n cause:\n 'The address answered slowly or not at all — a firewall, a security group, or the wrong network.',\n fix: 'Check that this machine is allowed to reach the service, and that TLS and port settings match it.',\n }\n }\n if (findMessage(err, CREDENTIALS_REJECTED)) {\n return {\n summary: `${where} was refused: the credentials were not accepted`,\n // A fixed explanation, not the driver's message: those can carry the\n // connection URL, and this text goes to the log.\n cause: 'The server rejected the user name or password.',\n fix: 'Check the user and password in your connection URL or env, and that the user exists on this server.',\n }\n }\n return undefined\n}\n\n/** Render advice for the log. */\nexport function formatAdvice(advice: FailureAdvice): string {\n return [\n advice.summary,\n ...(advice.cause ? ['', ` Cause: ${advice.cause}`] : []),\n '',\n ` Fix: ${advice.fix}`,\n ].join('\\n')\n}\n","/**\n * Startup checks: rules run against the assembled app before it serves a\n * request, so a risky configuration is reported at boot — with an ID you can\n * look up, and silence on purpose — instead of discovered in an incident.\n *\n * @module @forinda/kickjs/http/startup-checks\n */\nimport { createLogger } from '../core/logger'\nimport { isProduction } from '../core/is-production'\n\nconst log = createLogger('Checks')\n\n/** One finding. `error` fails startup; `warning` is logged. */\nexport interface CheckMessage {\n /** Stable ID, e.g. `'KICK-SEC-W001'` — what `silenceChecks` matches. */\n id: string\n level: 'error' | 'warning'\n message: string\n /** What to change. */\n fix?: string\n}\n\n/** What a check can look at. */\nexport interface CheckContext {\n /** The options the app was created with. */\n options: Readonly<Record<string, unknown>>\n /** Every mounted route, `{ method, path }`. */\n routes: ReadonlyArray<{ method: string; path: string }>\n production: boolean\n}\n\nexport interface StartupCheck {\n /** Names the check in logs; its messages carry their own IDs. */\n name: string\n /** Run only in production (`NODE_ENV` unset or not development/test) — deployment advice. */\n deploy?: boolean\n run(ctx: CheckContext): CheckMessage | CheckMessage[] | undefined | void\n}\n\n/** Declare a check — an identity helper, for the types. */\nexport function defineCheck(check: StartupCheck): StartupCheck {\n return check\n}\n\n/** Thrown when a check reports an error; lists every error found. */\nexport class StartupCheckError extends Error {\n constructor(readonly messages: CheckMessage[]) {\n super(\n `Startup checks failed:\\n${messages.map((m) => ` ${m.id}: ${m.message}${m.fix ? `\\n fix: ${m.fix}` : ''}`).join('\\n')}`,\n )\n this.name = 'StartupCheckError'\n }\n}\n\n/** The framework's own checks. */\nexport const builtInChecks: StartupCheck[] = [\n defineCheck({\n name: 'allowed hosts',\n deploy: true,\n run: ({ options }) => {\n const configured = (options.security as { allowedHosts?: unknown } | undefined)?.allowedHosts\n const hosts = Array.isArray(configured)\n ? configured\n : (configured as { hosts?: unknown } | undefined)?.hosts\n // `'*'` matches every host: configured, but no restriction.\n if (Array.isArray(hosts) && hosts.length > 0 && !hosts.includes('*')) return\n return {\n id: 'KICK-SEC-W001',\n level: 'warning',\n message:\n 'No allowed hosts in production (or `*`): any Host header is accepted, and absolute ' +\n 'URLs built from it (reset links, redirects) can point anywhere.',\n fix: \"bootstrap({ security: { allowedHosts: ['example.com'] } })\",\n }\n },\n }),\n defineCheck({\n name: 'trust proxy',\n deploy: true,\n run: ({ options }) => {\n if (options.trustProxy !== true) return\n return {\n id: 'KICK-SEC-W002',\n level: 'warning',\n message:\n '`trustProxy: true` trusts every X-Forwarded-For hop, so a client that reaches the app ' +\n 'directly can set its own IP (rate limits, logs, ctx.ip).',\n fix: 'Trust the number of proxies in front of the app instead, e.g. `trustProxy: 1`.',\n }\n },\n }),\n]\n\n/**\n * Run the checks, skipping silenced IDs. Warnings are logged; errors throw a\n * {@link StartupCheckError} once every check has run.\n */\nexport function runStartupChecks(\n checks: readonly StartupCheck[],\n ctx: Omit<CheckContext, 'production'>,\n silenced: readonly string[] = [],\n): CheckMessage[] {\n const production = isProduction()\n const skip = new Set(silenced)\n const found: CheckMessage[] = []\n for (const check of checks) {\n if (check.deploy && !production) continue\n let result: ReturnType<StartupCheck['run']>\n try {\n result = check.run({ ...ctx, production })\n } catch (err) {\n // A broken check must not stop the app; say so and move on.\n log.error(err, `Startup check '${check.name}' threw`)\n continue\n }\n for (const message of [result ?? []].flat()) {\n if (!skip.has(message.id)) found.push(message)\n }\n }\n\n for (const message of found) {\n if (message.level === 'warning') {\n log.warn(`${message.id}: ${message.message}${message.fix ? ` Fix: ${message.fix}` : ''}`)\n }\n }\n const errors = found.filter((m) => m.level === 'error')\n if (errors.length > 0) throw new StartupCheckError(errors)\n return found\n}\n","/**\n * The built-in health endpoints, as a module you can see.\n *\n * These used to be mounted straight onto the engine with `http.route()` before\n * the middleware chain. That worked, but it made them invisible in two ways\n * that matter:\n *\n * 1. **Swagger never saw them.** The OpenAPI spec is built by scanning\n * controller decorators, and a raw `http.route()` carries none — so the two\n * routes the framework itself serves were missing from every generated spec.\n * 2. **Nothing in an adopter's code said they existed.** `kick g adapter`\n * documents `onHealthCheck`, but the endpoint consuming it appeared nowhere,\n * so people wrote their own `/health/ready` beside the built-in one.\n *\n * As a module it is registered like any other, appears in the boot module list,\n * shows up in the spec, and can be replaced — pass your own module and set\n * `health: false`.\n *\n * Mounting it with the other modules also puts it INSIDE the middleware chain,\n * where it was previously ahead of it. That is deliberate: an app controls its\n * own auth, and a framework route quietly bypassing it is the surprise, not the\n * other way round. An app that wants its probes unauthenticated exempts them —\n * `health: { flags: ['auth.public'] }` puts the app's own flag on both routes,\n * and whatever already skips on that flag skips these too.\n *\n * @module @forinda/kickjs/http/health-module\n */\nimport { Controller, Get } from '../core/decorators'\nimport { createToken } from '../core/token'\nimport { defineModule } from '../core/define-module'\nimport type { Container } from '../core/container'\nimport type { RouteFlagDeclarations } from '../core/route-flag'\nimport { reply } from './reply'\n\n/** One adapter's answer to `onHealthCheck()`. */\nexport interface HealthCheckResult {\n name: string\n status: 'up' | 'down'\n /** Why a check counts as down when it didn't answer for itself. */\n reason?: 'timeout' | 'error'\n}\n\n/**\n * What the health routes need from the running Application.\n *\n * A controller cannot reach `Application` internals, and should not: this is\n * the whole surface the endpoints depend on, so a replacement module can\n * satisfy it without knowing anything else.\n */\nexport interface HealthProbe {\n /** True once shutdown has begun and traffic should drain away. */\n isDraining(): boolean\n /** True while the app is still starting — before it serves. */\n isStarting?(): boolean\n /** Aggregated `onHealthCheck()` results from every adapter that has one. */\n checks(): Promise<HealthCheckResult[]>\n}\n\nexport const HEALTH_PROBE = createToken<HealthProbe>('kick/Health/probe')\n\n/** Config for {@link healthModule}. */\nexport interface HealthModuleConfig {\n /**\n * Route flags to put on `GET /health/live` and `GET /health/ready`.\n *\n * The framework names no flags, so it cannot decide these probes are\n * \"public\" on your behalf — the name is yours, and every consumer that\n * already reads it (an auth contributor's `skipWhen`, a guard's\n * `exemptWhen`, `SwaggerAdapter({ publicFlag })`) then covers health with no\n * further wiring:\n *\n * ```ts\n * bootstrap({ health: { flags: ['auth.public'] } })\n * ```\n *\n * This replaces exempting `/health/live` and `/health/ready` by pathname,\n * which silently stops matching if the probe paths ever move.\n */\n flags?: RouteFlagDeclarations\n /**\n * Milliseconds each `onHealthCheck()` gets before it counts as down\n * (`reason: 'timeout'`). Default 2000. Keeps one hung dependency from\n * hanging the probe itself, which the orchestrator would then time out.\n */\n checkTimeout?: number\n}\n\n/** A check slower than this share of its timeout is logged as slow. */\nconst SLOW_SHARE = 0.5\n/** Probes from several kubelets or balancers within this window share one run. */\nconst CACHE_MS = 1000\n\n/**\n * The adapters' `onHealthCheck()`s, run with a timeout each, shared by calls\n * within a second of one another, and logged when slow.\n */\nexport function createHealthChecks(\n sources: () => ReadonlyArray<{ name?: string; onHealthCheck?: () => Promise<HealthCheckResult> }>,\n options: { timeoutMs?: number; onSlow?: (name: string, ms: number) => void } = {},\n): () => Promise<HealthCheckResult[]> {\n const timeoutMs = options.timeoutMs ?? 2000\n let cached: { at: number; result: Promise<HealthCheckResult[]> } | undefined\n\n const runOne = async (source: {\n name?: string\n onHealthCheck?: () => Promise<HealthCheckResult>\n }): Promise<HealthCheckResult> => {\n const name = source.name ?? 'unknown'\n const started = Date.now()\n let timer: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<HealthCheckResult>((resolve) => {\n // Referenced on purpose: an unref'd timer lets a process with nothing\n // else pending exit before a hung check is reported. `finally` clears it.\n timer = setTimeout(() => resolve({ name, status: 'down', reason: 'timeout' }), timeoutMs)\n })\n try {\n return await Promise.race([\n // Through a then(): a check that throws synchronously is down too.\n Promise.resolve()\n .then(() => source.onHealthCheck!())\n .catch((): HealthCheckResult => ({\n name,\n status: 'down',\n reason: 'error',\n })),\n timedOut,\n ])\n } finally {\n clearTimeout(timer)\n const ms = Date.now() - started\n if (ms >= timeoutMs * SLOW_SHARE) options.onSlow?.(name, ms)\n }\n }\n\n return () => {\n const now = Date.now()\n if (cached && now - cached.at < CACHE_MS) return cached.result\n const result = Promise.all(\n sources()\n .filter((s) => s.onHealthCheck)\n .map(runOne),\n )\n cached = { at: now, result }\n return result\n }\n}\n\n@Controller()\nexport class HealthController {\n constructor(private readonly probe: HealthProbe) {}\n\n /**\n * Liveness: is the process up. Stays 200 while draining — an orchestrator\n * restarts a container whose liveness fails, which would kill a graceful\n * shutdown partway through. Readiness is what turns traffic away.\n */\n @Get('/live')\n live() {\n return reply(200, {\n status: this.probe.isDraining() ? 'draining' : 'ok',\n uptime: process.uptime(),\n })\n }\n\n /** Readiness: is every adapter's dependency answering. */\n @Get('/ready')\n async ready() {\n if (this.probe.isDraining()) {\n return reply(503, { status: 'draining', checks: [] })\n }\n // A management port answers before the app has finished starting.\n if (this.probe.isStarting?.()) {\n return reply(503, { status: 'starting', checks: [] })\n }\n const checks = await this.probe.checks()\n const healthy = checks.every((c) => c.status === 'up')\n return reply(healthy ? 200 : 503, {\n status: healthy ? 'ready' : 'degraded',\n checks,\n })\n }\n}\n\n/**\n * `GET /health/live` and `GET /health/ready`, mounted at the root.\n *\n * A `defineModule` factory like any other module — the framework's own routes\n * should be declared the way it asks adopters to declare theirs, not through a\n * shape only the framework can produce.\n *\n * Registered automatically unless the app passes `health: false` or supplies a\n * module of its own. Pass `health: { flags: [...] }` to `bootstrap()` to flag\n * both probes — see {@link HealthModuleConfig}.\n */\nexport const healthModule = defineModule<HealthModuleConfig>({\n name: 'HealthModule',\n build: (config) => ({\n register(container: Container) {\n // Resolve through the token so a replacement probe — or a test double —\n // can be bound before this runs.\n container.registerFactory(HealthController, () => {\n const probe = container.resolve<HealthProbe>(HEALTH_PROBE)\n return new HealthController(probe)\n })\n },\n routes() {\n // Root-mounted and unversioned: the probe URL an orchestrator is\n // configured against must not move when the API prefix or version does.\n return {\n path: '/health',\n controller: HealthController,\n version: false,\n prefix: false,\n // Declared at the mount rather than on HealthController: the class is\n // the framework's, the flag names are the app's.\n flags: config.flags,\n }\n },\n }),\n})\n","/**\n * Serve web `Request`s through a Node request handler by forwarding them to a\n * server bound to `127.0.0.1` inside the same process. Used by\n * `Application.fetch()` for runtimes without a native fetch (Express and\n * Fastify): their handlers need real Node request/response objects, and Express\n * swaps the `res` prototype, which makes a direct Request→`res` bridge\n * unreliable.\n *\n * @module @forinda/kickjs/http/loopback\n */\nimport { randomBytes } from 'node:crypto'\nimport http, { type IncomingMessage, type ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\n\n/**\n * Request headers that describe one hop, not the request. Forwarding them\n * makes Node's `fetch` reject the request (\"fetch failed\") or misframe it —\n * `content-length` is recomputed from the buffered body.\n */\nconst HOP_BY_HOP_REQUEST = [\n 'connection',\n 'keep-alive',\n 'proxy-connection',\n 'transfer-encoding',\n 'upgrade',\n 'te',\n 'trailer',\n 'host',\n 'content-length',\n]\n\nconst HOP_BY_HOP_RESPONSE = [\n 'connection',\n 'keep-alive',\n 'proxy-connection',\n 'transfer-encoding',\n 'upgrade',\n 'trailer',\n 'content-encoding',\n 'content-length',\n]\n\n/** Carry the Request's host across the loopback hop; never seen by the app. */\nconst LOOPBACK_HOST = 'x-kick-loopback-host'\nconst LOOPBACK_SECRET = 'x-kick-loopback-secret'\n\nexport interface Loopback {\n /** Forward a Request to the handler; starts the server on first use. */\n fetch(request: Request): Promise<Response>\n /** Stop the server, if it started. */\n close(): Promise<void>\n}\n\n/**\n * The request body as a stream, without buffering it — so the app's body\n * parsers enforce their size limits as it arrives. A body that turns out to be\n * empty becomes `undefined`: Node's fetch rejects an empty stream on POST.\n */\nasync function streamedBody(request: Request): Promise<ReadableStream<Uint8Array> | undefined> {\n if (!request.body || request.method === 'GET' || request.method === 'HEAD') return undefined\n const reader = request.body.getReader()\n const first = await reader.read()\n if (first.done) return undefined\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(first.value)\n },\n async pull(controller) {\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n}\n\nexport function createLoopback(\n handle: (req: IncomingMessage, res: ServerResponse) => void,\n): Loopback {\n let started: Promise<{ origin: string; server: http.Server }> | undefined\n // Proves a request came through this loopback, not from another process\n // that found the port: only then is the host it carries believed.\n const secret = randomBytes(24).toString('hex')\n\n const server = () => {\n started ??= new Promise<{ origin: string; server: http.Server }>((resolve, reject) => {\n const instance = http.createServer((req, res) => {\n // Node's fetch won't send a Host header, so the original host travels\n // in LOOPBACK_HOST and is put back here: the app sees the Host the\n // Request was addressed to, as it would from a real client.\n const host = req.headers[LOOPBACK_HOST]\n if (req.headers[LOOPBACK_SECRET] === secret && typeof host === 'string')\n req.headers.host = host\n delete req.headers[LOOPBACK_HOST]\n delete req.headers[LOOPBACK_SECRET]\n handle(req, res)\n })\n instance.once('error', reject)\n instance.listen(0, '127.0.0.1', () => {\n // Never keep a process alive on its own account.\n instance.unref()\n resolve({\n origin: `http://127.0.0.1:${(instance.address() as AddressInfo).port}`,\n server: instance,\n })\n })\n }).catch((err) => {\n started = undefined\n throw err\n })\n return started\n }\n\n return {\n async fetch(request) {\n const { origin } = await server()\n const url = new URL(request.url)\n\n const headers = new Headers(request.headers)\n for (const name of HOP_BY_HOP_REQUEST) headers.delete(name)\n // The forwarded request arrives from 127.0.0.1. Host and protocol come\n // from the Request's URL — never from caller-supplied forwarding\n // headers, which a trusting runtime would otherwise believe.\n headers.set('x-forwarded-host', url.host)\n headers.set('x-forwarded-proto', url.protocol.slice(0, -1))\n headers.set(LOOPBACK_HOST, url.host)\n headers.set(LOOPBACK_SECRET, secret)\n\n const body = await streamedBody(request)\n const upstream = await fetch(origin + url.pathname + url.search, {\n method: request.method,\n headers,\n body,\n // Required by Node's fetch for a streamed request body.\n ...(body ? { duplex: 'half' } : {}),\n redirect: 'manual',\n signal: request.signal,\n } as RequestInit)\n\n // Node's fetch has already decoded a compressed body, so the encoding and\n // length headers no longer describe what is being returned. Connection\n // headers describe the loopback hop.\n const responseHeaders = new Headers(upstream.headers)\n const named = responseHeaders.get('connection')?.split(',') ?? []\n for (const name of [...HOP_BY_HOP_RESPONSE, ...named]) responseHeaders.delete(name.trim())\n return new Response(upstream.body, {\n status: upstream.status,\n statusText: upstream.statusText,\n headers: responseHeaders,\n })\n },\n\n async close() {\n const running = await started?.catch(() => undefined)\n started = undefined\n if (!running) return\n const closed = new Promise<void>((resolve) => running.server.close(() => resolve()))\n // Application.shutdown has already drained in-flight requests; what is\n // left is keep-alive sockets from fetch's pool, which would hold\n // close() open past the shutdown timeout.\n running.server.closeAllConnections()\n await closed\n },\n }\n}\n","import http from 'node:http'\nimport { HttpException } from '../core/errors'\nimport { isProduction } from '../core/is-production'\nimport { moduleName } from '../core/define-module'\nimport { createToken } from '../core/token'\nimport { runCronJobs } from '../core/cron'\nimport { matchesBearer } from '../core/web-crypto'\nimport https from 'node:https'\nimport http2 from 'node:http2'\nimport tls from 'node:tls'\nimport type { ConnectHandler, ConnectMiddleware } from './connect'\nimport {\n Container,\n createLogger,\n Logger,\n joinPaths,\n buildMountPath,\n tokenName,\n METADATA,\n type AppModule,\n type AppModuleClass,\n type AppModuleEntry,\n type AppAdapter,\n type AdapterContext,\n type KickServer,\n type AdapterMiddleware,\n type ContributorRegistrations,\n type KickPlugin,\n type ModuleRegistry,\n type RouteDefinition,\n type SourcedRegistration,\n mountSort,\n DuplicateMountNameError,\n MutableModuleRegistry,\n} from '../core'\nimport {\n http2RequiresTlsError,\n http2UnsupportedRuntimeError,\n moduleRouteMissingControllerError,\n tlsCredentialsError,\n} from '../core/kick-errors'\nimport { RoutePolicyTable, offerRoutePolicy } from '../core/route-policy'\nimport {\n disposeAll,\n drainDisposables,\n registerDisposable,\n runDisposables,\n} from '../core/disposables'\nimport { getClassMeta } from '../core/metadata'\nimport { computed, ref, type ComputedRef } from '../core/reactivity'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './body-policy'\nimport { requestId } from './middleware/request-id'\nimport { pendingBackgroundWork, settleBackgroundWork } from './background'\nimport { installChannelPublisher, traceHandler } from './tracing'\nimport {\n hasResponseObservers,\n releaseObservers,\n reportError,\n reportResponse,\n setObservers,\n type Observer,\n} from '../core/observers'\nimport { ROUTE_SLOT } from '../core/route-flag'\nimport type { MatchedRoute, RouteContributor } from './runtime'\nimport { notFoundHandler, errorHandler, type MountedRoute } from './middleware/error-handler'\nimport type { ValidationErrorFactory } from './middleware/validate'\nimport { allowedHosts, type AllowedHostsOptions } from './middleware/allowed-hosts'\nimport { requestScopeMiddleware, isRequestScopeMiddleware } from './middleware/request-scope'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './router-builder'\nimport { StartupTimeline, type StartupTimelineSnapshot } from './startup-timeline'\nimport { ROUTE_URLS, RouteUrls, type RouteName, type UrlForArgs } from './url-for'\nimport {\n loadSettings,\n originsOf,\n type ConfigVar,\n type Settings,\n type SettingsDeclaration,\n type VarOrigin,\n} from '../config/settings'\nimport { describeEnvSchema } from '../config/env'\nimport { evaluateCondition, type ConditionOutcome } from '../core/adapter-conditions'\nimport { builtInAdvice, formatAdvice, type FailureAdvice } from '../core/failure-analysis'\nimport { builtInChecks, runStartupChecks, type StartupCheck } from './startup-checks'\nimport {\n HEALTH_PROBE,\n HealthController,\n createHealthChecks,\n healthModule,\n type HealthModuleConfig,\n} from './health-module'\nimport { expressBodyParsers, expressRuntime, settleExpressLoad } from './runtimes/express-lazy'\nimport { createLoopback, type Loopback } from './loopback'\nimport type {\n ActiveRuntime,\n AdapterHttp,\n HttpRuntime,\n RouteEntry,\n RuntimeCapabilities,\n RuntimeResponse,\n} from './runtime'\nimport { requestStore } from './request-store'\n\n/** Startup slower than this logs its slowest steps. */\nconst SLOW_STARTUP_MS = 1000\nconst log = createLogger('Application')\n\n/**\n * A middleware entry in the declarative pipeline.\n * Can be a bare handler or an object with path scoping.\n */\nexport type MiddlewareEntry = ConnectHandler | { path: string; handler: ConnectHandler }\n\n/** Options for {@link Application.shutdown}. */\nexport interface ShutdownOptions {\n /**\n * Close the HTTP server and drain in-flight requests. Default `true`.\n *\n * Set `false` for a dev HMR rebuild, where the server is shared across\n * reloads — adapters, plugins, and disposables are still torn down, which is\n * the part a reload needs.\n */\n closeServer?: boolean\n}\n\n/**\n * Throw KICK009 unless `options` can identify the server. Node creates an\n * HTTPS / HTTP/2 server without a certificate and then fails every handshake,\n * so the check has to happen here, at boot.\n */\nfunction assertUsableTls(options: tls.SecureContextOptions & tls.TlsOptions): void {\n const { key, cert, pfx, SNICallback, pskCallback } = options\n if (!pfx && !SNICallback && !pskCallback) {\n if (!key && !cert) throw tlsCredentialsError('no key/cert, pfx, SNICallback, or pskCallback')\n if (!key) throw tlsCredentialsError('cert is set but key is missing')\n if (!cert) throw tlsCredentialsError('key is set but cert is missing')\n }\n // Build the context once: surfaces unreadable PEMs, a wrong passphrase, and\n // a key that does not match its certificate before any adapter runs.\n try {\n tls.createSecureContext(options)\n } catch (err) {\n throw tlsCredentialsError((err as Error).message)\n }\n}\n\n/** See {@link ApplicationOptions.server}. */\nexport interface ServerOptions {\n /** TLS credentials and options (`key`, `cert`, `ca`, `pfx`, `passphrase`, …). */\n tls?: tls.SecureContextOptions & tls.TlsOptions\n /**\n * `true`: HTTP/2 with HTTP/1.1 fallback; requires `tls`. `'h2c'`: cleartext\n * HTTP/2 only, no `tls` and no HTTP/1.1 — for a proxy or mesh that speaks\n * HTTP/2 to the app. Both need an HTTP/2-capable runtime.\n */\n http2?: boolean | 'h2c'\n /**\n * Milliseconds an idle keep-alive connection stays open. Default 65000.\n * Keep it ABOVE your load balancer's idle timeout (AWS ALB: 60s): when the\n * server closes a connection the balancer is about to reuse, that request\n * fails with a 502. Node's own default is 5s.\n */\n keepAliveTimeout?: number\n /** Milliseconds to receive the request headers. Default `keepAliveTimeout + 1000`. */\n headersTimeout?: number\n /** Milliseconds to receive the whole request. Default 300000; 0 disables. */\n requestTimeout?: number\n}\n\n/** A mounted controller route, as `app.getRoutes()` lists it. */\nexport interface MountedRouteInfo {\n method: string\n /** Full pattern, prefix and version included: `/api/v1/users/:id`. Static files: `/assets/*`. */\n pattern: string\n /** The controller — or, for a route an adapter added, the adapter's name. */\n controller: string\n handler: string\n /** Context contributors in execution order, with where each was registered. */\n contributors: readonly RouteContributor[]\n /** A module's controller, or an adapter through `ctx.http` / `ctx.management.http`. */\n source: 'module' | 'adapter'\n /** Which listener serves it: the app's port, or the management port. */\n port: 'app' | 'management'\n}\n\n/** What `app.describeConfig()` returns. */\nexport interface ConfigDescription {\n /** The app's env schema (`loadEnv` / `loadEnvFromSchema`), or the base schema. */\n env: ConfigVar[]\n /** Declared settings sections, in declaration order, each once. */\n sections: Array<{ prefix: string; declaredBy: string; vars: ConfigVar[] }>\n}\n\n/** What `app.configOrigins()` returns. */\nexport interface ConfigOrigins {\n /** The app's env schema. */\n env: VarOrigin[]\n /** The settings sections the app bound, in binding order. */\n sections: Array<{ prefix: string; vars: VarOrigin[] }>\n}\n\nexport interface ApplicationOptions {\n /**\n * Feature modules to load. Accepts both class form\n * (`SomeModule extends AppModule`, instantiated via `new`) and\n * instance form (output of {@link defineModule}'s factory call,\n * e.g. `TasksModule({ scope: 'admin' })`) — the loader discriminates\n * and either `new`-s the class or uses the instance directly.\n *\n * Static path — for conditional / dynamic registration, use the\n * {@link ApplicationOptions.setup} callback instead.\n */\n modules: AppModuleEntry[]\n\n /**\n * Imperative module registration callback. Receives a\n * {@link ModuleRegistry} you call `.mount(module)` on to register\n * modules conditionally — based on env flags, runtime config, a\n * tenant list, etc. Runs after every plugin's `setup()` hook and\n * after the static `modules: [...]` array is collected.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()],\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * },\n * })\n * ```\n */\n setup?(registry: ModuleRegistry): void\n /** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */\n adapters?: AppAdapter[]\n /** Server port (falls back to PORT env var, then 3000) */\n port?: number\n /**\n * The Node server `start()` creates in production. Omit for plain HTTP.\n *\n * - `{ tls }` — HTTPS on every runtime.\n * - `{ tls, http2: true }` — HTTP/2 (ALPN `h2`) with HTTP/1.1 fallback, so\n * HTTP/1.1 clients and WebSocket upgrades keep working. Fastify and h3\n * only; Express fails at boot with KICK007, and `http2` without `tls`\n * with KICK008.\n * - `{ http2: 'h2c' }` — cleartext HTTP/2 with no HTTP/1.1 fallback, for a\n * proxy or service mesh that speaks HTTP/2 to the app (native gRPC behind\n * Envoy or Linkerd). Fastify and h3 only.\n *\n * Ignored in dev mode, where Vite owns the server. Most deploys terminate\n * TLS / HTTP/2 at a proxy and need none of this.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * runtime: fastifyRuntime(),\n * server: {\n * tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },\n * http2: true,\n * },\n * })\n * ```\n */\n server?: ServerOptions\n /**\n * Serve operational endpoints on a second port — the same app and container,\n * a second listener, like Spring Boot's `management.server.port`. `/health/live`\n * and `/health/ready` move there, off the public port, along with whatever\n * adapters register on `AdapterContext.management` (DevTools with\n * `DevToolsAdapter({ management: true })`). The management port skips the\n * app's middleware, and keeps answering while the public port drains.\n *\n * Off by default. Ignored in dev mode (Vite owns the only server) and in\n * handler mode (serverless), where everything stays on the one entry.\n *\n * ```ts\n * bootstrap({ modules, management: { port: 9090 } })\n * ```\n */\n management?: ManagementOptions\n /** Global API prefix (default: '/api'). Pass `''` to mount at the root. */\n apiPrefix?: string\n /**\n * Default API version (default: 1) — routes become /{prefix}/v{version}/{path}.\n *\n * `false` opts out of URL versioning: routes mount at /{prefix}/{path}.\n * A module can still version itself by setting `version` on its\n * `ModuleRoutes` — the per-mount value always wins over this default, in\n * either direction.\n */\n defaultVersion?: number | false\n\n /**\n * Global middleware pipeline. Declared in order.\n * Replaces the hardcoded middleware stack — you control exactly what runs.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * middlewares: [\n * helmet(),\n * cors(),\n * compression(),\n * morgan('dev'),\n * express.json({ limit: '1mb' }),\n * ],\n * })\n * ```\n *\n * If omitted, a sensible default is applied:\n * requestId(), and a JSON body parser limited to `jsonLimit` (default '1mb')\n */\n middlewares?: MiddlewareEntry[]\n\n /** Plugins that bundle modules, adapters, middleware, and DI bindings */\n plugins?: KickPlugin[]\n\n /**\n * Global Context Contributors (#107) that apply to every route in the\n * application. Merge into the per-route pipeline at the `'global'`\n * precedence level — they lose to module, adapter, class, and method\n * contributors with the same key, providing app-wide defaults that any\n * narrower scope can override.\n *\n * @example\n * ```ts\n * const StartedAt = defineContextDecorator({\n * key: 'requestStartedAt',\n * resolve: () => Date.now(),\n * })\n *\n * bootstrap({\n * modules,\n * contributors: [StartedAt.registration],\n * })\n * ```\n */\n contributors?: ContributorRegistrations\n\n /**\n * Backing store strategy for {@link RequestContext} `set/get` and the\n * Context Contributor pipeline (#107).\n *\n * - `'auto'` (default) — Application mounts {@link requestScopeMiddleware}\n * automatically before any user middleware. If the user-supplied\n * `middleware` list already includes `requestScopeMiddleware()`,\n * detection skips the auto-mount so adopters can control its position.\n * - `'manual'` — Application never mounts the wrapper. The Context\n * Contributor pipeline still runs on every route — the runner is\n * inserted by `router-builder` regardless of ALS state. What\n * degrades without an ALS frame is the *backing store*:\n * REQUEST-scoped DI throws (no `requestStore.getStore()` to read\n * from) and `RequestContext.set/get` throws. Use `'manual'` only when you\n * genuinely intend to wrap requests in your own ALS frame (rare —\n * multi-tenant adapters used to do this; post-Phase 3 they share\n * the framework's frame instead).\n */\n contextStore?: 'auto' | 'manual'\n\n /**\n * Controls whether KickJS registers process-level handlers at bootstrap.\n *\n * - `'auto'` (default) — register `uncaughtException` /\n * `unhandledRejection` loggers AND `SIGINT` / `SIGTERM` →\n * `app.shutdown()` → `process.exit(0)`.\n * - `'errors-only'` — register the error loggers; skip the signal\n * handlers. Use this when you have your own shutdown choreographer\n * (OpenTelemetry SDK, Sentry, custom orchestrator) that calls\n * `app.shutdown()` itself and you don't want two listeners racing\n * to call `process.exit`.\n * - `'manual'` — skip everything. Adopter is responsible for both\n * error logging and signal-driven shutdown.\n *\n * Background: many observability SDKs install their own SIGTERM\n * handler to flush spans/metrics before the process exits. Two\n * separate handlers calling `process.exit(0)` race each other and\n * can truncate the in-flight flush. Setting this to `'errors-only'`\n * or `'manual'` lets the SDK own the lifecycle while still letting\n * KickJS surface uncaught exceptions / rejections via the logger.\n *\n * The dev mode auto-detect (`__kickjs_httpServer` set by the Vite\n * plugin) suppresses signal registration regardless of this option,\n * since Vite owns the lifecycle in development.\n */\n processHooks?: 'auto' | 'errors-only' | 'manual'\n\n /**\n * The HTTP engine driver. Defaults to {@link expressRuntime} — Express stays\n * the zero-config default, so existing apps are unaffected.\n *\n * Any `HttpRuntime` is accepted — pass `fastifyRuntime()` (from\n * `@forinda/kickjs/fastify`) or a custom engine driver. Defaults to\n * {@link expressRuntime}. The engine-native escape hatches\n * (`getRuntimeApp()`, `AdapterContext.app`) follow the active runtime via the\n * registry (`ActiveRuntime`, spec §4.3b) — Express by default, or the augmented\n * engine once the `kick/runtime` typegen output is present.\n */\n /**\n * Mount the built-in `GET /health/live` and `GET /health/ready`.\n *\n * On by default. Set `false` to take them over completely — supply your own\n * module at `/health` and nothing collides. The built-in is registered last,\n * so an app module claiming the same path already wins without this.\n *\n * They mount as an ordinary module, which means they sit inside the\n * middleware chain: whatever guards the rest of the app guards these too.\n * Pass `{ flags: [...] }` to put your own route flags on both probes — the\n * way to make them reachable unauthenticated without exempting a pathname\n * that can move:\n *\n * ```ts\n * bootstrap({ health: { flags: ['auth.public'] } })\n * ```\n */\n health?: boolean | HealthModuleConfig\n\n runtime?: HttpRuntime\n\n /**\n * Requests no route matched, when the app runs inside another handler —\n * `kick dev`'s Vite server, or `app.handle(req, res, next)` in a host server.\n *\n * - `true` (default): Fastify and h3 hand them back to that handler.\n * - `false`: they are answered here — `onNotFound`, or the built-in 404 /\n * 405 — the same as in production. Express always answers.\n *\n * Set `false` when the app owns its URLs, e.g. pages with an error page,\n * so dev answers unknown URLs the way production does.\n */\n notFoundFallthrough?: boolean\n\n /** Express `trust proxy` setting */\n trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean)\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`).\n * Express applies it to its default parsers, so only when `middlewares` is\n * not provided; Fastify, h3 and the web entry parse bodies themselves and\n * always apply it. A larger body answers 413.\n */\n jsonLimit?: string | number\n /**\n * Print the route table on startup. Default: `false`. Set to `true`\n * to log a per-controller summary (method counts + mount paths) once\n * the app has mounted. Emitted at `info` level, so it is still subject\n * to `LOG_LEVEL` filtering (visible at the default `info`; hidden at\n * `warn`/`error`/`silent`).\n */\n logRouteTable?: boolean\n /**\n * @deprecated Use {@link ApplicationOptions.logRouteTable}. Kept as an\n * alias for back-compat; `logRouteTable` wins when both are set.\n */\n logRoutesTable?: boolean\n /**\n * Maximum time (ms) to wait for graceful shutdown before forcing exit.\n * Default: 30000 (30 seconds). Set to 0 to disable forced exit.\n */\n shutdownTimeout?: number\n\n /**\n * Milliseconds to keep serving after shutdown begins, with `/health/ready`\n * already answering 503, before the server stops accepting connections.\n * Load balancers and Kubernetes endpoints take a few seconds to notice an\n * unready instance; closing at once refuses the requests still routed here.\n * Default 0. Not counted against `shutdownTimeout`.\n */\n preStopDelay?: number\n\n /**\n * Enable cluster mode for multi-core utilization.\n *\n * When enabled, the primary process forks worker processes that share the\n * same port via Node's built-in `cluster` module (OS load balancing).\n *\n * - `true` — use all available CPU cores\n * - `{ workers: N }` — use exactly N workers\n *\n * Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is\n * forwarded to all workers.\n *\n * @example\n * ```ts\n * bootstrap({ modules, cluster: true })\n * bootstrap({ modules, cluster: { workers: 4 } })\n * ```\n */\n cluster?: boolean | { workers?: number }\n\n /**\n * Custom 404 handler for unmatched routes. When omitted, the built-in\n * handler returns `{ message: 'Not Found' }` with status 404.\n *\n * Connect-**shaped**, not Express-**semantic** — see {@link onError} for the\n * per-runtime table. The same two caveats apply: `next()` is inert on\n * Fastify and h3, and Express-only request members (`req.originalUrl`,\n * `req.path`, `req.ip`) are `undefined` there, so read `req.url`.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onNotFound: (req, res) => {\n * // `req.originalUrl` is Express-only — use `req.url` for portability.\n * res.status(404).json({ error: 'Route not found', path: req.url })\n * },\n * })\n * ```\n *\n * Calling `next()` hands the request to the built-in handler — the usual\n * 404, or the 405 with `Allow` when the path exists under another method —\n * so a custom handler can answer some requests and leave the rest.\n */\n onNotFound?: (req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void\n\n /**\n * Custom global error handler, receiving `(err, req, res, next)`. When\n * omitted, the built-in handler formats ZodError, HttpException, and\n * unexpected errors.\n *\n * The shape is connect-style, but it is NOT \"the standard Express error\n * handler\" on every engine — what you actually receive differs, and the\n * differences bite:\n *\n * | | `req` | `res` | `next` |\n * | --- | --- | --- | --- |\n * | Express | native `Request` | native `Response` | real `next` |\n * | Fastify | `request.raw` | reply driver | **no-op** |\n * | h3 | `event.node.req` | response driver | no-op (or dev fall-through) |\n *\n * Two consequences worth knowing before you write one:\n *\n * - **`next(err)` does nothing on Fastify and h3.** It is a no-op function\n * there, so delegating to the default handler silently drops the error.\n * Send a response yourself rather than passing it on.\n * - **Express-only request members are `undefined` elsewhere.**\n * `req.originalUrl`, `req.path`, and `req.ip` do not exist on the raw node\n * request — use `req.url` and the `x-forwarded-*` headers, or reach for\n * `ctx.ip` in a contributor / guard where a `RequestContext` is available.\n *\n * `res` is typed {@link RuntimeResponse} because that is what every engine\n * genuinely provides: `status`, `json`, `send`, `setHeader`, `render`,\n * `writeHead`, `end`. Express's own `Response` satisfies it.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onError: (err, req, res) => {\n * logger.error(err, `${req.method} ${req.url}`) // not `originalUrl`\n * res.status(err.status ?? 500).json({ error: err.message })\n * },\n * })\n * ```\n */\n onError?: (err: any, req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void\n\n /**\n * Decide what a failed route validation (`@Validate` / `validate()`) throws.\n * Receives `{ source, issues, req }` and returns the error — by default a 422\n * `HttpException` with `[{ field, message }]` details. Return `undefined` to\n * fall back to the default for that failure.\n *\n * ```ts\n * bootstrap({\n * validationError: ({ source, issues }) =>\n * new ProblemException({\n * status: 400,\n * title: `Invalid ${source}`,\n * errors: issues.map((i) => ({ path: i.path.join('.'), message: i.message })),\n * }),\n * })\n * ```\n *\n * Applies to this app's routes only.\n */\n validationError?: ValidationErrorFactory\n\n /**\n * Your own startup checks, run with the built-in ones once the app is\n * assembled and before it serves a request. A check returning an `error`\n * fails startup; a `warning` is logged.\n *\n * ```ts\n * const needsDb = defineCheck({\n * name: 'database url',\n * deploy: true, // production only\n * run: () =>\n * process.env.DATABASE_URL?.includes('localhost')\n * ? { id: 'APP-W001', level: 'warning', message: 'DATABASE_URL points at localhost' }\n * : undefined,\n * })\n * bootstrap({ modules, checks: [needsDb] })\n * ```\n */\n checks?: StartupCheck[]\n\n /** Check IDs to skip, e.g. `['KICK-SEC-W002']` — a deliberate, reviewable exception. */\n silenceChecks?: string[]\n\n /**\n * App-wide settings sections ({@link defineSettings}): validated at startup\n * — a missing or invalid value fails it, naming the variables — and\n * injectable by their tokens. Modules, adapters and plugins declare their\n * own with `settings()`.\n */\n settings?: SettingsDeclaration[]\n\n /**\n * Security defaults applied automatically unless opted out.\n *\n * When not specified, secure defaults are applied:\n * - Helmet security headers are auto-injected\n * - JSON body limit defaults to 1MB\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * security: {\n * helmet: false, // disable auto-helmet\n * },\n * })\n * ```\n */\n security?: {\n /** Auto-inject helmet security headers. Default: true */\n helmet?: boolean\n /**\n * Answer only requests for these hosts — `allowedHosts()` mounted first.\n * `'.example.com'` matches the domain and its subdomains. The health\n * probes are exempt: orchestrators send them to the instance's IP.\n *\n * ```ts\n * bootstrap({ security: { allowedHosts: ['example.com', '.example.com'] } })\n * ```\n */\n allowedHosts?: string[] | AllowedHostsOptions\n }\n}\n\n/**\n * The main application class. Wires together Express, the DI container,\n * feature modules, adapters, and the middleware pipeline.\n */\n\n/**\n * A `defineModule()` factory, as opposed to a module class.\n *\n * Both are functions, so `typeof` cannot tell them apart. The factory carries a\n * frozen `definition` and a `scoped` helper, neither of which a class has.\n */\nfunction isModuleFactory(entry: unknown): entry is (() => AppModule) & {\n definition: { name?: string; defaults?: unknown }\n} {\n return (\n typeof entry === 'function' &&\n 'definition' in entry &&\n typeof (entry as { scoped?: unknown }).scoped === 'function'\n )\n}\n\n/**\n * Whether a factory takes configuration.\n *\n * `defaults` is the only runtime signal that a module has config at all — the\n * type parameter is erased. Its presence is what separates \"the bare name is\n * exactly equivalent\" from \"the bare name silently picked defaults for you\".\n */\nfunction isConfigurable(factory: { definition: { defaults?: unknown } }): boolean {\n const defaults = factory.definition?.defaults\n return defaults !== undefined && defaults !== null\n}\n\n/**\n * Resolve a module entry to an `AppModule`, whichever shape it arrives in.\n *\n * Three forms reach here: an instance (`defineModule(...)()` output), a legacy\n * module class, and — the case this exists for — a `defineModule()` factory\n * passed UNINVOKED. That last one used to hit `new factory()` and die with a\n * bare `TypeError: entry is not a constructor`, naming neither the module nor\n * the fix. It is easy to hit because the class form takes the bare name, so\n * the two styles look interchangeable and are not.\n *\n * For a module with NO config, calling the factory with no arguments produces\n * exactly what `Module()` would, so accepting the bare name is equivalent\n * rather than lenient.\n *\n * For a CONFIGURABLE module it is not equivalent in intent: the bare name\n * silently selects the defaults, and an author who meant `Module({ … })` would\n * get a running app wired the wrong way with nothing said. That is the failure\n * mode this whole change exists to remove, so those stay loud — with a message\n * that names the module and both correct spellings, rather than the bare\n * `entry is not a constructor` it used to produce.\n */\nfunction toAppModule(entry: AppModuleEntry): AppModule {\n if (typeof entry !== 'function') return entry as AppModule\n if (isModuleFactory(entry)) {\n if (isConfigurable(entry)) {\n const name = entry.definition?.name || entry.name || '<anonymous>'\n throw new TypeError(\n `bootstrap: module \\`${name}\\` takes configuration, so it must be invoked.\\n` +\n ` Write \\`${name}()\\` for its defaults, or \\`${name}({ … })\\` to configure it.\\n` +\n ` Passing it bare would have silently selected the defaults.`,\n )\n }\n return entry()\n }\n\n const name = (entry as { name?: string }).name || '<anonymous>'\n if (!isConstructible(entry)) {\n throw new TypeError(\n `bootstrap: module entry \\`${name}\\` is a function, but not a module class ` +\n `and not a defineModule() factory (no \\`definition\\`).\\n` +\n ` A defineModule() module is passed as \\`${name}\\` or \\`${name}()\\`; ` +\n `a class must implement AppModule.`,\n )\n }\n\n // Constructed OUTSIDE any catch. Wrapping this was masking real failures:\n // a legacy module whose constructor threw came back reported as \"not a\n // module class\", hiding the actual error and sending the reader to the\n // wrong place entirely.\n const mod = new (entry as AppModuleClass)() as AppModule\n\n // A plain `function Foo() {}` IS constructible and returns `{}`, so it\n // reaches here and would fail later inside the framework at `mod.routes()`\n // — a generic error, far from the entry that caused it. Check the shape\n // where the entry is still in hand.\n if (typeof mod?.routes !== 'function') {\n throw new TypeError(\n `bootstrap: module entry \\`${name}\\` constructed, but the result does not ` +\n `implement AppModule — \\`routes()\\` is missing.\\n` +\n ` A module class needs \\`routes()\\`; a defineModule() module is passed ` +\n `as \\`${name}\\` or \\`${name}()\\`.`,\n )\n }\n return mod\n}\n\n/**\n * Whether `new fn()` is legal, without calling it.\n *\n * Reflect.construct with a deliberately unrelated `newTarget` performs the\n * constructibility check and then throws before running any constructor body,\n * so this stays side-effect free — which matters, because the whole point is\n * to avoid invoking something that may not be a constructor at all.\n */\nfunction isConstructible(fn: unknown): boolean {\n try {\n Reflect.construct(String, [], fn as never)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * The running {@link Application} — for a service that needs the app itself,\n * e.g. to call `describeConfig()` or `urlFor()`. Bound when the app is\n * constructed and again on each `setup()` (an HMR rebuild resets the\n * container). One per process, like every DI binding.\n *\n * ```ts\n * constructor(@Inject(APPLICATION) private readonly app: Application) {}\n * ```\n */\nexport const APPLICATION = createToken<Application>('kick/Http/Application')\n\n/** {@link Application.status}. */\nexport type AppStatus = 'idle' | 'starting' | 'ready' | 'draining' | 'stopped'\n\n/** {@link ApplicationOptions.management}. */\nexport interface ManagementOptions {\n /** Port for the management listener. */\n port: number\n /**\n * Interface to bind. Default: every interface, like the public port — an\n * orchestrator probes the pod's address, so `127.0.0.1` would fail its\n * probes. Narrow it with a network policy, or bind an internal address.\n */\n host?: string\n /**\n * Serve the management port over HTTPS — same shape as `server.tls`. Off by\n * default: the port is meant for an internal network. Set it when anything\n * that crosses that network carries a credential (a DevTools token, an\n * admin route's bearer token).\n */\n tls?: tls.SecureContextOptions & tls.TlsOptions\n}\n\nexport class Application {\n private app: unknown\n /** The HTTP engine driver. Defaults to {@link expressRuntime}. */\n private readonly runtime: HttpRuntime\n private container: Container\n private httpServer: KickServer | null = null\n /**\n * `bootstrap({ management })`: its engine app, created by start() outside dev\n * mode — whatever `runtime` builds (Express, Fastify, h3), so not typed as one.\n */\n private managementApp: unknown = null\n private managementServer: http.Server | https.Server | null = null\n /** Set by start() when `management` applies; setup() then creates the management app. */\n private wantsManagement = false\n /** Set by startWithoutServer() — the serverless path, where cron runs over HTTP. */\n private handlerMode = false\n /** The observer set this app installed — released on shutdown only if still current. */\n private observers: readonly Observer[] = []\n /**\n * Open HTTP/2 sessions. `server.close()` stops new sessions, but on older\n * Node (22 and earlier) existing ones keep accepting new streams — so\n * shutdown closes them itself.\n */\n private readonly http2Sessions = new Set<http2.ServerHttp2Session>()\n /** Forwarding server behind {@link fetch} on Node-based runtimes. */\n private loopback?: Loopback\n private timeline = new StartupTimeline()\n private conditionReport: ConditionOutcome[] = []\n private mountedRoutes: MountedRoute[] = []\n private mountedRouteInfo: MountedRouteInfo[] = []\n private routeUrls = new RouteUrls()\n /** Settings prefixes bound in this setup, across its two binding phases. */\n private settingsPrefixes = new Map<string, Settings<unknown>>()\n private settingsProvided = new Map<Settings<unknown>, unknown>()\n private handlerFor?: { app: unknown; handler: ReturnType<HttpRuntime['nodeHandler']> }\n private readonly adapters: AppAdapter[]\n /**\n * Flags of every mounted route, for middleware that runs before routing and\n * therefore cannot read `ctx.route` (the connect-style rate limiter). Handed\n * to middleware that declares the slot — see `core/route-policy.ts`.\n */\n private readonly routePolicy = new RoutePolicyTable()\n\n private readonly plugins: KickPlugin[]\n\n /**\n * Snapshot of every module-level Context Contributor registration\n * captured during `setup()`. The registrations themselves are\n * frozen by `defineContextDecorator`, so storing references is\n * safe — they outlive the module instances they came from.\n *\n * Used by {@link getContributors} so DevTools and adopter tooling\n * can render the module-level contributors alongside the adapter /\n * plugin / global ones. Populated once per `setup()` call; cleared\n * at the start of each invocation so a re-setup (test harnesses,\n * dev-server restarts) doesn't accumulate stale entries.\n */\n private _moduleContributors: Array<{\n registration: { key: string; dependsOn: readonly string[] }\n label: string\n }> = []\n\n /** Number of HTTP requests currently being processed */\n private _inFlightRequests = 0\n /** Whether the application is draining (shutting down gracefully) */\n private readonly _status = ref<AppStatus>('idle')\n /**\n * Where the app is in its lifecycle, as a read-only reactive value: read\n * `status.value`, or `watch(app.status, fn)` to act on a change —\n * `'starting'` while `start()` runs, `'ready'` once it serves, `'draining'`\n * from `shutdown()`, `'stopped'` after. An app that is only set up (tests)\n * stays `'idle'`.\n */\n readonly status: ComputedRef<AppStatus> = computed(() => this._status.value)\n /** Whether shutdown has already been initiated (prevents double-shutdown) */\n private _shutdownInitiated = false\n /** Resolvers waiting for in-flight requests to reach zero */\n private _drainResolvers: Array<() => void> = []\n\n constructor(private readonly options: ApplicationOptions) {\n // The default loads Express in setup(), so an app that passes another\n // runtime never needs it installed.\n this.runtime = options.runtime ?? expressRuntime()\n this.container = Container.getInstance()\n this.container.registerInstance(APPLICATION, this)\n\n // Sort plugins by `dependsOn` declarations BEFORE reading their adapters/etc.\n // Plugins without `dependsOn` keep their declaration order — this is a\n // pure refinement; no behaviour change for apps that don't use the field.\n this.plugins = mountSort(options.plugins ?? [], 'plugin')\n\n // Build adapter list from plugin adapters + user adapters, synthesize\n // a stable name for any anonymous adapter (so duplicate-name detection\n // and `dependsOn` resolution have something to key on), then sort by\n // adapter `dependsOn`. Plugin-shipped adapters keep their plugin's\n // relative order unless their own `dependsOn` says otherwise.\n const allAdapters = [\n ...this.plugins.flatMap((p) => p.adapters?.() ?? []),\n ...(options.adapters ?? []),\n ]\n let anonAdapterCount = 0\n const namedAdapters: Array<AppAdapter & { name: string }> = allAdapters.map((adapter) => {\n if (!adapter.name) {\n // `constructor.name === 'Object'` for plain object-literal adapters —\n // useless as an identity since two anonymous literals would collide.\n // Only borrow the constructor name when it's an actual class.\n const ctorName = adapter.constructor?.name\n const fallback =\n ctorName && ctorName !== 'Object' ? ctorName : `AnonymousAdapter#${anonAdapterCount++}`\n return Object.assign(adapter, { name: fallback })\n }\n return adapter as AppAdapter & { name: string }\n })\n this.adapters = mountSort(this.applyConditions(namedAdapters), 'adapter')\n // Adapters and plugins with onError / onResponse observe every error and\n // response; the diagnostics_channel channels are fed from the same funnel.\n this.observers = setObservers([...this.adapters, ...this.plugins])\n installChannelPublisher()\n // Wire the request store provider so Container can resolve REQUEST-scoped deps\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n }\n\n /**\n * Leave out adapters whose `when` says no — and, until nothing changes, any\n * adapter that `dependsOn` one left out, which could not run without it.\n */\n private applyConditions<A extends AppAdapter & { name: string }>(adapters: A[]): A[] {\n // Names identify adapters below, and dependsOn refers to them by name. Two\n // with one name would both be dropped when one is off, hiding the\n // duplicate from mountSort — so reject it first, as mountSort would.\n const seen = new Set<string>()\n for (const adapter of adapters) {\n if (seen.has(adapter.name)) throw new DuplicateMountNameError('adapter', adapter.name)\n seen.add(adapter.name)\n }\n const off = new Map<string, string>()\n for (const adapter of adapters) {\n if (!adapter.when) continue\n const result = evaluateCondition(adapter.when, (err) =>\n log.warn(`Adapter ${adapter.name}: its \\`when\\` condition threw — ${String(err)}`),\n )\n if (result !== true) off.set(adapter.name, result)\n }\n let changed = off.size > 0\n while (changed) {\n changed = false\n for (const adapter of adapters) {\n if (off.has(adapter.name)) continue\n const missing = adapter.dependsOn?.find((dep) => off.has(dep))\n if (missing) {\n off.set(adapter.name, `depends on ${missing}, which is off`)\n changed = true\n }\n }\n }\n this.conditionReport = adapters\n .filter((a) => a.when || off.has(a.name))\n .map((a) =>\n off.has(a.name)\n ? { adapter: a.name, enabled: false, reason: off.get(a.name) }\n : { adapter: a.name, enabled: true },\n )\n for (const outcome of this.conditionReport) {\n if (!outcome.enabled) log.debug(`Adapter ${outcome.adapter} is off: ${outcome.reason}`)\n }\n return adapters.filter((a) => !off.has(a.name))\n }\n\n /**\n * Adapters with a `when` condition, and whether each is on — with the reason\n * when it is not. Served by DevTools at `/_debug/conditions`.\n */\n getConditionReport(): readonly ConditionOutcome[] {\n return this.conditionReport\n }\n\n /** Whether the application is currently draining in-flight requests */\n get isDraining(): boolean {\n return this._status.value === 'draining' || this._status.value === 'stopped'\n }\n\n /** Number of HTTP requests currently being processed */\n get inFlightRequests(): number {\n return this._inFlightRequests\n }\n\n /** Get the DI container instance */\n getContainer(): Container {\n return this.container\n }\n\n /**\n * Express request handler — delegates to the internal Express app.\n *\n * Used by the Vite dev-server plugin to route requests through KickJS:\n * ```ts\n * const mod = await ssrLoadModule('virtual:kickjs/app')\n * mod.app.handle(req, res, next)\n * ```\n *\n * Also works as a standard Node.js request handler for production:\n * ```ts\n * http.createServer(app.handle.bind(app))\n * ```\n */\n /**\n * Run a web `Request` through the app — routing, middleware, validation,\n * contributors, error handling — and return its `Response`, with no\n * listening server required.\n *\n * Runtimes with a native fetch (h3) are called directly.\n * Node-based runtimes (Express, Fastify) are served by forwarding to\n * a server bound to `127.0.0.1` inside this process, started on first use\n * and closed by {@link shutdown}; request bodies are buffered on that path.\n *\n * Used by `createHandler()` and by adapters (`AdapterContext.fetch`) that\n * call the app's own routes, such as MCP and AI tool dispatch.\n */\n fetch(request: Request): Promise<Response> {\n if (this.app === undefined) {\n return Promise.reject(\n new Error(\n 'kickjs: Application.fetch() before setup — await start() or startWithoutServer() first',\n ),\n )\n }\n const runtimeApp = this.app as { fetch?: (request: Request) => unknown }\n if (typeof runtimeApp?.fetch === 'function') {\n return Promise.resolve(runtimeApp.fetch(request) as Response | Promise<Response>)\n }\n this.loopback ??= createLoopback((req, res) => this.handle(req, res))\n return this.loopback.fetch(request)\n }\n\n /** The engine app, from the options — one place, so a rebuild (HMR) keeps them all. */\n private createEngineApp(): unknown {\n return this.runtime.createApp({\n trustProxy: this.options.trustProxy,\n notFoundFallthrough: this.options.notFoundFallthrough,\n bodyLimit: parseByteSize(this.options.jsonLimit ?? DEFAULT_BODY_LIMIT),\n })\n }\n\n handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void {\n if (this.app === undefined) {\n throw new Error(\n 'kickjs: Application.handle() before setup — await start() or startWithoutServer() first',\n )\n }\n // Built once per engine app — the serverless and loopback paths call this\n // per request, and h3 wraps the app in a fresh node listener on each call.\n // Keyed on the app, so a rebuild (HMR) gets a handler for the new one.\n if (!this.handlerFor || this.handlerFor.app !== this.app) {\n this.handlerFor = { app: this.app, handler: this.runtime.nodeHandler(this.app) }\n }\n const handler = this.handlerFor.handler\n if (next) {\n handler(req, res, next)\n } else {\n handler(req, res)\n }\n }\n\n /**\n * Full setup pipeline:\n * 1. Adapter beforeMount hooks (early routes — e.g. docs UI)\n * 2. Adapter middleware (phase: beforeGlobal)\n * 3. Global middleware (user-declared or defaults)\n * 4. Adapter middleware (phase: afterGlobal)\n * 5. Module registration + DI bootstrap (the built-in health module mounts\n * here with everything else — it is NOT an early route)\n * 6. Adapter middleware (phase: beforeRoutes)\n * 7. Module route mounting\n * 8. Adapter middleware (phase: afterRoutes)\n * 9. Adapter beforeStart hooks\n * 10. Error handlers (notFound + global)\n */\n /** Build the adapter context object (shared across all hooks) */\n private adapterCtx(server?: any, owner?: string): AdapterContext {\n const env = process.env.NODE_ENV ?? 'production'\n const managementApp = this.managementApp\n return {\n http: this.adapterHttp(undefined, owner),\n app: this.app,\n fetch: (request) => this.fetch(request),\n container: this.container,\n server,\n ...(managementApp\n ? {\n management: {\n http: this.adapterHttp(() => managementApp, owner),\n server: this.managementServer ?? undefined,\n },\n }\n : {}),\n env,\n isProduction: isProduction(),\n }\n }\n\n /**\n * The engine-agnostic HTTP surface handed to adapters as `ctx.http`. Each\n * call routes through the active runtime over the current `this.app`, so an\n * adapter written against this works under any runtime.\n */\n private adapterHttp(target: () => unknown = () => this.app, owner = 'kick'): AdapterHttp {\n // What an adapter mounts is recorded like a module's routes, so\n // getRoutes() and the startup log can say what each port serves.\n const record = (method: string, pattern: string, handler: string) => {\n this.mountedRouteInfo.push({\n method,\n pattern,\n controller: owner,\n handler,\n contributors: [],\n source: 'adapter',\n port: target() === this.app ? 'app' : 'management',\n })\n }\n return {\n route: (method, path, handler) => {\n record(method, path, '')\n const entry: RouteEntry = {\n method,\n path,\n middlewares: [],\n contributorRunner: null,\n handler,\n meta: {},\n }\n this.runtime.mountRoutes(target(), [{ mountPath: '/', routes: [entry] }])\n },\n mount: (prefix, routes) => {\n for (const entry of routes) {\n record(entry.method, joinPaths(prefix, entry.path), String(entry.meta.handlerName ?? ''))\n }\n this.runtime.mountRoutes(target(), [{ mountPath: prefix, routes }])\n },\n serveStatic: (prefix, dir) => {\n record('GET', `${joinPaths(prefix, '/').replace(/\\/$/, '')}/*`, 'static')\n this.runtime.serveStatic(target(), prefix, dir)\n },\n use: (mw, opts) => {\n this.runtime.useConnect(target(), mw, opts)\n },\n }\n }\n\n /**\n * Call an adapter hook, awaiting async hooks.\n *\n * A setup hook (`beforeMount`, `beforeStart`) that throws aborts boot: the\n * adapter didn't finish wiring itself — a database adapter refusing to\n * start with pending migrations, say — and serving anyway runs on a\n * half-built app. `afterStart` runs once the server is already listening,\n * so its failure is logged and the server keeps going.\n */\n private async callHook(\n hook: ((ctx: AdapterContext) => void | Promise<void>) | undefined,\n ctx: AdapterContext,\n adapterName = 'adapter',\n hookName: 'beforeMount' | 'beforeStart' | 'afterStart',\n ): Promise<void> {\n if (!hook) return\n const where = `${adapterName}.${hookName}`\n try {\n await this.timeline.time(where, () => hook(ctx))\n } catch (err) {\n this.adviseOnFailure(err, where, adapterName)\n // A failing setup hook fails boot; afterStart runs on a live server.\n if (hookName !== 'afterStart') throw err\n log.error(err, `${adapterName} afterStart hook failed`)\n }\n }\n\n /**\n * Log advice for a hook failure: the failing adapter's own analysis first,\n * then the framework's. The error itself is still thrown or logged by the\n * caller — this only adds the explanation in front of it.\n */\n private adviseOnFailure(err: unknown, where: string, adapterName: string): void {\n const adapter = this.adapters.find((a) => a.name === adapterName)\n let advice: FailureAdvice | undefined\n try {\n advice = adapter?.analyzeFailure?.(err)\n } catch (analyzerErr) {\n log.debug(`${adapterName}.analyzeFailure threw: ${String(analyzerErr)}`)\n }\n advice ??= builtInAdvice(err, where)\n if (advice) log.error(formatAdvice(advice))\n }\n\n /**\n * Where the last startup's time went: each phase and each adapter hook, in\n * order. Served by devtools at `/_debug/startup`.\n */\n getStartupTimeline(): StartupTimelineSnapshot {\n return this.timeline.snapshot()\n }\n\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string. For links built outside a\n * request (emails, jobs); inside one, use `ctx.urlFor()`.\n *\n * ```ts\n * app.urlFor('UsersController.show', { id: user.id }) // '/api/v1/users/42'\n * ```\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.routeUrls.build(name, params as Record<string, unknown> | undefined, query)\n }\n\n /** The app's modules — plugins', then its own — in registration order. */\n private collectModules(): MutableModuleRegistry {\n const registry = new MutableModuleRegistry()\n for (const plugin of this.plugins) {\n for (const m of plugin.modules?.() ?? []) registry.mount(m)\n plugin.setup?.(registry)\n }\n for (const m of this.options.modules) registry.mount(m)\n this.options.setup?.(registry)\n return registry\n }\n\n /**\n * Every variable the app reads — its env schema, and each declared settings\n * section with who declared it — and whether each is required, its default\n * and description. Reads no environment and validates nothing, so it works\n * when the environment is missing: it's what `kick env example` writes.\n * Call it on an app that hasn't started.\n */\n describeConfig(): ConfigDescription {\n const sections: ConfigDescription['sections'] = []\n const seen = new Set<Settings<unknown>>()\n const add = (declaredBy: string, list: readonly SettingsDeclaration[] | undefined) => {\n for (const decl of list ?? []) {\n // A provided section still reads these variables when not provided.\n const section = 'section' in decl ? decl.section : decl\n if (seen.has(section)) continue\n seen.add(section)\n sections.push({ prefix: section.prefix, declaredBy, vars: section.describe() })\n }\n }\n add('app', this.options.settings)\n for (const plugin of this.plugins) add(`plugin ${plugin.name}`, plugin.settings?.())\n for (const adapter of this.adapters) add(`adapter ${adapter.name}`, adapter.settings?.())\n for (const entry of this.collectModules().entries) {\n const mod = toAppModule(entry)\n add(`module ${moduleName(mod)}`, mod.settings?.())\n }\n return { env: describeEnvSchema(), sections }\n }\n\n /**\n * Where each variable the app reads gets its value — env, a `_FILE` secret,\n * the schema's default, `provide()`, or nothing — for the env schema and\n * every bound settings section. Names only, never values. Read from the\n * current environment; call it on a started app.\n */\n configOrigins(): ConfigOrigins {\n return {\n env: originsOf(describeEnvSchema()),\n sections: Array.from(this.settingsPrefixes.values(), (section) => ({\n prefix: section.prefix,\n vars: this.settingsProvided.has(section)\n ? section.envNames.map((name) => ({ name, origin: 'provided' as const }))\n : originsOf(section.describe()),\n })),\n }\n }\n\n /** Validate settings sections and bind each under its token. */\n private bindSettings(sections: readonly SettingsDeclaration[]): void {\n for (const [section, value] of loadSettings(\n sections,\n process.env,\n this.settingsPrefixes,\n this.settingsProvided,\n )) {\n this.container.registerInstance(section, value)\n }\n }\n\n /** Run the built-in and the app's startup checks against the assembled app. */\n private runChecks(): void {\n runStartupChecks(\n [...builtInChecks, ...(this.options.checks ?? [])],\n { options: this.options as unknown as Record<string, unknown>, routes: this.mountedRoutes },\n this.options.silenceChecks,\n )\n this.timeline.mark('checks')\n }\n\n /** Log the slowest steps — only when startup was slow enough to ask why. */\n private reportStartup(): void {\n const { totalMs } = this.timeline.snapshot()\n if (totalMs < SLOW_STARTUP_MS) return\n const slowest = this.timeline\n .slowest(3)\n .map((step) => `${step.name} ${Math.round(step.ms)}ms`)\n .join(', ')\n log.info(`Startup took ${Math.round(totalMs)}ms — slowest: ${slowest}`)\n }\n\n async setup(): Promise<void> {\n log.debug('Bootstrapping application...')\n // The engine app — `getRuntimeApp()` / `AdapterContext.app`, typed through\n // ActiveRuntime — once the runtime has loaded its engine. A rebuild (HMR)\n // brings its own.\n await this.runtime.load?.()\n await settleExpressLoad()\n this.app ??= this.createEngineApp()\n if (this.wantsManagement) this.managementApp ??= this.createEngineApp()\n this.timeline = new StartupTimeline()\n // Before the adapters' hooks: the routes they add are recorded too.\n this.mountedRouteInfo = []\n // Bound before modules register, so their services can inject it; the\n // routes fill it in as they mount.\n this.routeUrls = new RouteUrls()\n this.container.registerInstance(ROUTE_URLS, this.routeUrls)\n this.container.registerInstance(APPLICATION, this)\n this.settingsPrefixes = new Map()\n this.settingsProvided = new Map()\n // Settings sections declared by bootstrap, plugins and enabled adapters:\n // validated now — a bad value fails startup with the full list — and bound\n // before any hook runs. Modules' sections are bound before they register.\n this.bindSettings([\n ...(this.options.settings ?? []),\n ...this.plugins.flatMap((plugin) => plugin.settings?.() ?? []),\n ...this.adapters.flatMap((adapter) => adapter.settings?.() ?? []),\n ])\n\n // Reset module-contributor snapshot at the very top of each\n // setup pass — before anything that could throw — so a partial\n // failure doesn't leave stale entries that getContributors()\n // would surface on the next call. See _moduleContributors field\n // declaration for the use case.\n this._moduleContributors = []\n\n // Collect adapter middleware by phase\n const adapterMw = this.collectAdapterMiddleware()\n\n // Expose the Application instance on the Express app for adapter discovery\n ;(this.app as any).__kickApp = this\n\n // ── 0. Host allow-list, before anything is mounted ─────────────────\n // First, ahead of adapter beforeMount: routes an adapter registers there\n // (docs UIs, devtools, the cron trigger) would otherwise answer on\n // Express before the check runs.\n const hostList = this.options.security?.allowedHosts\n if (hostList) {\n const hostOptions = Array.isArray(hostList) ? { hosts: hostList } : hostList\n this.runtime.useConnect(\n this.app,\n allowedHosts({\n ...hostOptions,\n ignorePaths: [...(hostOptions.ignorePaths ?? []), '/health/live', '/health/ready'],\n }),\n )\n }\n\n // ── 1. Adapter beforeMount hooks ──────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(\n adapter.beforeMount?.bind(adapter),\n this.adapterCtx(undefined, adapter.name),\n adapter.name,\n 'beforeMount',\n )\n }\n\n // ── 1a. Cron trigger (serverless) ─────────────────────────────────\n if (this.handlerMode) this.mountCronTrigger()\n\n // ── 2. Hardened defaults ──────────────────────────────────────────\n // x-powered-by disable + trust proxy now live in `runtime.createApp()`.\n\n // ── 2a. In-flight request tracking ──────────────────────────────\n this.runtime.useConnect(this.app, this.requestTrackingMiddleware())\n\n // ── 2c. Request scope (AsyncLocalStorage) ────────────────────────\n // Auto-mounted unless the user opted out (`contextStore: 'manual'`)\n // or already included one in their middleware list.\n if (this.shouldAutoMountRequestScope()) {\n this.runtime.useConnect(this.app, requestScopeMiddleware())\n }\n // The management app runs none of the app's middleware, so it gets its own\n // request scope even when the app mounted one itself.\n if (this.managementApp && this.options.contextStore !== 'manual') {\n this.runtime.useConnect(this.managementApp, requestScopeMiddleware())\n }\n\n // ── 3. Adapter middleware: beforeGlobal ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeGlobal)\n\n // ── 3b. Plugin registration ──────────────────────────────────────\n for (const plugin of this.plugins) {\n plugin.register?.(this.container)\n }\n\n // ── 3c. Plugin middleware ─────────────────────────────────────────\n for (const plugin of this.plugins) {\n try {\n const mw = plugin.middleware?.() ?? []\n for (const handler of mw) {\n this.runtime.useConnect(this.app, handler)\n }\n } catch (err) {\n log.error(err, `Plugin middleware failed: ${(plugin as any).name ?? 'unknown'}`)\n }\n }\n\n // ── 4. Global middleware ─────────────────────────────────────────\n // Auto-inject helmet unless opted out, or unless the app mounts its own.\n // Injecting alongside a user helmet makes its options half-inert: ours runs\n // first with defaults, and theirs can only overwrite a header, never drop\n // one — so `helmet({ frameguard: false })` would still emit DENY.\n // Only a GLOBAL declaration stands us down. The object form of\n // MiddlewareEntry always carries a `path`, so a helmet scoped to one route\n // does not replace the app-wide pass — standing down for it would strip\n // security headers from every OTHER path.\n // `Symbol.for` registry lookup, so the dynamic import() below stays intact.\n const declaredHelmet = (this.options.middlewares ?? []).some(\n (entry) => typeof entry === 'function' && Symbol.for('kick/http/helmet') in entry,\n )\n const autoHelmet = this.options.security?.helmet !== false && !declaredHelmet\n if (autoHelmet) {\n try {\n const { helmet: helmetFn } = await import('./middleware/helmet')\n this.runtime.useConnect(this.app, helmetFn())\n } catch {\n // helmet middleware not available — skip silently\n }\n }\n\n const userMiddlewares = this.options.middlewares\n if (userMiddlewares) {\n // User-declared pipeline — full control\n for (const entry of userMiddlewares) {\n this.mountMiddlewareEntry(entry)\n }\n } else {\n // Sensible defaults when no middleware declared\n this.runtime.useConnect(this.app, requestId())\n // Skip express.json on engines that parse bodies natively (Fastify, h3) —\n // otherwise the body stream is read twice and the engine's parser hangs.\n if (!this.runtime.capabilities.nativeBodyParsing) {\n const limit = this.options.jsonLimit ?? DEFAULT_BODY_LIMIT\n const parsers = this.runtime.bodyParsers\n ? this.runtime.bodyParsers({ limit })\n : await expressBodyParsers(limit)\n for (const parser of parsers) {\n this.runtime.useConnect(this.app, parser)\n }\n }\n }\n\n // ── 5. Adapter middleware: afterGlobal ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterGlobal)\n this.timeline.mark('middleware')\n\n // ── 6. Module registration + DI bootstrap ────────────────────────\n // Module collection — the static `modules: [...]` array AND the\n // imperative `setup(registry)` callback feed into the same\n // ordered list. Plugins go first so plugin modules / setup\n // calls run before user code (existing precedence).\n //\n // Order within the registry:\n // 1. plugin static modules (`plugin.modules?()`)\n // 2. plugin setup() calls (in plugin dependsOn-sorted order)\n // 3. user static modules (`options.modules`)\n // 4. user setup() callback\n const moduleRegistry = this.collectModules()\n\n // The built-in health endpoints, as an ordinary module. Registered last so\n // an app's own `/health` module wins by being mounted first, and skipped\n // entirely with `health: false`.\n //\n // The probe is bound before `register()` runs below, because the module's\n // factory resolves it. It closes over the Application rather than exposing\n // it: `isDraining` and `checks` are the whole surface the endpoints need,\n // so a replacement module can satisfy the same token.\n if (this.options.health !== false) {\n this.container.registerInstance(HEALTH_PROBE, {\n isDraining: () => this.isDraining,\n isStarting: () => this._status.value === 'starting',\n checks: createHealthChecks(() => this.adapters, {\n timeoutMs:\n typeof this.options.health === 'object' ? this.options.health.checkTimeout : undefined,\n onSlow: (name, ms) => log.warn(`Health check '${name}' took ${ms}ms`),\n }),\n })\n moduleRegistry.mount(healthModule(this.options.health === true ? {} : this.options.health))\n }\n const allModuleEntries: AppModuleEntry[] = moduleRegistry.entries\n const modules = allModuleEntries.map(toAppModule)\n // Mounted modules' settings sections, bound before any of them registers.\n this.bindSettings(modules.flatMap((mod) => mod.settings?.() ?? []))\n for (const mod of modules) {\n // `register()` is optional — modules whose classes are entirely\n // decorator-managed (@Service, @Controller, @Repository) don't need it.\n mod.register?.(this.container)\n }\n this.container.bootstrap()\n\n // Register Logger as an injectable singleton so @Inject(Logger)\n // works in constructors. Without this, Logger is just a plain\n // class with static methods and no DI binding.\n if (!this.container.has(Logger)) {\n this.container.registerInstance(Logger, new Logger())\n }\n\n this.timeline.mark('modules')\n\n // ── 7. Adapter middleware: beforeRoutes ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeRoutes)\n\n // ── 8. Mount module routes with versioning ───────────────────────\n const apiPrefix = this.options.apiPrefix ?? '/api'\n const defaultVersion = this.options.defaultVersion ?? 1\n // Opt-in, default off. `logRouteTable` is the current name;\n // `logRoutesTable` is the deprecated alias.\n const shouldLogRoutes = this.options.logRouteTable ?? this.options.logRoutesTable ?? false\n\n // Collect route metadata during mounting (avoids calling mod.routes() twice)\n const mountedRoutes: Array<{ controller: any; mountPath: string; management?: boolean }> = []\n\n // Context Contributors (#107) — collect adapter + plugin + global once;\n // per-module sources are computed inside the loop so module isolation is\n // preserved.\n //\n // Plugin contributors merge at the same `'adapter'` precedence as adapter\n // contributors. Plugins are conceptually \"bundles of adapters + extras\",\n // so a plugin that ships a typed contributor without standing up an\n // accompanying adapter behaves identically to one that does.\n const adapterSources: SourcedRegistration[] = []\n for (const adapter of this.adapters) {\n const adapterContribs = adapter.contributors?.() ?? []\n const adapterLabel = adapter.name ?? adapter.constructor.name ?? 'adapter'\n for (const registration of adapterContribs) {\n adapterSources.push({ source: 'adapter', registration, label: adapterLabel })\n }\n }\n for (const plugin of this.plugins) {\n const pluginContribs = plugin.contributors?.() ?? []\n const pluginLabel = plugin.name ?? plugin.constructor?.name ?? 'plugin'\n for (const registration of pluginContribs) {\n adapterSources.push({ source: 'adapter', registration, label: pluginLabel })\n }\n }\n const globalSources: SourcedRegistration[] = (this.options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration,\n label: 'bootstrap',\n }),\n )\n\n // Reset module-contributor snapshot at the start of each setup\n // pass so re-running `setup()` (test harnesses, dev-server\n // restarts) doesn't accumulate stale entries.\n this._moduleContributors = []\n\n // Duplicate-route guard (KICK006): one registry across every module in\n // this setup pass, so cross-module collisions fail at boot instead of\n // silently losing the dispatch race.\n const seenRoutes = new Map<string, string>()\n\n // Every path this app mounts, for the catch-all: a request that matches a\n // path but not its method is a 405, not a 404. Collected here because this\n // is the only place that knows the FULL mounted path — prefix, version and\n // controller route joined.\n const mountedPaths: MountedRoute[] = []\n const managementPaths: MountedRoute[] = []\n this.mountedRoutes = mountedPaths\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n // Retain registrations for `getContributors()` — these would\n // otherwise be unreachable post-bootstrap (module instances\n // are not kept on the Application).\n for (const src of moduleSources) {\n this._moduleContributors.push({\n registration: src.registration as { key: string; dependsOn: readonly string[] },\n label: moduleLabel,\n })\n }\n\n // Thread per-module + adapter + global sources to buildRoutes via the\n // module-scoped slot. Module setup is sequential, so the slot is\n // race-free. The slot MUST stay populated across both `mod.routes()`\n // AND any framework-driven `buildRoutes(controller)` calls below —\n // when a module returns `{ path, controller }` (auto-derive shape),\n // buildRoutes runs here, not inside routes(). Clearing the slot in\n // the routes()-finally would drop module/adapter/global contributors\n // on the floor and surface as `MissingContributorError` for any\n // class/method-level dependsOn referencing a module-level key.\n _setExternalContributorSources([...moduleSources, ...adapterSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue // Non-HTTP modules (queues, cron) may return null\n\n const routeSets = Array.isArray(result) ? result : [result]\n\n for (const route of routeSets) {\n const version = route.version ?? defaultVersion\n // `prefix: false` mounts at the root — see ModuleRoutes.prefix.\n const mountPath = buildMountPath(\n route.prefix === false ? '' : apiPrefix,\n version,\n route.path,\n )\n // Common-case `{ path, controller }`: build the engine-neutral route\n // table and let the runtime materialize it natively (Express Router /\n // Fastify routes / …). Adopters who hand-build a `router` (composing\n // multiple controllers, third-party routers) pass it explicitly — that\n // is an Express-specific connect handler, mounted via `useConnect`.\n if (route.router) {\n this.runtime.useConnect(this.app, route.router, { path: mountPath })\n } else if (route.controller) {\n // The built-in health routes answer on the management port when there is one.\n const target =\n this.managementApp && route.controller === HealthController\n ? this.managementApp\n : this.app\n const routeTable = buildRouteTable(route.controller, { mountFlags: route.flags })\n const ctrl = route.controller.name ?? 'controller'\n for (const entry of routeTable) {\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${ctrl}.${String(entry.meta.handlerName ?? '?')}`\n const fullPath = joinPaths(mountPath, entry.path)\n assertRouteUnique(seenRoutes, entry.method, fullPath, owner)\n ;(target === this.app ? mountedPaths : managementPaths).push({\n method: entry.method,\n path: fullPath,\n })\n this.routeUrls.add(owner, fullPath)\n this.routePolicy.add(entry.method, fullPath, entry.meta.flags)\n }\n // Each handler runs inside the `kickjs:handler` tracing channel (a\n // no-op without subscribers), and carries its full pattern so\n // metrics and spans are keyed by `/api/v1/users/:id`, not `/:id`.\n // Copies, not edits: `routeTable` entries also feed the route policy\n // table and the duplicate-route check above.\n // oxlint-disable-next-line no-map-spread\n const traced = routeTable.map((entry) => {\n const pattern = joinPaths(mountPath, entry.path)\n return {\n ...entry,\n handler: traceHandler(entry.handler, {\n method: entry.method,\n route: pattern,\n controller: route.controller?.name,\n handler: entry.meta.handlerName,\n }),\n meta: { ...entry.meta, pattern },\n validationError: this.options.validationError,\n urls: this.routeUrls,\n }\n })\n this.runtime.mountRoutes(target, [{ mountPath, routes: traced }])\n for (const entry of traced) {\n this.mountedRouteInfo.push({\n method: entry.method,\n pattern: entry.meta.pattern ?? entry.path,\n controller: route.controller.name,\n handler: String(entry.meta.handlerName ?? ''),\n contributors: entry.meta.contributors ?? [],\n source: 'module',\n port: target === this.app ? 'app' : 'management',\n })\n }\n } else {\n throw moduleRouteMissingControllerError(mountPath)\n }\n\n // Notify adapters (e.g. SwaggerAdapter for OpenAPI spec generation) —\n // of the app's own routes: one on the management port isn't part of\n // the API a spec describes.\n const onManagement = !!this.managementApp && route.controller === HealthController\n if (route.controller && !onManagement) {\n for (const adapter of this.adapters) {\n try {\n adapter.onRouteMount?.(route.controller, mountPath)\n } catch (err) {\n log.error(err, `adapter.onRouteMount() failed for ${mountPath}`)\n }\n }\n }\n if (route.controller && shouldLogRoutes) {\n mountedRoutes.push({\n controller: route.controller,\n mountPath,\n management: onManagement,\n })\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // ── 8b. Log route summary ─────────────────────────────────────────\n if (shouldLogRoutes && mountedRoutes.length > 0) {\n const methodOrder = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']\n const methodRank = (m: string) => {\n const i = methodOrder.indexOf(m)\n return i === -1 ? 99 : i\n }\n\n let totalRoutes = 0\n log.info('Routes:')\n\n for (const { controller, mountPath, management } of mountedRoutes) {\n const defs: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controller,\n [],\n )\n if (defs.length === 0) continue\n\n const counts: Record<string, number> = {}\n for (const def of defs) {\n const m = def.method.toUpperCase()\n counts[m] = (counts[m] || 0) + 1\n }\n totalRoutes += defs.length\n\n const methods = Object.entries(counts)\n .toSorted(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([m, n]) => `${n} ${m}`)\n .join(', ')\n const name = controller.name || 'Controller'\n const port = management ? ' [management port]' : ''\n log.info(\n ` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})${port}`,\n )\n }\n\n log.info(` Total: ${totalRoutes} routes`)\n }\n\n // ── 9. Adapter middleware: afterRoutes ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterRoutes)\n this.timeline.mark('routes')\n\n // ── 10. Adapter beforeStart hooks ────────────────────────────────\n // Runs BEFORE error handlers so adapters can still mount Express\n // routes (e.g. `McpAdapter` registers `/_mcp/messages` here). If\n // error handlers were registered first, the notFoundHandler — a\n // catch-all that never calls next() — would pre-empt anything an\n // adapter adds afterwards and adapter-mounted endpoints would 404.\n for (const adapter of this.adapters) {\n await this.callHook(\n adapter.beforeStart?.bind(adapter),\n this.adapterCtx(undefined, adapter.name),\n adapter.name,\n 'beforeStart',\n )\n }\n\n // ── 11. Error handlers ───────────────────────────────────────────\n // Last in the chain so any adapter-mounted route (step 10) gets\n // a chance to match before the catch-all 404 fires.\n // `onNotFound` / `onError` still win — the route table only sharpens the\n // DEFAULT, so an app that supplies its own catch-all is unaffected.\n // Routes are mounted: middleware that asked for the policy table can have\n // it now. Global middleware was mounted earlier — its closure reads the\n // table per request, so binding after the fact is in time.\n for (const entry of this.options.middlewares ?? []) {\n offerRoutePolicy(typeof entry === 'function' ? entry : entry.handler, this.routePolicy)\n }\n for (const adapter of this.adapters) {\n for (const mw of adapter.middleware?.() ?? []) offerRoutePolicy(mw.handler, this.routePolicy)\n }\n\n const builtInNotFound = notFoundHandler(mountedPaths)\n const customNotFound = this.options.onNotFound\n // Typed with RuntimeResponse, which every runtime's driver provides; the\n // connect types only promise Node's ServerResponse.\n this.runtime.setNotFound(\n this.app,\n (customNotFound\n ? (req: any, res: RuntimeResponse, next: (err?: unknown) => void) =>\n customNotFound(req, res, (err?: unknown) =>\n err === undefined ? builtInNotFound(req, res, next as () => void) : next(err),\n )\n : builtInNotFound) as unknown as ConnectMiddleware,\n )\n this.runtime.setErrorHandler(\n this.app,\n observeErrors(this.options.onError ?? errorHandler()) as unknown as ConnectMiddleware,\n )\n if (this.managementApp) {\n this.runtime.setNotFound(\n this.managementApp,\n notFoundHandler(managementPaths) as unknown as ConnectMiddleware,\n )\n this.runtime.setErrorHandler(\n this.managementApp,\n observeErrors(errorHandler()) as unknown as ConnectMiddleware,\n )\n }\n this.timeline.mark('error handlers')\n }\n\n /** Register modules and DI without starting the HTTP server (used by kick tinker) */\n async registerOnly(): Promise<void> {\n await this.setup()\n }\n\n /**\n * Make the app ready to serve requests handed to it, with no server of its\n * own — the serverless path behind {@link createHandler}.\n *\n * Runs the same `setup()` as {@link start} and the plugins' `onReady`, but\n * nothing that needs a listening server: there is no port, no `afterStart`\n * (it receives the `http.Server`), and no process signal handlers.\n */\n async startWithoutServer(): Promise<void> {\n await this.untilStartedOrStopped(() => this.startWithoutServerSteps())\n }\n\n /**\n * Run a startup, leaving the status at `'stopped'` if it fails — a failed\n * startup is not still starting.\n */\n private async untilStartedOrStopped(run: () => Promise<void>): Promise<void> {\n try {\n await run()\n } catch (err) {\n this._status.value = 'stopped'\n throw err\n }\n }\n\n private async startWithoutServerSteps(): Promise<void> {\n this.handlerMode = true\n this._status.value = 'starting'\n await this.setup()\n this.runChecks()\n\n const needServer = this.adapters.filter((adapter) => adapter.afterStart)\n if (needServer.length > 0) {\n log.warn(\n `No HTTP server in handler mode, so afterStart does not run for: ${needServer\n .map((adapter) => adapter.name)\n .join(\n ', ',\n )}. Anything they attach to the server (WebSockets, upgrade handlers) is unavailable.`,\n )\n }\n\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n this.timeline.mark('ready')\n this._status.value = 'ready'\n this.timeline.complete()\n this.reportStartup()\n }\n\n /**\n * Start the HTTP server.\n *\n * In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`\n * created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real\n * `http.Server` through `afterStart({ server })` — zero adapter changes needed.\n *\n * In **production**: creates its own `http.Server` and binds to the port.\n */\n async start(): Promise<void> {\n await this.untilStartedOrStopped(() => this.startSteps())\n }\n\n private async startSteps(): Promise<void> {\n const g = globalThis as any\n const serverOptions = this.options.server\n this._status.value = 'starting'\n\n // Check the server options before setup() so a bad combination fails\n // before any adapter has done work.\n if (serverOptions && g.__kickjs_httpServer) {\n log.warn('server options (tls / http2) are ignored in dev mode — Vite owns the server')\n } else if (serverOptions) {\n if (serverOptions.http2 === true && !serverOptions.tls) throw http2RequiresTlsError()\n if (serverOptions.http2 === 'h2c' && serverOptions.tls) throw http2RequiresTlsError(true)\n if (serverOptions.http2 && !this.runtime.capabilities.http2) {\n throw http2UnsupportedRuntimeError(this.runtime.name)\n }\n if (serverOptions.tls) assertUsableTls(serverOptions.tls)\n }\n\n const management = this.options.management\n if (management && g.__kickjs_httpServer) {\n log.info('management port is ignored in dev mode — /health stays on the dev server')\n } else if (management) {\n // setup() creates it beside the app, once the runtime has loaded its\n // engine — adapters see `ctx.management` from beforeMount on.\n this.wantsManagement = true\n }\n\n await this.setup()\n this.runChecks()\n\n if (g.__kickjs_httpServer) {\n // ── DEV MODE: Vite owns the http.Server ──────────────────────\n // Don't create a new server or listen — Vite is already listening.\n // Just wire up adapters with the Vite-created server.\n this.httpServer = g.__kickjs_httpServer\n log.debug('Attached to Vite dev server')\n\n // Dev mode suppresses our own SIGINT/SIGTERM handlers (Vite owns\n // the process lifecycle), so a Ctrl+C would otherwise skip graceful\n // shutdown entirely — `adapter.shutdown()`, request draining, and\n // any shutdown logs never run. Expose `shutdown()` on globalThis so\n // the CLI dev server (`kick dev`) can drive it before tearing down\n // Vite. Same process, so the CLI's signal handler can reach this.\n g.__kickjs_app_shutdown = () => this.shutdown()\n\n for (const adapter of this.adapters) {\n const ctx = this.adapterCtx(this.httpServer!, adapter.name)\n await this.callHook(adapter.afterStart?.bind(adapter), ctx, adapter.name, 'afterStart')\n }\n\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n this.timeline.mark('ready')\n this._status.value = 'ready'\n this.timeline.complete()\n this.reportStartup()\n\n return\n }\n\n // ── PRODUCTION: Create and own the http.Server ─────────────────\n const port = this.options.port ?? parseInt(process.env.PORT || '3000', 10)\n this.httpServer = this.createNodeServer()\n\n this.httpServer.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n log.error(\n `Port ${port} is already in use. Kill the existing process or use a different port:\\n` +\n ` PORT=${port + 1} kick dev\\n` +\n ` lsof -i :${port} # find what's using it\\n` +\n ` kill <PID> # stop it`,\n )\n process.exit(1)\n }\n throw err\n })\n\n if (this.managementApp && management) await this.listenManagement(management)\n\n try {\n await this.listenAndFinishStartup(port, serverOptions)\n } catch (err) {\n // A failed startup leaves no listener behind to keep the process up.\n await this.closeManagementServer()\n throw err\n }\n }\n\n /** Listen on the public port, then run afterStart and onReady. */\n private async listenAndFinishStartup(\n port: number,\n serverOptions: ApplicationOptions['server'],\n ): Promise<void> {\n // Wrap listen in a Promise so afterStart/onReady errors propagate\n await new Promise<void>((resolve, reject) => {\n this.httpServer!.listen(port, async () => {\n try {\n const scheme = serverOptions?.tls ? 'https' : 'http'\n const protocol =\n serverOptions?.http2 === 'h2c'\n ? ' (cleartext HTTP/2)'\n : serverOptions?.http2\n ? ' (HTTP/2)'\n : ''\n this.timeline.mark('listen')\n log.info(`Server running on ${scheme}://localhost:${port}${protocol}`)\n\n for (const adapter of this.adapters) {\n const afterCtx = this.adapterCtx(this.httpServer!, adapter.name)\n await this.callHook(\n adapter.afterStart?.bind(adapter),\n afterCtx,\n adapter.name,\n 'afterStart',\n )\n }\n\n // Plugin onReady hooks\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n this.timeline.mark('ready')\n this._status.value = 'ready'\n this.timeline.complete()\n this.reportStartup()\n\n resolve()\n } catch (err) {\n reject(err)\n }\n })\n })\n }\n\n private async closeManagementServer(): Promise<void> {\n const server = this.managementServer\n if (!server) return\n this.managementServer = null\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n server.closeAllConnections()\n })\n }\n\n /** The management listener: on its own port, before the public one; HTTPS with `tls`. */\n private async listenManagement(options: ManagementOptions): Promise<void> {\n const handler = this.runtime.nodeHandler(this.managementApp!)\n if (options.tls) assertUsableTls(options.tls)\n const server = options.tls\n ? https.createServer(options.tls, handler)\n : http.createServer(handler)\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(options.port, options.host, () => {\n server.off('error', reject)\n resolve()\n })\n })\n this.managementServer = server\n const scheme = options.tls ? 'https' : 'http'\n log.info(`Management server on ${scheme}://${options.host ?? 'localhost'}:${options.port}`)\n for (const line of describeRoutes(\n this.mountedRouteInfo.filter((r) => r.port === 'management'),\n )) {\n log.info(` ${line}`)\n }\n }\n\n /** The production server for {@link ApplicationOptions.server}. */\n private createNodeServer(): KickServer {\n const server = this.createBareServer()\n const options = this.options.server ?? {}\n const keepAlive = options.keepAliveTimeout ?? 65_000\n // HTTP/2 sessions have their own lifetime; these apply to HTTP/1.1 servers.\n if ('keepAliveTimeout' in server) {\n server.keepAliveTimeout = keepAlive\n // Must exceed keepAliveTimeout, or Node can drop a reused connection\n // while its next request's headers are arriving.\n server.headersTimeout = options.headersTimeout ?? keepAlive + 1000\n server.requestTimeout = options.requestTimeout ?? 300_000\n }\n return server\n }\n\n private createBareServer(): KickServer {\n const handler = this.runtime.nodeHandler(this.app)\n const { tls, http2: useHttp2 } = this.options.server ?? {}\n if (useHttp2) {\n // The compat API hands the handler Http2ServerRequest/Response; runtimes\n // that declare `capabilities.http2` accept them.\n // h2c has no ALPN to negotiate with, so no HTTP/1.1 fallback either.\n const server =\n useHttp2 === 'h2c'\n ? http2.createServer(handler as never)\n : http2.createSecureServer({ ...tls, allowHTTP1: true }, handler as never)\n server.on('session', (session) => {\n this.http2Sessions.add(session)\n session.once('close', () => this.http2Sessions.delete(session))\n })\n return server\n }\n if (tls) return https.createServer(tls, handler)\n return http.createServer(handler)\n }\n\n /** HMR rebuild: swap Express handler without restarting the server */\n async rebuild(): Promise<void> {\n // Build the new app fully before swapping — if setup() throws,\n // the old app keeps running so the server stays responsive.\n const prevApp = this.app\n const prevContainer = this.container\n // setup() replaces the URL registry; a failed rebuild keeps the old routes\n // serving, so it must keep their names too.\n const prevRouteUrls = this.routeUrls\n // Likewise the settings bookkeeping configOrigins() reads.\n const prevSettingsPrefixes = this.settingsPrefixes\n const prevSettingsProvided = this.settingsProvided\n // Snapshot the outgoing app's disposables (session/rate-limit store\n // intervals) BEFORE setup() registers the incoming app's. On success the\n // stale set is disposed — without this, every HMR swap leaked one live\n // interval + Map per store. On failure it's restored, and whatever the\n // failed setup() half-registered is disposed instead.\n const staleDisposables = drainDisposables()\n\n try {\n Container.reset()\n this.container = Container.getInstance()\n this.app = this.createEngineApp()\n await this.setup()\n } catch (err) {\n log.error(err, 'HMR rebuild failed, keeping previous app')\n // Restore previous state so the server stays responsive\n await runDisposables(drainDisposables())\n for (const d of staleDisposables) registerDisposable(d)\n this.app = prevApp\n this.container = prevContainer\n this.routeUrls = prevRouteUrls\n this.settingsPrefixes = prevSettingsPrefixes\n this.settingsProvided = prevSettingsProvided\n return\n }\n\n await runDisposables(staleDisposables)\n\n if (this.httpServer) {\n this.httpServer.removeAllListeners('request')\n this.httpServer.on('request', this.runtime.nodeHandler(this.app))\n log.debug('HMR: app rebuilt and swapped')\n }\n }\n\n /**\n * Graceful shutdown with request draining.\n *\n * 1. Stops accepting new connections (server.close())\n * 2. Waits for in-flight requests to complete (up to shutdownTimeout)\n * 3. Calls adapter.shutdown() for all registered adapters\n * 4. Force-closes after timeout\n *\n * Safe to call multiple times — subsequent calls return the same promise.\n */\n async shutdown(options: ShutdownOptions = {}): Promise<void> {\n // `closeServer: false` is the HMR reload path. In dev the HTTP server is\n // SHARED across rebuilds via `globalThis.__kickjs_httpServer`, so closing\n // it would kill the dev server on the first save — which is why the reload\n // path used to skip teardown entirely, leaking an adapter set per reload.\n // Everything below Step 2 is what a reload actually needs.\n const closeServer = options.closeServer ?? true\n // Prevent double-shutdown — return immediately if already initiated\n if (this._shutdownInitiated) {\n log.debug('Shutdown already in progress, skipping duplicate call')\n return\n }\n this._shutdownInitiated = true\n this._status.value = 'draining'\n\n // Readiness already answers 503; keep serving while the balancers notice.\n const preStopDelay = this.options.preStopDelay ?? 0\n if (closeServer && preStopDelay > 0) {\n log.debug(`Waiting ${preStopDelay}ms for load balancers to stop routing here...`)\n await new Promise((resolve) => setTimeout(resolve, preStopDelay))\n }\n\n log.debug('Shutting down — draining in-flight requests...')\n\n const timeoutMs = this.options.shutdownTimeout ?? 30_000\n let timer: ReturnType<typeof setTimeout> | undefined\n\n // Start a force-exit timer if timeout is configured\n const forceExitPromise =\n timeoutMs > 0\n ? new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n timer.unref()\n })\n : new Promise<never>(() => {}) // never resolves — no forced exit\n\n try {\n // Step 1: Stop accepting new connections.\n // server.close() prevents new connections. Its callback fires only when\n // ALL existing connections are fully closed, so we do NOT await it here —\n // we track request draining separately via the tracking middleware.\n if (closeServer && this.httpServer) {\n this.httpServer.close(() => {})\n // GOAWAY on every open HTTP/2 session: streams in flight finish,\n // new ones are refused.\n for (const session of this.http2Sessions) session.close()\n }\n\n // Step 2: Wait for in-flight requests to drain (or timeout).\n // Skipped on a reload: the server keeps listening and the fresh app\n // takes over, so there is nothing to drain toward — waiting would just\n // stall the rebuild for up to `shutdownTimeout`.\n if (closeServer && this._inFlightRequests > 0) {\n log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`)\n const drainPromise = new Promise<'drained'>((resolve) => {\n this._drainResolvers.push(() => resolve('drained'))\n })\n\n const result = await Promise.race([drainPromise, forceExitPromise])\n if (result === 'timeout') {\n log.warn(\n `Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`,\n )\n for (const session of this.http2Sessions) session.destroy()\n } else {\n log.debug('All in-flight requests completed')\n }\n }\n\n // Step 2b: Wait for work handed to `waitUntil()` — it outlives its\n // response, so draining requests alone doesn't cover it. Same budget\n // as the drain; skipped on a reload, where the process keeps running.\n if (closeServer && pendingBackgroundWork() > 0) {\n log.debug(`Waiting for ${pendingBackgroundWork()} waitUntil() task(s) to settle...`)\n const settled = await Promise.race([\n settleBackgroundWork().then(() => 'settled' as const),\n forceExitPromise,\n ])\n if (settled === 'timeout') {\n log.warn(\n `Shutdown timeout (${timeoutMs}ms) reached with ${pendingBackgroundWork()} waitUntil() task(s) still running`,\n )\n }\n }\n\n // Step 3: Run all plugin + adapter shutdowns concurrently.\n //\n // Each hook is time-boxed INDIVIDUALLY. An unbounded `allSettled` here\n // means one hook that never settles wedges the whole shutdown, and on\n // the reload path that leaves the dev server with no app and no error —\n // it just stops rebuilding. Seen with a socket.io adapter calling\n // `io.close(cb)`: that callback fires only once every client\n // disconnects, so a single open browser tab hung every save forever.\n //\n // A reload gets a much shorter budget than a real shutdown — nobody\n // wants to wait `shutdownTimeout` (30s by default) per keystroke-save.\n // `shutdownTimeout: 0` means \"no forced exit\" for the drain above, so it\n // disables the per-hook budget too. Anything else would invert the\n // setting: `Math.min(0, 5_000)` is a ZERO-ms budget, which fires before\n // any hook can settle and silently skips every cleanup there is.\n const hookTimeoutMs = closeServer ? timeoutMs : Math.min(timeoutMs, 5_000)\n const timeBoxed = (label: string, run: () => unknown): Promise<unknown> => {\n // Invoke inside the promise: a hook that throws SYNCHRONOUSLY would\n // otherwise escape at the argument site, before `allSettled` wraps it,\n // taking down the whole teardown instead of just its own entry.\n const hook = (async () => run())()\n if (hookTimeoutMs <= 0) return hook\n return new Promise<unknown>((resolve, reject) => {\n const t = setTimeout(() => {\n log.warn(\n `${label} did not finish shutting down within ${hookTimeoutMs}ms — continuing without it. ` +\n `Its resources may still be held.`,\n )\n resolve(undefined)\n }, hookTimeoutMs)\n t.unref()\n // Clear on BOTH paths. `Promise.race` alone leaves the timer armed,\n // so a hook that finished promptly still logged a timeout warning\n // once the budget elapsed — on the reload path that is a false\n // accusation after every save.\n hook.then(\n (value) => {\n clearTimeout(t)\n resolve(value)\n },\n (err) => {\n clearTimeout(t)\n reject(err)\n },\n )\n })\n }\n\n const wasListening = this.httpServer?.listening === true\n const results = await Promise.allSettled([\n ...this.plugins.map((plugin) =>\n timeBoxed(`Plugin '${plugin.name}'`, () => plugin.shutdown?.()),\n ),\n ...this.adapters.map((adapter) =>\n timeBoxed(`Adapter '${adapter.name}'`, () => adapter.shutdown?.()),\n ),\n timeBoxed(`Runtime '${this.runtime.name}'`, () => this.runtime.close?.(this.app)),\n ...(this.managementApp && closeServer\n ? [\n timeBoxed(`Runtime '${this.runtime.name}' (management)`, () =>\n this.runtime.close?.(this.managementApp),\n ),\n ]\n : []),\n ])\n\n // A reload must leave the shared dev server listening. If a hook closed\n // it, every later request is ECONNREFUSED and the port never comes back\n // — with nothing in the log to say why. socket.io's `close()` does\n // exactly this: it closes the HTTP server it was constructed with.\n if (!closeServer && wasListening && this.httpServer?.listening === false) {\n log.error(\n 'An adapter or plugin closed the shared HTTP server during an HMR reload. ' +\n 'The dev server is now unreachable and will not rebind until you restart it. ' +\n \"Close only what you own: socket.io's `io.close()` closes the HTTP server passed \" +\n 'to its constructor — on a reload, disconnect the sockets instead.',\n )\n }\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error({ err: result.reason }, 'Adapter shutdown failed')\n }\n }\n\n // Step 4: Release framework-owned resources started outside the\n // adapter lifecycle — in-memory session/rate-limit store intervals —\n // and flush any pending container change batch so its debounce timer\n // doesn't outlive the app.\n await disposeAll()\n this.container.flushChanges()\n await this.loopback?.close()\n this.loopback = undefined\n // Last: probes kept answering (readiness 503) while the public port drained.\n if (closeServer) await this.closeManagementServer()\n // The adapters are shut down: stop routing reports to them. A reload\n // keeps the same adapters, so it keeps them observing.\n if (closeServer) releaseObservers(this.observers)\n } finally {\n if (timer) clearTimeout(timer)\n this._status.value = 'stopped'\n }\n }\n\n /**\n * The engine-native app instance, typed from the active runtime\n * ({@link ActiveRuntime} — Express by default). Prefer this over\n * {@link getExpressApp}; under a non-Express runtime the type follows the\n * augmented registry.\n */\n getRuntimeApp(): ActiveRuntime['app'] {\n return this.app\n }\n\n /**\n * The active HTTP runtime's identity + capabilities — `name` is `'express'`\n * (default), `'fastify'`, or `'h3'`; `capabilities` reports what the engine\n * supports (render / uploads / connectMiddleware / nativeBodyParsing).\n * Surfaced by DevTools and the VS Code extension so tooling can show which\n * engine the app is running on. Cheap, side-effect free.\n */\n getActiveRuntime(): { name: string; capabilities: RuntimeCapabilities } {\n return { name: this.runtime.name, capabilities: this.runtime.capabilities }\n }\n\n /** @deprecated Use {@link getRuntimeApp}. Returns the engine-native app. */\n getExpressApp(): ActiveRuntime['app'] {\n return this.app\n }\n\n /** Get registered adapters — used by DevToolsAdapter for peer discovery */\n getAdapters(): AppAdapter[] {\n return this.adapters\n }\n\n /**\n * Get registered plugins — used by DevToolsAdapter for topology\n * introspection (architecture.md §23). Read-only; returns the\n * already-sorted plugin list (post-`dependsOn` topo-sort).\n */\n getPlugins(): readonly KickPlugin[] {\n return this.plugins\n }\n\n /**\n * Snapshot of every Context Contributor reachable from this app —\n * walks **four** registration sites: adapters, plugins, modules,\n * and the bootstrap `contributors` option. The devtools Topology\n * tab consumes this for the Contributors panel; tests + adopters\n * can call it for diagnostics.\n *\n * Per-route (method/class-decorator) registrations are NOT included\n * here — they live on the route registry rather than on any of\n * the four collection sites this method walks. A future RPC will\n * surface them separately.\n *\n * Result shape stays minimal — `{ key, source, label, dependsOn }`\n * — so we don't leak `resolve` closures or other internal fields.\n * `source` matches the five-level precedence union from\n * `ContributorSource` (minus `'method'` / `'class'` which require\n * the per-route walk noted above).\n */\n /**\n * Every controller route the app mounted, with its full pattern and the\n * context contributors a request runs, in execution order — decorators\n * included. Devtools serves this per route.\n */\n getRoutes(): readonly MountedRouteInfo[] {\n return this.mountedRouteInfo\n }\n\n getContributors(): ReadonlyArray<{\n key: string\n source: 'method' | 'class' | 'module' | 'adapter' | 'plugin' | 'global'\n label: string\n dependsOn: readonly string[]\n }> {\n const out: Array<{\n key: string\n source: 'method' | 'class' | 'module' | 'adapter' | 'plugin' | 'global'\n label: string\n dependsOn: readonly string[]\n }> = []\n const ingest = (\n list: ReadonlyArray<unknown> | null | undefined,\n source: 'module' | 'adapter' | 'plugin' | 'global',\n label: string,\n ): void => {\n if (!list) return\n for (const reg of list) {\n const r = reg as { key?: unknown; dependsOn?: unknown }\n if (r.key === undefined || r.key === null) continue\n // `key` is typically a string but createToken<T>() yields a\n // branded token object — normalise via tokenName so both\n // surfaces flow through.\n const key = typeof r.key === 'string' ? r.key : tokenName(r.key)\n out.push({\n key,\n source,\n label,\n dependsOn: Array.isArray(r.dependsOn) ? (r.dependsOn as string[]) : [],\n })\n }\n }\n for (const adapter of this.adapters) {\n ingest(adapter.contributors?.(), 'adapter', adapter.name ?? 'adapter')\n }\n for (const plugin of this.plugins) {\n ingest(plugin.contributors?.(), 'plugin', plugin.name ?? 'plugin')\n }\n // Module-level registrations — captured during `setup()` because\n // module instances are not retained on the Application. Walk the\n // snapshot rather than calling `mod.contributors()` here.\n for (const { registration, label } of this._moduleContributors) {\n ingest([registration], 'module', label)\n }\n ingest(this.options.contributors, 'global', 'bootstrap')\n // Decorator-applied contributors (`@LoadTenant` on a class or method) live\n // in controller metadata and only reach the per-route pipelines — read\n // them back from what was mounted, once per decorator site.\n const sites = new Set<string>()\n for (const route of this.mountedRouteInfo) {\n for (const c of route.contributors) {\n if (c.source !== 'class' && c.source !== 'method') continue\n const site = `${c.source}:${c.label ?? `${route.controller}.${route.handler}`}`\n if (sites.has(site)) continue\n sites.add(site)\n out.push({\n key: c.key,\n source: c.source,\n label: c.label ?? `${route.controller}.${route.handler}`,\n dependsOn: c.dependsOn,\n })\n }\n }\n return out\n }\n\n getHttpServer(): KickServer | null {\n return this.httpServer\n }\n\n /**\n * The management listener (`bootstrap({ management })`) — its address, or\n * something to attach to it. `null` without a management port, in dev mode,\n * before `start()` has opened it, and after shutdown has closed it.\n */\n getManagementServer(): http.Server | https.Server | null {\n return this.managementServer\n }\n\n // ── Internal helpers ────────────────────────────────────────────────\n\n /**\n * Decide whether {@link Application} should auto-mount the\n * {@link requestScopeMiddleware} ALS wrapper.\n *\n * Returns `false` when:\n * - `contextStore: 'manual'` was set (caller manages ALS frames), or\n * - the user-supplied `middleware` list already includes a\n * `requestScopeMiddleware()` (detected via the symbol marker stamped\n * in `middleware/request-scope.ts`).\n *\n * Otherwise `true` — preserves the historical default of \"always wrap\n * requests in an ALS frame\" so existing apps see no behavior change.\n */\n private shouldAutoMountRequestScope(): boolean {\n if (this.options.contextStore === 'manual') return false\n\n const userEntries = this.options.middlewares ?? []\n for (const entry of userEntries) {\n const handler = typeof entry === 'function' ? entry : entry.handler\n if (isRequestScopeMiddleware(handler)) return false\n }\n return true\n }\n\n private collectAdapterMiddleware() {\n const result = {\n beforeGlobal: [] as AdapterMiddleware[],\n afterGlobal: [] as AdapterMiddleware[],\n beforeRoutes: [] as AdapterMiddleware[],\n afterRoutes: [] as AdapterMiddleware[],\n }\n\n for (const adapter of this.adapters) {\n const entries = adapter.middleware?.() ?? []\n for (const entry of entries) {\n const phase = entry.phase ?? 'afterGlobal'\n result[phase].push(entry)\n }\n }\n\n return result\n }\n\n private mountMiddlewareList(entries: AdapterMiddleware[]): void {\n for (const entry of entries) {\n if (entry.path === undefined) {\n this.runtime.useConnect(this.app, entry.handler)\n continue\n }\n this.runtime.useConnect(this.app, entry.handler, { path: entry.path })\n }\n }\n\n private mountMiddlewareEntry(entry: MiddlewareEntry): void {\n if (typeof entry === 'function') {\n this.runtime.useConnect(this.app, entry)\n } else {\n this.runtime.useConnect(this.app, entry.handler, { path: entry.path })\n }\n }\n\n /**\n * `GET /_kick/cron/:scheduleId` — how a serverless platform\n * (Vercel crons) runs `@Cron` jobs: `kick build:vercel` emits one cron entry\n * per schedule pointing here. Mounted only in handler mode and only when\n * `CRON_SECRET` is set; the request must carry `Authorization: Bearer\n * $CRON_SECRET` (Vercel sends it). Runs every job on that schedule.\n */\n private mountCronTrigger(): void {\n const secret = process.env.CRON_SECRET\n if (!secret) return\n // Fixed and outside `apiPrefix` (like /health): `kick build:vercel` writes\n // the exact path, and can't see the app's `apiPrefix`.\n const path = '/_kick/cron/:scheduleId'\n this.adapterHttp().route('GET', path, async (ctx) => {\n if (!matchesBearer(ctx.headers.authorization, secret)) {\n throw new HttpException(401, 'Missing or invalid CRON_SECRET bearer token')\n }\n const result = await runCronJobs(\n this.container,\n { scheduleId: ctx.params.scheduleId },\n 'http',\n )\n ctx.json(result, result.failed > 0 ? 500 : 200)\n })\n }\n\n /** Middleware that tracks in-flight requests for graceful draining */\n private requestTrackingMiddleware(): ConnectHandler {\n return (req, res, next) => {\n this._inFlightRequests++\n // Timed only while something observes responses — checked per request,\n // since a diagnostics channel can gain a subscriber at any time.\n const started = hasResponseObservers() ? performance.now() : undefined\n // `finish` means the response went out; a bare `close` means the client\n // gave up first. Only the first is a response to report — on an abort\n // `res.statusCode` still holds its default (200) and would read as a\n // success. Both still leave the in-flight count.\n const onFinish = () => settle(true)\n const onClose = () => settle(false)\n const settle = (finished: boolean) => {\n res.removeListener('finish', onFinish)\n res.removeListener('close', onClose)\n if (finished && started !== undefined) {\n const matched = (req as unknown as Record<symbol, MatchedRoute | undefined>)[ROUTE_SLOT]\n reportResponse({\n method: req.method,\n path: requestPath(req),\n route: matched?.pattern,\n status: res.statusCode,\n durationMs: performance.now() - started,\n requestId: requestIdOf(req),\n })\n }\n this._inFlightRequests--\n // If draining and no more in-flight requests, resolve all waiters\n if (this.isDraining && this._inFlightRequests === 0) {\n for (const resolve of this._drainResolvers) {\n resolve()\n }\n this._drainResolvers = []\n }\n }\n res.on('finish', onFinish)\n res.on('close', onClose)\n next()\n }\n }\n\n /** Mount /health/live and /health/ready endpoints at the root (no API prefix) */\n}\n\n/**\n * One line per owner (controller or adapter): its routes, or — past a few —\n * how many there are under their common prefix, so `/_debug`'s dozens stay one line.\n */\nexport function describeRoutes(routes: readonly MountedRouteInfo[]): string[] {\n const byOwner = new Map<string, MountedRouteInfo[]>()\n for (const route of routes) {\n byOwner.set(route.controller, [...(byOwner.get(route.controller) ?? []), route])\n }\n const width = Math.max(0, ...[...byOwner.keys()].map((owner) => owner.length))\n return [...byOwner].map(([owner, list]) => {\n if (list.length <= 4) {\n return `${owner.padEnd(width)} ${list.map((r) => `${r.method} ${r.pattern}`).join(', ')}`\n }\n const segments = list.map((r) => r.pattern.split('/'))\n const common: string[] = []\n for (let i = 0; segments.every((s) => s[i] !== undefined && s[i] === segments[0]![i]); i++) {\n common.push(segments[0]![i]!)\n }\n return `${owner.padEnd(width)} ${list.length} routes under ${common.join('/') || '/'}`\n })\n}\n\n/** The request path without the query string, on every engine. */\nfunction requestPath(req: { originalUrl?: string; url?: string }): string {\n return (req.originalUrl ?? req.url ?? '').split('?')[0]\n}\n\nfunction requestIdOf(req: {\n requestId?: string\n headers?: Record<string, unknown>\n}): string | undefined {\n const header = req.headers?.['x-request-id']\n return req.requestId ?? (typeof header === 'string' ? header : undefined)\n}\n\n/** The status an error will be answered with, as the default handler decides it. */\nfunction errorStatus(err: any): number {\n if (typeof err?.problem?.status === 'number') return err.problem.status\n if (typeof err?.status === 'number') return err.status\n if (typeof err?.statusCode === 'number') return err.statusCode\n if (err?.name === 'ZodError') return 422\n return 500\n}\n\n/**\n * Report every request error to the observers, then hand it to the real error\n * handler (the default one or `bootstrap({ onError })`) unchanged.\n */\nfunction observeErrors<H extends (err: any, req: any, res: any, next: any) => unknown>(\n handler: H,\n): H {\n return ((err: any, req: any, res: any, next: any) => {\n const matched = req?.[ROUTE_SLOT] as MatchedRoute | undefined\n reportError(err, {\n source: 'request',\n requestId: requestIdOf(req ?? {}),\n method: req?.method,\n path: requestPath(req ?? {}),\n route: matched?.pattern,\n status: errorStatus(err),\n })\n return handler(err, req, res, next)\n }) as H\n}\n"],"mappings":";;;;;;;;;;i9EAoCA,IAAa,wBAAb,cAA6C,KAAM,CACjD,KACA,UAEA,YAAY,KAAiB,UAAmB,CAC9C,MAAM,aAAa,KAAK,SAAS,UAAU,YAAY,KAAK,4BAA4B,EACxF,KAAK,KAAO,0BACZ,KAAK,KAAO,KACZ,KAAK,UAAY,SACnB,CACF,EAQa,qBAAb,cAA0C,KAAM,CAC9C,KACA,QACA,UAEA,YAAY,KAAiB,QAAiB,UAAmB,CAC/D,MACE,WAAW,KAAK,eAAe,QAAQ,iBAAiB,UAAU,aACtD,KAAK,gCACnB,EACA,KAAK,KAAO,uBACZ,KAAK,KAAO,KACZ,KAAK,QAAU,QACf,KAAK,UAAY,SACnB,CACF,EAOa,gBAAb,cAAqC,KAAM,CACzC,KACA,MAEA,YAAY,KAAiB,MAA0B,CACrD,MAAM,YAAY,KAAK,2BAA2B,MAAM,KAAK,KAAK,GAAG,EACrE,KAAK,KAAO,kBACZ,KAAK,KAAO,KACZ,KAAK,MAAQ,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC,CACvC,CACF,EAgBA,SAAgB,UAAmC,MAAqB,KAAsB,CAC5F,IAAM,uBAAS,IAAI,IACnB,IAAK,IAAM,QAAQ,MAAO,CACxB,GAAI,OAAO,IAAI,KAAK,IAAI,EACtB,MAAM,IAAI,wBAAwB,KAAM,KAAK,IAAI,EAEnD,OAAO,IAAI,KAAK,KAAM,IAAI,CAC5B,CAGA,IAAM,yBAAW,IAAI,IAEf,2BAAa,IAAI,IAEvB,IAAK,IAAM,QAAQ,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ACvD,CAEA,SAAS,YAAY,IAGE,CACrB,IAAM,OAAS,IAAI,UAAU,gBAC7B,OAAO,IAAI,YAAc,OAAO,QAAW,SAAW,OAAS,IAAA,GACjE,CAGA,SAAS,YAAY,IAAkB,CAKrC,OAJI,OAAO,KAAK,SAAS,QAAW,SAAiB,IAAI,QAAQ,OAC7D,OAAO,KAAK,QAAW,SAAiB,IAAI,OAC5C,OAAO,KAAK,YAAe,SAAiB,IAAI,WAChD,KAAK,OAAS,WAAmB,IAC9B,GACT,CAMA,SAAS,cACP,QACG,CACH,QAAS,IAAU,IAAU,IAAU,OAAc,CACnD,IAAM,QAAU,MAAM,YAStB,OARA,YAAY,IAAK,CACf,OAAQ,UACR,UAAW,YAAY,KAAO,CAAC,CAAC,EAChC,OAAQ,KAAK,OACb,KAAM,YAAY,KAAO,CAAC,CAAC,EAC3B,MAAO,SAAS,QAChB,OAAQ,YAAY,GAAG,CACzB,CAAC,EACM,QAAQ,IAAK,IAAK,IAAK,IAAI,CACpC,EACF"}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
|
|
2
|
-
import { i as SettingsDeclaration, s as VarOrigin, t as ConfigVar } from "./settings-
|
|
3
|
-
import "./index-
|
|
4
|
-
import { E as RequestContext, K as AdapterFactory, Ot as KickPlugin, Rt as ResponseInfo, U as UrlForArgs, Ut as ConditionOutcome, V as RouteName, a as KickServer, b as RuntimeCapabilities, c as ActiveRuntime, d as HttpRuntime, h as RouteEntry, kt as ModuleRegistry, m as RouteContributor, r as AppAdapter, x as RuntimeResponse, xt as ModuleFactory } from "./adapter-
|
|
2
|
+
import { i as SettingsDeclaration, s as VarOrigin, t as ConfigVar } from "./settings-BFQisfqG.mjs";
|
|
3
|
+
import "./index-CNBYZDto.mjs";
|
|
4
|
+
import { E as RequestContext, K as AdapterFactory, Ot as KickPlugin, Rt as ResponseInfo, U as UrlForArgs, Ut as ConditionOutcome, V as RouteName, a as KickServer, b as RuntimeCapabilities, c as ActiveRuntime, d as HttpRuntime, h as RouteEntry, kt as ModuleRegistry, m as RouteContributor, r as AppAdapter, x as RuntimeResponse, xt as ModuleFactory } from "./adapter-DLjn8q0c.mjs";
|
|
5
5
|
import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse } from "./connect-BlIamapT.mjs";
|
|
6
6
|
import { t as Container } from "./container-4iJdDkRH.mjs";
|
|
7
7
|
import { p as RouteFlags, s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
|
|
8
|
-
import { C as MetaValue, c as ContextDecorator, h as DepValue, m as ContributorRegistrations, r as AppModuleEntry, u as ContextDecoratorSpec, x as ContextMetaKey } from "./app-module-
|
|
9
|
-
import { l as PlatformContext, m as Reply } from "./kv-stores-
|
|
10
|
-
import { t as ComputedRef } from "./reactivity-
|
|
8
|
+
import { C as MetaValue, c as ContextDecorator, h as DepValue, m as ContributorRegistrations, r as AppModuleEntry, u as ContextDecoratorSpec, x as ContextMetaKey } from "./app-module-Bk3glnPP.mjs";
|
|
9
|
+
import { l as PlatformContext, m as Reply } from "./kv-stores-DJBnGQsJ.mjs";
|
|
10
|
+
import { t as ComputedRef } from "./reactivity-DZrc3Yhu.mjs";
|
|
11
11
|
import { t as ValidationErrorFactory } from "./validate-D4Poe2EE.mjs";
|
|
12
12
|
import { t as AllowedHostsOptions } from "./allowed-hosts-BpKwviq5.mjs";
|
|
13
|
-
import { t as BuildRoutesOptions } from "./router-builder-
|
|
14
|
-
import "./error-handler-
|
|
15
|
-
import "./csrf-
|
|
16
|
-
import "./upload-
|
|
13
|
+
import { t as BuildRoutesOptions } from "./router-builder-CPJHwoL1.mjs";
|
|
14
|
+
import "./error-handler-BrihKETE.mjs";
|
|
15
|
+
import "./csrf-w5bc-PGs.mjs";
|
|
16
|
+
import "./upload-DtQ1pdQw.mjs";
|
|
17
17
|
import http, { IncomingMessage, ServerResponse } from "node:http";
|
|
18
18
|
import https from "node:https";
|
|
19
19
|
import tls from "node:tls";
|
|
@@ -448,6 +448,39 @@ declare class StartupCheckError extends Error {
|
|
|
448
448
|
constructor(messages: CheckMessage[]);
|
|
449
449
|
}
|
|
450
450
|
//#endregion
|
|
451
|
+
//#region src/http/cache-response.d.ts
|
|
452
|
+
interface CacheResponseOptions {
|
|
453
|
+
/** Seconds a stored response is served as fresh. */
|
|
454
|
+
maxAge: number;
|
|
455
|
+
/**
|
|
456
|
+
* Seconds past `maxAge` a stale response is still served, while one request
|
|
457
|
+
* rebuilds it in the background. Default 0: past `maxAge` the next request waits.
|
|
458
|
+
*/
|
|
459
|
+
swr?: number;
|
|
460
|
+
/**
|
|
461
|
+
* Request headers that select a different response — `accept-language`, or
|
|
462
|
+
* `authorization` for per-user responses. Their values are part of the key.
|
|
463
|
+
* Every header the handler reads belongs here.
|
|
464
|
+
*
|
|
465
|
+
* A request that identifies its caller — `authorization`, `proxy-authorization`,
|
|
466
|
+
* `x-api-key`, a `cookie`, or a signed-in `ctx.user` — skips the cache unless
|
|
467
|
+
* that header is listed here: under a shared key, one user's response would
|
|
468
|
+
* reach another.
|
|
469
|
+
*/
|
|
470
|
+
varies?: string[];
|
|
471
|
+
/**
|
|
472
|
+
* A string is the key prefix — `@CacheEvict(prefix)` clears the route's
|
|
473
|
+
* entries. Default: `kick:response:Controller.method`.
|
|
474
|
+
*
|
|
475
|
+
* A function decides the key per request, from the whole context — params,
|
|
476
|
+
* `ctx.get('tenant')`, `ctx.user`. It owns the decision: the caller check
|
|
477
|
+
* above doesn't apply, so include the user or tenant when the response
|
|
478
|
+
* depends on them. Return `null` to skip the cache for that request.
|
|
479
|
+
*/
|
|
480
|
+
key?: string | ((ctx: RequestContext) => string | null);
|
|
481
|
+
}
|
|
482
|
+
declare function CacheResponse(options: CacheResponseOptions): MethodDecorator;
|
|
483
|
+
//#endregion
|
|
451
484
|
//#region src/http/metrics.d.ts
|
|
452
485
|
interface MetricsOptions {
|
|
453
486
|
/** Where to serve the metrics. Default `/metrics`. */
|
|
@@ -1219,8 +1252,12 @@ interface ShutdownOptions {
|
|
|
1219
1252
|
interface ServerOptions {
|
|
1220
1253
|
/** TLS credentials and options (`key`, `cert`, `ca`, `pfx`, `passphrase`, …). */
|
|
1221
1254
|
tls?: tls.SecureContextOptions & tls.TlsOptions;
|
|
1222
|
-
/**
|
|
1223
|
-
|
|
1255
|
+
/**
|
|
1256
|
+
* `true`: HTTP/2 with HTTP/1.1 fallback; requires `tls`. `'h2c'`: cleartext
|
|
1257
|
+
* HTTP/2 only, no `tls` and no HTTP/1.1 — for a proxy or mesh that speaks
|
|
1258
|
+
* HTTP/2 to the app. Both need an HTTP/2-capable runtime.
|
|
1259
|
+
*/
|
|
1260
|
+
http2?: boolean | 'h2c';
|
|
1224
1261
|
/**
|
|
1225
1262
|
* Milliseconds an idle keep-alive connection stays open. Default 65000.
|
|
1226
1263
|
* Keep it ABOVE your load balancer's idle timeout (AWS ALB: 60s): when the
|
|
@@ -1311,6 +1348,9 @@ interface ApplicationOptions {
|
|
|
1311
1348
|
* HTTP/1.1 clients and WebSocket upgrades keep working. Fastify and h3
|
|
1312
1349
|
* only; Express fails at boot with KICK007, and `http2` without `tls`
|
|
1313
1350
|
* with KICK008.
|
|
1351
|
+
* - `{ http2: 'h2c' }` — cleartext HTTP/2 with no HTTP/1.1 fallback, for a
|
|
1352
|
+
* proxy or service mesh that speaks HTTP/2 to the app (native gRPC behind
|
|
1353
|
+
* Envoy or Linkerd). Fastify and h3 only.
|
|
1314
1354
|
*
|
|
1315
1355
|
* Ignored in dev mode, where Vite owns the server. Most deploys terminate
|
|
1316
1356
|
* TLS / HTTP/2 at a proxy and need none of this.
|
|
@@ -2065,5 +2105,5 @@ declare class Application {
|
|
|
2065
2105
|
*/
|
|
2066
2106
|
declare function describeRoutes(routes: readonly MountedRouteInfo[]): string[];
|
|
2067
2107
|
//#endregion
|
|
2068
|
-
export { createHandler as $, requestScopeMiddleware as A,
|
|
2069
|
-
//# sourceMappingURL=application-
|
|
2108
|
+
export { createHandler as $, requestScopeMiddleware as A, DuplicateMountNameError as At, SignerOptions as B, CircuitBreaker as Bt, ViewAdapterOptions as C, offerRoutePolicy as Ct, TraceContextOptions as D, GroupAssetKeysResult as Dt, TraceContext as E, GroupAssetKeysOptions as Et, buildRoutes as F, mountSort as Ft, PasswordHashOptions as G, FormatKickErrorOptions as Gt, createSigner as H, CircuitBreakerState as Ht, expressRuntime as I, ContributorCycleError as It, verifyPassword as J, formatKickError as Jt, VerifyPasswordOptions as K, KickError as Kt, materializeRouter as L, DuplicateContributorError as Lt, getRequestStore as M, MountCycleError as Mt, getRequestValue as N, MountKind as Nt, parseTraceparent as O, groupAssetKeys as Ot, requestStore as P, MountSortItem as Pt, KickHandler as Q, SignedCheck as R, MissingContextValueError as Rt, ViewAdapter as S, bindRoutePolicy as St, TRACEPARENT_HEADER as T, AssetKeyStrategy as Tt, LegacyHasher as U, CircuitBreakerStats as Ut, VerifyOptions as V, CircuitBreakerOptions as Vt, PasswordCheck as W, CircuitOpenError as Wt, ClusterOptions as X, defineHttpContextDecorator as Y, isClusterPrimary as Z, HealthProbe as _, StartupCheckError as _t, ConfigDescription as a, CRON_WORKER_ENV as at, SpaAdapterOptions as b, StartupTimelineSnapshot as bt, MiddlewareEntry as c, RAW_BODY as ct, ShutdownOptions as d, metricsAdapter as dt, bootstrap as et, describeRoutes as f, CacheResponse as ft, HealthModuleConfig as g, StartupCheck as gt, HealthController as h, CheckMessage as ht, ApplicationOptions as i, RESPONSE_CHANNEL as it, RequestStore as j, MissingMountDepError as jt, traceContext as k, stripExt as kt, MountedRouteInfo as l, MetricsOptions as lt, HealthCheckResult as m, CheckContext as mt, AppStatus as n, HANDLER_CHANNEL as nt, ConfigOrigins as o, CronAdapterOptions as ot, HEALTH_PROBE as p, CacheResponseOptions as pt, hashPassword as q, KickErrorInit as qt, Application as r, HandlerTraceContext as rt, ManagementOptions as s, KickCronAdapter as st, APPLICATION as t, ERROR_CHANNEL as tt, ServerOptions as u, RequestHistogram as ut, healthModule as v, defineCheck as vt, viewDirs as w, AssetKeyPair as wt, resolveClientDir as x, RoutePolicyTable as xt, SpaAdapter as y, StartupStep as yt, Signer as z, MissingContributorError as zt };
|
|
2109
|
+
//# sourceMappingURL=application-w0Xnc35j.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"application-w0Xnc35j.d.mts","names":["_$__0.AdapterFactory","Request","Response","NextFunction","Request","Response","NextFunction","_$_____0.AdapterFactory","_$_____0.AdapterFactory","_$__reply0.Reply","_$__0.ModuleFactory"],"sources":["../src/core/kick-error.ts","../src/core/circuit-breaker.ts","../src/core/context-errors.ts","../src/core/mount-sort.ts","../src/core/asset-keys.ts","../src/core/route-policy.ts","../src/http/startup-timeline.ts","../src/http/startup-checks.ts","../src/http/cache-response.ts","../src/http/metrics.ts","../src/http/body-policy.ts","../src/http/cron-adapter.ts","../src/http/tracing.ts","../src/http/bootstrap.ts","../src/http/handler.ts","../src/http/cluster.ts","../src/http/define-http-context-decorator.ts","../src/core/password.ts","../src/core/signing.ts","../src/http/runtimes/express-lazy.ts","../src/http/request-store.ts","../src/http/middleware/request-scope.ts","../src/http/middleware/trace-context.ts","../src/http/middleware/views.ts","../src/http/middleware/spa.ts","../src/http/health-module.ts","../src/http/application.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAiBiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;cAGC,kBAAkB;WACb;WACA;WACA;WACA;WACA;WACA,UAAU;EAE1B,YAAY,MAAM;;UAiDH;;;;;;EAMf;;;;;;;iBAQc,gBACd,KAAK,gBAAgB,WACrB,UAAS;;;;;;;;;;;;;;;;;;;;KCvFC;UAEK;;EAEf;;EAEA;;EAEA;;UAGe;EACf;EACA;EACA,OAAO;EACP,cAAc;;;;;cAMH,yBAAyB;WACR;EAA5B,YAA4B;;cAMjB;WAaO;UAZV;UACA;UACA;UACA;UACA;UACA;mBAES;mBACA;mBACA;EAEjB,YACkB,cAChB,SAAS;;;;;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