@forinda/kickjs 8.6.0 → 9.0.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/README.md +27 -164
- package/dist/{adapter-2bnoYEPX.d.mts → adapter-DhjoIYVI.d.mts} +122 -106
- package/dist/adapter-DhjoIYVI.d.mts.map +1 -0
- package/dist/application-BnFA6J97.mjs +12 -0
- package/dist/application-BnFA6J97.mjs.map +1 -0
- package/dist/{application-_QOiAVx2.d.mts → application-DqD58rhF.d.mts} +104 -15
- package/dist/application-DqD58rhF.d.mts.map +1 -0
- package/dist/bootstrap-K1PcxSTg.mjs +12 -0
- package/dist/bootstrap-K1PcxSTg.mjs.map +1 -0
- package/dist/cache-C0qL0NSD.d.mts.map +1 -1
- package/dist/{client-ip-DF_smNX7.mjs → client-ip-DAnYuS54.mjs} +2 -2
- package/dist/{client-ip-DF_smNX7.mjs.map → client-ip-DAnYuS54.mjs.map} +1 -1
- package/dist/config/index.d.mts +2 -2
- package/dist/config/index.mjs +2 -2
- package/dist/config-16yw-Mxk.mjs +12 -0
- package/dist/config-16yw-Mxk.mjs.map +1 -0
- package/dist/container-Dw45sa0Y.mjs +132 -0
- package/dist/container-Dw45sa0Y.mjs.map +1 -0
- package/dist/context-DlIdXA6I.mjs +12 -0
- package/dist/context-DlIdXA6I.mjs.map +1 -0
- package/dist/{context-errors-Ch0DuUQo.mjs → context-errors-BqOFD7UE.mjs} +2 -2
- package/dist/{context-errors-Ch0DuUQo.mjs.map → context-errors-BqOFD7UE.mjs.map} +1 -1
- package/dist/{contributor-runner-DujKZy4N.mjs → contributor-runner-DLvBA96K.mjs} +3 -3
- package/dist/{contributor-runner-DujKZy4N.mjs.map → contributor-runner-DLvBA96K.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +2 -2
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +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.d.mts +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/cron.mjs.map +1 -1
- 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.mjs +1 -1
- package/dist/core-CCwlN0Gn.mjs +12 -0
- package/dist/{core-y8QbzHM5.mjs.map → core-CCwlN0Gn.mjs.map} +1 -1
- package/dist/cron-BTGytNg-.d.mts +122 -0
- package/dist/cron-BTGytNg-.d.mts.map +1 -0
- package/dist/{csrf-RP5hgc0c.mjs → csrf-B8CGeOlP.mjs} +3 -3
- package/dist/csrf-B8CGeOlP.mjs.map +1 -0
- package/dist/{csrf-C4MwaMp4.d.mts → csrf-COFjRrUz.d.mts} +2 -2
- package/dist/{csrf-C4MwaMp4.d.mts.map → csrf-COFjRrUz.d.mts.map} +1 -1
- package/dist/{decorate-D85rEnU-.mjs → decorate-CahyjuWW.mjs} +1 -1
- package/dist/{decorators-mg0qJ6Qc.d.mts → decorators-DOcWsXci.d.mts} +2 -2
- package/dist/{decorators-mg0qJ6Qc.d.mts.map → decorators-DOcWsXci.d.mts.map} +1 -1
- package/dist/{define-adapter-C1Db6xfO.mjs → define-adapter-Ckc2P-wH.mjs} +2 -2
- package/dist/{define-adapter-C1Db6xfO.mjs.map → define-adapter-Ckc2P-wH.mjs.map} +1 -1
- package/dist/{disposables-CEAxve3A.mjs → disposables-DnvT8DXr.mjs} +2 -2
- package/dist/{disposables-CEAxve3A.mjs.map → disposables-DnvT8DXr.mjs.map} +1 -1
- package/dist/{env-BelmDj19.mjs → env-DMAdjj8Z.mjs} +4 -4
- package/dist/env-DMAdjj8Z.mjs.map +1 -0
- package/dist/{error-handler-C1uWVGVY.d.mts → error-handler-DiueQHes.d.mts} +2 -2
- package/dist/{error-handler-C1uWVGVY.d.mts.map → error-handler-DiueQHes.d.mts.map} +1 -1
- package/dist/{handler-DHlakr0v.mjs → handler-2CbWK63p.mjs} +3 -3
- package/dist/handler-2CbWK63p.mjs.map +1 -0
- package/dist/http/application.d.mts +2 -2
- 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/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/error-handler.mjs.map +1 -1
- 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.d.mts +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +3 -3
- 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/fastify.d.mts +1 -1
- 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.d.mts +1 -1
- package/dist/http/runtimes/h3-web.d.mts.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs.map +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -6
- package/dist/http/runtimes/h3.d.mts.map +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-Btz1W0X5.d.mts → index-CDn-p3tq.d.mts} +27 -18
- package/dist/index-CDn-p3tq.d.mts.map +1 -0
- package/dist/index.d.mts +12 -12
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/jobs-C8_ESbx0.mjs +12 -0
- package/dist/jobs-C8_ESbx0.mjs.map +1 -0
- package/dist/{kv-stores-DUFcps01.mjs → kv-stores-BhUmirED.mjs} +3 -3
- package/dist/{kv-stores-DUFcps01.mjs.map → kv-stores-BhUmirED.mjs.map} +1 -1
- package/dist/{kv-stores-Dx5RvIaP.d.mts → kv-stores-CetFF9N_.d.mts} +135 -5
- package/dist/kv-stores-CetFF9N_.d.mts.map +1 -0
- package/dist/{metadata-B8_KXybT.mjs → metadata-BQG1MmqL.mjs} +2 -2
- package/dist/{metadata-B8_KXybT.mjs.map → metadata-BQG1MmqL.mjs.map} +1 -1
- package/dist/{module-registry-BFrJ1PQ4.mjs → module-registry-BXnvRtH9.mjs} +2 -2
- package/dist/{module-registry-BFrJ1PQ4.mjs.map → module-registry-BXnvRtH9.mjs.map} +1 -1
- package/dist/observers-BI8H_g45.mjs +12 -0
- package/dist/observers-BI8H_g45.mjs.map +1 -0
- package/dist/{query-CC7o6I5K.mjs → query-CRTeiKUv.mjs} +2 -2
- package/dist/{query-CC7o6I5K.mjs.map → query-CRTeiKUv.mjs.map} +1 -1
- package/dist/{respond-B-EDymxF.mjs → respond-BAxhPjRj.mjs} +2 -2
- package/dist/{respond-B-EDymxF.mjs.map → respond-BAxhPjRj.mjs.map} +1 -1
- package/dist/route-flag-B1lQht6v.d.mts.map +1 -1
- package/dist/{route-flag-B4sNP7zH.mjs → route-flag-GipNvQ4O.mjs} +3 -3
- package/dist/route-flag-GipNvQ4O.mjs.map +1 -0
- package/dist/{route-policy-CDlMbl1b.mjs → route-policy-DtGR4sar.mjs} +2 -2
- package/dist/route-policy-DtGR4sar.mjs.map +1 -0
- package/dist/{router-builder-C6gmK0nZ.d.mts → router-builder-BSBSYgYW.d.mts} +3 -3
- package/dist/{router-builder-C6gmK0nZ.d.mts.map → router-builder-BSBSYgYW.d.mts.map} +1 -1
- package/dist/{router-builder-cTsA2XtO.mjs → router-builder-C2nnS0VJ.mjs} +3 -3
- package/dist/{router-builder-cTsA2XtO.mjs.map → router-builder-C2nnS0VJ.mjs.map} +1 -1
- package/dist/{runtime-C-7Yhs7a.mjs → runtime-DGzigyO2.mjs} +3 -3
- package/dist/runtime-DGzigyO2.mjs.map +1 -0
- package/dist/{session-BHgRyfqZ.d.mts → session-4Tb6q0Ny.d.mts} +11 -1
- package/dist/session-4Tb6q0Ny.d.mts.map +1 -0
- package/dist/{upload-TW2ZuECF.d.mts → upload-DjhnyHHm.d.mts} +3 -15
- package/dist/{upload-TW2ZuECF.d.mts.map → upload-DjhnyHHm.d.mts.map} +1 -1
- package/dist/{upload-config-CoE6BzM4.mjs → upload-config-CcoZp7xA.mjs} +2 -2
- package/dist/{upload-config-CoE6BzM4.mjs.map → upload-config-CcoZp7xA.mjs.map} +1 -1
- package/dist/web.d.mts +39 -7
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +15 -10
- package/dist/adapter-2bnoYEPX.d.mts.map +0 -1
- package/dist/application-DZiG1QCw.mjs +0 -12
- package/dist/application-DZiG1QCw.mjs.map +0 -1
- package/dist/application-_QOiAVx2.d.mts.map +0 -1
- package/dist/bootstrap-BEbka3UV.mjs +0 -12
- package/dist/bootstrap-BEbka3UV.mjs.map +0 -1
- package/dist/config-CIOXZmLS.mjs +0 -12
- package/dist/config-CIOXZmLS.mjs.map +0 -1
- package/dist/container-DF8FRoY8.mjs +0 -117
- package/dist/container-DF8FRoY8.mjs.map +0 -1
- package/dist/context-BTqeZH1A.mjs +0 -12
- package/dist/context-BTqeZH1A.mjs.map +0 -1
- package/dist/core-y8QbzHM5.mjs +0 -12
- package/dist/cron-DOOtTY4q.d.mts +0 -30
- package/dist/cron-DOOtTY4q.d.mts.map +0 -1
- package/dist/csrf-RP5hgc0c.mjs.map +0 -1
- package/dist/env-BelmDj19.mjs.map +0 -1
- package/dist/handler-DHlakr0v.mjs.map +0 -1
- package/dist/index-Btz1W0X5.d.mts.map +0 -1
- package/dist/kv-stores-Dx5RvIaP.d.mts.map +0 -1
- package/dist/route-flag-B4sNP7zH.mjs.map +0 -1
- package/dist/route-policy-CDlMbl1b.mjs.map +0 -1
- package/dist/runtime-C-7Yhs7a.mjs.map +0 -1
- package/dist/session-BHgRyfqZ.d.mts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"application-DZiG1QCw.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/mount-sort.ts","../src/http/health-module.ts","../src/http/runtimes/express.ts","../src/http/loopback.ts","../src/http/application.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n","/**\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 * 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}\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 /** 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\n@Controller()\nexport class HealthController {\n constructor(private readonly probe: HealthProbe) {}\n\n /** Liveness: is the process up and not shutting down. */\n @Get('/live')\n live() {\n return this.probe.isDraining()\n ? reply(503, { status: 'draining', uptime: process.uptime() })\n : reply(200, { status: 'ok', uptime: process.uptime() })\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 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","// The default Express runtime — the M1 reference implementation of HttpRuntime.\n//\n// Its route materializer rebuilds the exact `(req, res, next)` handler chain\n// the old `buildRoutes()` produced, so swapping decorators → RouteTable →\n// runtime is behavior-neutral under Express. `buildRoutes()` (the public,\n// Router-returning API) now lives here as a thin shim over `buildRouteTable()`\n// + this materializer.\n\nimport express, {\n Router,\n type Express,\n type Request,\n type Response,\n type NextFunction,\n type RequestHandler,\n} from 'express'\n\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\nimport { RequestContext } from '../context'\nimport { applyHandlerResult } from '../reply'\nimport { validate } from '../middleware/validate'\nimport { publishMatchedRoute } from '../runtime'\nimport { buildUploadMiddleware } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\n\n/**\n * Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.\n * Reproduces the legacy handler ordering precisely: validation → upload →\n * `(ctx, next)` middleware → contributor runner → terminal handler, with\n * `beforeValidation` contributors ahead of validation. Each step\n * constructs its own `RequestContext` over the same `req`/`res` — request-scoped\n * state lives in the AsyncLocalStorage store, not on the ctx instance, so the\n * per-step instances share state exactly as before.\n */\nexport function materializeRouter(entries: RouteEntry[]): Router {\n const router = Router()\n\n for (const entry of entries) {\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n const handlers: RequestHandler[] = []\n\n // Publish the matched route first, so every later step — validation,\n // upload, middleware, contributors, handler — reads the same `ctx.route`.\n handlers.push((req: Request, _res: Response, next: NextFunction) => {\n publishMatchedRoute(req, entry)\n next()\n })\n\n // Context Contributor pipeline (#107) — runs, then advances the chain\n // unless a contributor already answered.\n const contributorStep =\n (run: NonNullable<RouteEntry['contributorRunner']>): RequestHandler =>\n async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n await run(ctx)\n if (!res.headersSent) next()\n } catch (err) {\n next(err)\n }\n }\n\n // `beforeValidation` contributors (#677) — an auth rejection answers 401\n // before a malformed body could answer 422.\n if (entry.earlyContributorRunner) {\n handlers.push(contributorStep(entry.earlyContributorRunner))\n }\n\n // Validation middleware (shared with the standalone validate() export).\n if (entry.meta.validation) {\n handlers.push(validate(entry.meta.validation))\n }\n\n // @FileUpload — auto-attach upload middleware from metadata.\n if (entry.meta.upload) {\n handlers.push(buildUploadMiddleware(entry.meta.upload))\n }\n\n // Class + method middleware — wrapped as Express middleware with error catching.\n for (const mw of entry.middlewares) {\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n Promise.resolve(mw(ctx, next)).catch(next)\n })\n }\n\n if (entry.contributorRunner) {\n handlers.push(contributorStep(entry.contributorRunner))\n }\n\n // Terminal handler.\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send the returned payload\n // when the handler wrote nothing. `undefined` keeps prior behavior.\n if (!res.headersSent) applyHandlerResult(ctx, result)\n } catch (err) {\n next(err)\n }\n })\n ;(router as any)[method](entry.path, ...handlers)\n }\n\n return router\n}\n\n/**\n * Build an Express Router from a controller class decorated with @Get, @Post,\n * etc. The public, back-compatible entry point: a thin shim over\n * {@link buildRouteTable} + {@link materializeRouter}. Returns an\n * `express.Router` exactly as before — modules pass it to `app.use(path, router)`.\n *\n * @see buildRouteTable for the engine-neutral route-table form.\n */\nexport function buildRoutes(controllerClass: any, options: BuildRoutesOptions = {}): Router {\n return materializeRouter(buildRouteTable(controllerClass, options))\n}\n\n/**\n * The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;\n * apps that pass no `runtime` get this and behave exactly as before.\n */\nexport function expressRuntime(): HttpRuntime<Express> {\n return {\n name: 'express',\n\n createApp(options: RuntimeAppOptions = {}): Express {\n const app = express()\n // Engine hardening + config the Application used to apply directly.\n app.disable('x-powered-by')\n app.set('trust proxy', options.trustProxy ?? false)\n return app\n },\n\n nodeHandler(app) {\n return (req, res, next) => {\n if (next) {\n ;(app as any)(req, res, next)\n } else {\n ;(app as any)(req, res)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n app.use(mountPath, materializeRouter(routes))\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts: UseConnectOptions = {}) {\n if (opts.path !== undefined) {\n ;(app as any).use(opts.path, mw)\n } else {\n ;(app as any).use(mw)\n }\n },\n\n serveStatic(app, prefix, dir) {\n app.use(prefix, express.static(dir))\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n capabilities: {\n render: true,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: false,\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, Fastify,\n * h3 v1): 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 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\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\n const server = () => {\n started ??= new Promise<{ origin: string; server: http.Server }>((resolve, reject) => {\n const instance = http.createServer((req, res) => handle(req, res))\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\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 express, { type Express, type RequestHandler } from 'express'\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 AdapterMiddleware,\n type ContributorRegistrations,\n type KickPlugin,\n type ModuleRegistry,\n type RouteDefinition,\n type SourcedRegistration,\n mountSort,\n MutableModuleRegistry,\n} from '../core'\nimport { moduleRouteMissingControllerError } 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 { EXPRESS_JSON_TYPES, rejectUnsupportedBody } from './body-policy'\nimport { requestId } from './middleware/request-id'\nimport { notFoundHandler, errorHandler, type MountedRoute } from './middleware/error-handler'\nimport { requestScopeMiddleware, isRequestScopeMiddleware } from './middleware/request-scope'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './router-builder'\nimport { HEALTH_PROBE, healthModule, type HealthModuleConfig } from './health-module'\nimport { expressRuntime } from './runtimes/express'\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\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 = RequestHandler | { path: string; handler: RequestHandler }\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\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 /** 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(), express.json({ limit: '100kb' })\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 /** Express `trust proxy` setting */\n trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean)\n /** Maximum JSON body size (only used when middleware is not provided) */\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 * 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 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 * 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}\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\nexport class Application {\n private app: Express\n /** The HTTP engine driver. Defaults to {@link expressRuntime}. */\n private readonly runtime: HttpRuntime\n private container: Container\n private httpServer: http.Server | null = null\n /** Forwarding server behind {@link fetch} on Node-based runtimes. */\n private loopback?: Loopback\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 _draining = false\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 this.runtime = options.runtime ?? expressRuntime()\n // `this.app` is the engine-native app; typed Express here (the default) for\n // the legacy escape hatches. Under another runtime it holds that engine's\n // app — `getRuntimeApp()` / `AdapterContext.app` expose it via ActiveRuntime.\n this.app = this.runtime.createApp({ trustProxy: options.trustProxy }) as Express\n this.container = Container.getInstance()\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(namedAdapters, 'adapter')\n // Wire the request store provider so Container can resolve REQUEST-scoped deps\n Container._requestStoreProvider = () => requestStore.getStore() ?? null\n }\n\n /** Whether the application is currently draining in-flight requests */\n get isDraining(): boolean {\n return this._draining\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 (the h3 v2 runtime) are called directly.\n * Node-based runtimes (Express, Fastify, h3 v1) 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 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 handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void {\n const handler = this.runtime.nodeHandler(this.app)\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): AdapterContext {\n const env = process.env.NODE_ENV ?? 'development'\n return {\n http: this.adapterHttp(),\n app: this.app,\n fetch: (request) => this.fetch(request),\n container: this.container,\n server,\n env,\n isProduction: env === 'production',\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(): AdapterHttp {\n return {\n route: (method, path, handler) => {\n const entry: RouteEntry = {\n method,\n path,\n middlewares: [],\n contributorRunner: null,\n handler,\n meta: {},\n }\n this.runtime.mountRoutes(this.app, [{ mountPath: '/', routes: [entry] }])\n },\n mount: (prefix, routes) => {\n this.runtime.mountRoutes(this.app, [{ mountPath: prefix, routes }])\n },\n serveStatic: (prefix, dir) => {\n this.runtime.serveStatic(this.app, prefix, dir)\n },\n use: (mw, opts) => {\n this.runtime.useConnect(this.app, mw, opts)\n },\n }\n }\n\n /** Call an adapter hook, awaiting async hooks and catching errors */\n private async callHook(\n hook: ((ctx: AdapterContext) => void | Promise<void>) | undefined,\n ctx: AdapterContext,\n ): Promise<void> {\n if (!hook) return\n try {\n const result = hook(ctx)\n if (result && typeof (result as Promise<void>).then === 'function') {\n await result\n }\n } catch (err) {\n log.error(err, 'Adapter hook failed')\n }\n }\n\n async setup(): Promise<void> {\n log.debug('Bootstrapping application...')\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 const ctx = this.adapterCtx()\n\n // ── 1. Adapter beforeMount hooks ──────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(adapter.beforeMount?.bind(adapter), ctx)\n }\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\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 ?? '1mb'\n // EXPRESS_JSON_TYPES, not the default: `express.json()` matches the\n // exact string `application/json`, so `application/merge-patch+json`\n // arrived unparsed while Fastify answered 415 and h3 parsed it (#590).\n this.runtime.useConnect(this.app, express.json({ limit, type: [...EXPRESS_JSON_TYPES] }))\n // Forms and text were parsed by h3 and rejected by Fastify; on Express\n // they reached the handler as `undefined`, because the engine parsed\n // only what its middleware list happened to cover.\n this.runtime.useConnect(this.app, express.urlencoded({ extended: true, limit }))\n this.runtime.useConnect(this.app, express.text({ limit, type: 'text/*' }))\n // After the parsers: Express leaves an unmatched type as `undefined`,\n // which is indistinguishable from \"no body sent\". This restores the\n // difference so an unsupported type is answered rather than ignored.\n this.runtime.useConnect(this.app, rejectUnsupportedBody())\n }\n }\n\n // ── 5. Adapter middleware: afterGlobal ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterGlobal)\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 = new MutableModuleRegistry()\n for (const plugin of this.plugins) {\n for (const m of plugin.modules?.() ?? []) moduleRegistry.mount(m)\n plugin.setup?.(moduleRegistry)\n }\n for (const m of this.options.modules) moduleRegistry.mount(m)\n this.options.setup?.(moduleRegistry)\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._draining,\n checks: async () => {\n const withCheck = this.adapters.filter((a) => a.onHealthCheck)\n const settled = await Promise.allSettled(withCheck.map((a) => a.onHealthCheck!()))\n return settled.map((c, i) =>\n c.status === 'fulfilled'\n ? c.value\n : { name: withCheck[i].name ?? 'unknown', status: 'down' as const },\n )\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((entry) => {\n const mod: AppModule = toAppModule(entry)\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 return mod\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 // ── 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 }> = []\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\n for (const mod of modules) {\n // Prefer the declared `name` field (set by `defineModule({ name: 'X', ... })`)\n // over `constructor.name`. Factory-built modules are plain objects whose\n // constructor is `Object` — falling straight to `constructor.name` would\n // degrade every label in the DevTools Contributors table to \"Object\".\n const declaredName = (mod as { name?: unknown }).name\n const ctorName = mod.constructor?.name\n const moduleLabel =\n typeof declaredName === 'string' && declaredName.length > 0\n ? declaredName\n : ctorName && ctorName !== 'Object'\n ? ctorName\n : 'module'\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 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 mountedPaths.push({ method: entry.method, path: fullPath })\n this.routePolicy.add(entry.method, fullPath, entry.meta.flags)\n }\n this.runtime.mountRoutes(this.app, [{ mountPath, routes: routeTable }])\n } else {\n throw moduleRouteMissingControllerError(mountPath)\n }\n\n // Notify adapters (e.g. SwaggerAdapter for OpenAPI spec generation)\n if (route.controller) {\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 if (shouldLogRoutes) {\n mountedRoutes.push({ controller: route.controller, mountPath })\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 } 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 log.info(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`)\n }\n\n log.info(` Total: ${totalRoutes} routes`)\n }\n\n // ── 9. Adapter middleware: afterRoutes ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterRoutes)\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(adapter.beforeStart?.bind(adapter), ctx)\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 this.runtime.setNotFound(this.app, this.options.onNotFound ?? notFoundHandler(mountedPaths))\n this.runtime.setErrorHandler(this.app, this.options.onError ?? errorHandler())\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.setup()\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 }\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.setup()\n\n const g = globalThis as any\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!)\n await this.callHook(adapter.afterStart?.bind(adapter), ctx)\n }\n\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\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 = http.createServer(this.runtime.nodeHandler(this.app))\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 // 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 log.info(`Server running on http://localhost:${port}`)\n\n for (const adapter of this.adapters) {\n const afterCtx = this.adapterCtx(this.httpServer!)\n await this.callHook(adapter.afterStart?.bind(adapter), afterCtx)\n }\n\n // Plugin onReady hooks\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n\n resolve()\n } catch (err) {\n reject(err)\n }\n })\n })\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 // 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.runtime.createApp({ trustProxy: this.options.trustProxy }) as Express\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 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._draining = true\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 }\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 } else {\n log.debug('All in-flight requests completed')\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 ])\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 } finally {\n if (timer) clearTimeout(timer)\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(): Express {\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 getContributors(): ReadonlyArray<{\n key: string\n source: 'module' | 'adapter' | 'plugin' | 'global'\n label: string\n dependsOn: readonly string[]\n }> {\n const out: Array<{\n key: string\n source: '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 return out\n }\n\n getHttpServer(): http.Server | null {\n return this.httpServer\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 /** Middleware that tracks in-flight requests for graceful draining */\n private requestTrackingMiddleware(): RequestHandler {\n return (_req, res, next) => {\n this._inFlightRequests++\n const onFinish = () => {\n res.removeListener('finish', onFinish)\n res.removeListener('close', onFinish)\n this._inFlightRequests--\n // If draining and no more in-flight requests, resolve all waiters\n if (this._draining && 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', onFinish)\n next()\n }\n }\n\n /** Mount /health/live and /health/ready endpoints at the root (no API prefix) */\n}\n"],"mappings":";;;;;;;;;;+6CAkEA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA4CxE,SAAgB,aACd,QACgC,CAChC,GAAwB,OAAO,SAAY,WAAvC,QACF,MAAU,UACR,8FAEF,EAEF,GAAI,OAAO,QAAQ,MAAS,UAAY,QAAQ,KAAK,SAAW,EAAG,CACjE,IAAM,IAAM,OAAO,QAAQ,MAAS,SAAW,KA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AW,KAAK,IAAK,MAAM,OAAO,EAC/C,QACF,CACA,KAAK,QAAQ,WAAW,KAAK,IAAK,MAAM,QAAS,CAAE,KAAM,MAAM,IAAK,CAAC,CACvE,CACF,CAEA,qBAA6B,MAA8B,CACrD,OAAO,OAAU,WACnB,KAAK,QAAQ,WAAW,KAAK,IAAK,KAAK,EAEvC,KAAK,QAAQ,WAAW,KAAK,IAAK,MAAM,QAAS,CAAE,KAAM,MAAM,IAAK,CAAC,CAEzE,CAGA,2BAAoD,CAClD,OAAQ,KAAM,IAAK,OAAS,CAC1B,KAAK,oBACL,IAAM,aAAiB,CAKrB,GAJA,IAAI,eAAe,SAAU,QAAQ,EACrC,IAAI,eAAe,QAAS,QAAQ,EACpC,KAAK,oBAED,KAAK,WAAa,KAAK,oBAAsB,EAAG,CAClD,IAAK,IAAM,WAAW,KAAK,gBACzB,QAAQ,EAEV,KAAK,gBAAkB,CAAC,CAC1B,CACF,EACA,IAAI,GAAG,SAAU,QAAQ,EACzB,IAAI,GAAG,QAAS,QAAQ,EACxB,KAAK,CACP,CACF,CAGF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"application-_QOiAVx2.d.mts","names":[],"sources":["../src/core/disposables.ts","../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/bootstrap.ts","../src/http/handler.ts","../src/http/cluster.ts","../src/http/define-http-context-decorator.ts","../src/http/runtimes/express.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAaY,0BAA0B;;iBAKtB,mBAAmB,IAAI;;iBA6BjB,cAAc;;;;;;;;;;;;;;;;;;;;UC9BnB;;EAEf;;EAEA;;EAEA;;EAEA;;EA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SE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{o as reloadEnv}from"./env-BelmDj19.mjs";import{t as Container}from"./container-DF8FRoY8.mjs";import{createLogger}from"./core/logger.mjs";import{t as Application}from"./application-DZiG1QCw.mjs";import{reactive,ref}from"./core/reactivity.mjs";import"./core-y8QbzHM5.mjs";import cluster from"node:cluster";import os from"node:os";const log$1=createLogger(`Cluster`);function isClusterPrimary(){return cluster.isPrimary}function setupClusterPrimary(opts){let numWorkers=opts.workers??os.cpus().length,gracefulTimeout=opts.gracefulShutdownTimeout??5e3,restartDelay=opts.restartDelay??1e3,maxFailures=opts.maxFailures??5,restartWindow=opts.restartWindow??3e4,startupTimeouts=new Map,state=reactive({failureTimestamps:[],shuttingDown:!1}),activeWorkers=ref(0);log$1.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`);for(let i=0;i<numWorkers;i++)cluster.fork();cluster.on(`fork`,worker=>{let timeout=setTimeout(()=>{log$1.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`),worker.kill()},1e4);startupTimeouts.set(worker.id,timeout),activeWorkers.value++,log$1.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)}),cluster.on(`listening`,(worker,address)=>{let timeout=startupTimeouts.get(worker.id);timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),log$1.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)}),cluster.on(`online`,worker=>{log$1.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)}),cluster.on(`exit`,(worker,code,signal)=>{let timeout=startupTimeouts.get(worker.id);if(timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),activeWorkers.value--,worker.exitedAfterDisconnect){log$1.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`);return}let now=Date.now();for(;state.failureTimestamps.length>0&&now-state.failureTimestamps[0]>=restartWindow;)state.failureTimestamps.shift();if(state.failureTimestamps.push(now),state.failureTimestamps.length>maxFailures){log$1.error(`${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`),activeWorkers.value===0&&(log$1.error(`All workers have crashed, exiting primary`),process.exit(1));return}log$1.warn(`Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`),setTimeout(()=>{activeWorkers.value<numWorkers&&cluster.fork()},restartDelay)}),cluster.on(`disconnect`,worker=>{log$1.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)});for(let signal of[`SIGTERM`,`SIGINT`])process.on(signal,()=>{state.shuttingDown||(state.shuttingDown=!0,log$1.info(`Primary received ${signal}, disconnecting workers...`),cluster.disconnect(()=>{log$1.info(`All workers disconnected, exiting primary`),process.exit(0)}),setTimeout(()=>{log$1.warn(`Graceful shutdown timed out, forcing exit`),process.exit(1)},gracefulTimeout).unref())})}function tryReloadEnv(){try{reloadEnv()}catch{}}const log=createLogger(`Process`);async function bootstrap(options){let isViteDev=!!globalThis.__kickjs_httpServer;if(options.cluster&&isViteDev&&log.warn(`Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).`),options.cluster&&cluster.isPrimary&&!isViteDev)return setupClusterPrimary(typeof options.cluster==`object`?options.cluster:{}),new Application(options);let g=globalThis,processHooks=options.processHooks??`auto`;if(!g.__kickBootstrapped){if(processHooks!==`manual`&&(process.on(`uncaughtException`,err=>{log.error(err,`Uncaught exception`)}),process.on(`unhandledRejection`,reason=>{log.error(reason,`Unhandled rejection`)})),processHooks===`auto`&&!g.__kickjs_httpServer)for(let signal of[`SIGINT`,`SIGTERM`])process.on(signal,async()=>{log.info(`Received ${signal}, shutting down...`),g.__app&&await g.__app.shutdown(),process.exit(0)});g.__kickBootstrapped=!0}if(g.__app){log.debug(`HMR rebuild triggered`);try{await g.__app.shutdown({closeServer:!1})}catch(err){log.error(err,`HMR teardown of the previous app failed`)}tryReloadEnv(),Container.reset();let freshApp=new Application(options);return g.__app=freshApp,g.__kickjs_container=freshApp.getContainer(),await freshApp.start(),log.debug(`HMR rebuild complete`),freshApp}let app=new Application(options);return g.__app=app,g.__kickjs_container=app.getContainer(),process.env.KICK_TINKER?(await app.registerOnly(),app):(await app.start(),app)}export{isClusterPrimary as n,bootstrap as t};
|
|
12
|
-
//# sourceMappingURL=bootstrap-BEbka3UV.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap-BEbka3UV.mjs","names":["log"],"sources":["../src/http/cluster.ts","../src/http/bootstrap.ts"],"sourcesContent":["import cluster from 'node:cluster'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n cluster.fork()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n cluster.fork()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","import cluster from 'node:cluster'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers + signal hooks ─────────────────────────────\n // `processHooks` controls whether KickJS registers its own\n // process-level handlers. Defaults to `'auto'` — register everything.\n // Adopters that bring their own observability stack (OpenTelemetry SDK,\n // Sentry, custom shutdown choreographer) often register their own\n // SIGINT/SIGTERM handlers and need to opt out of ours so the two don't\n // race to call `process.exit(0)`. Three modes:\n // - 'auto' (default): register uncaughtException/unhandledRejection\n // loggers + SIGINT/SIGTERM → `app.shutdown()` → `process.exit(0)`.\n // - 'errors-only': register the error loggers; skip signal handlers.\n // Use this when you have your own shutdown choreographer that calls\n // `app.shutdown()` itself.\n // - 'manual': skip everything. Adopter is responsible for both error\n // logging and signal-driven shutdown.\n const processHooks = options.processHooks ?? 'auto'\n\n if (!g.__kickBootstrapped) {\n if (processHooks !== 'manual') {\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n })\n }\n\n if (processHooks === 'auto' && !g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n\n // Tear the PREVIOUS app down before replacing it. Without this the old\n // Application was dropped on the floor still running: its adapters kept\n // their sockets and consumers open, so every save added another set.\n //\n // Observed in the wild as one process holding several consumer-group\n // members — on a single-partition topic only one can hold the assignment,\n // and it was a leaked consumer no longer wired to anything, so jobs\n // stopped being processed. A second socket.io server on the same HTTP\n // server crashed `handleUpgrade()` the same way.\n //\n // `closeServer: false` is load-bearing: the dev HTTP server is shared\n // across rebuilds, so a full shutdown would close the listening socket and\n // kill HMR on the first save.\n //\n // Failures are logged, not thrown — one broken adapter must not leave the\n // dev server wedged with no app at all.\n try {\n await g.__app.shutdown({ closeServer: false })\n } catch (err) {\n log.error(err as Error, 'HMR teardown of the previous app failed')\n }\n\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;;;;;;+UAKA,MAAMA,MAAM,aAAa,SAAS,EAgBlC,SAAgB,kBAA4B,CAC1C,OAAO,QAAQ,SACjB,CAgBA,SAAgB,oBAAoB,KAA4B,CAC9D,IAAM,WAAa,KAAK,SAAW,GAAG,KAAK,CAAC,CAAC,OACvC,gBAAkB,KAAK,yBAA2B,IAClD,aAAe,KAAK,cAAgB,IACpC,YAAc,KAAK,aAAe,EAClC,cAAgB,KAAK,e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-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{i as loadEnv,o as reloadEnv}from"./env-BelmDj19.mjs";import{Service}from"./core/decorators.mjs";import{t as __decorate}from"./decorate-D85rEnU-.mjs";let ConfigService=class{get env(){return loadEnv()}get(key){return this.env[key]}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key){return this.env[key]}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
|
|
12
|
-
//# sourceMappingURL=config-CIOXZmLS.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config-CIOXZmLS.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container._envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T> {\n return this.env[key] as ConfigValue<K, T>\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K] {\n return this.env[key]\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;4JA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAWA,IAA+B,IAAsC,CACnE,OAAO,KAAK,IAAI,IAClB,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EA3DC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EAsGT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAEA,IAAmC,IAAiB,CAClD,OAAO,KAAK,IAAI,IAClB,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAjCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAiCF,mBAGT"}
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v8.6.0
|
|
3
|
-
*
|
|
4
|
-
* Copyright (c) Felix Orinda
|
|
5
|
-
*
|
|
6
|
-
* This source code is licensed under the MIT license found in the
|
|
7
|
-
* LICENSE file in the root directory of this source tree.
|
|
8
|
-
*
|
|
9
|
-
* @license MIT
|
|
10
|
-
*/
|
|
11
|
-
import{METADATA}from"./core/interfaces.mjs";import{createLogger}from"./core/logger.mjs";import{i as getMetaRecord,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,r as getMetaMap,t as getClassMeta}from"./metadata-B8_KXybT.mjs";import"reflect-metadata";let impl=null;function _setAssetResolver(fn){impl=fn}function resolveAssetViaSlot(namespace,key){if(!impl)throw Error(`@Asset('${namespace}/${key}'): the asset manager is not loaded. Import it (any import from '@forinda/kickjs' loads it) — note @Asset reads from the filesystem and is not supported on edge runtimes.`);return impl(namespace,key)}var KickError=class extends Error{code;summary;cause;fix;docsUrl;context;constructor(init){super(formatKickError(init,{color:!1})),this.name=`KickError`,this.code=init.code,this.summary=init.summary,init.cause!==void 0&&(this.cause=init.cause),init.fix!==void 0&&(this.fix=init.fix),init.docsUrl!==void 0&&(this.docsUrl=init.docsUrl),init.context!==void 0&&(this.context=init.context)}};function ansiEnabled(){return process.env.NO_COLOR?!1:process.env.FORCE_COLOR?!0:process.stderr?.isTTY===!0}function paint(text,code,enabled){return enabled?`[${code}m${text}[0m`:text}const c={red:(s,enabled)=>paint(s,`31`,enabled),bold:(s,enabled)=>paint(s,`1`,enabled),dim:(s,enabled)=>paint(s,`2`,enabled),cyan:(s,enabled)=>paint(s,`36`,enabled),blue:(s,enabled)=>paint(s,`34`,enabled),underline:(s,enabled)=>paint(s,`4`,enabled)};function formatKickError(err,options={}){let color=options.color??ansiEnabled(),lines=[],code=c.bold(c.red(err.code,color),color);if(lines.push(`${code}: ${err.summary}`),err.cause){lines.push(``,` ${c.bold(c.dim(`Cause:`,color),color)}`);for(let line of err.cause.split(`
|
|
12
|
-
`))lines.push(` ${highlightInline(line,color)}`)}if(err.fix){lines.push(``,` ${c.bold(c.dim(`Fix:`,color),color)}`);for(let line of err.fix.split(`
|
|
13
|
-
`))lines.push(` ${highlightInline(line,color)}`)}return err.docsUrl&&(lines.push(``,` ${c.bold(c.dim(`Docs:`,color),color)}`),lines.push(` ${c.underline(c.blue(err.docsUrl,color),color)}`)),lines.join(`
|
|
14
|
-
`)}function highlightInline(line,color){return color?line.replace(/`([^`]+)`/g,(_,inner)=>`\`${c.cyan(inner,!0)}\``):line}const DOCS_BASE=`https://kickjs.app`;function noProviderError(tokenName){return new KickError({code:`KICK001`,summary:`No provider for ${tokenName}`,cause:`\`${tokenName}\` was requested from the DI container but no binding is registered.
|
|
15
|
-
This usually means one of:
|
|
16
|
-
• The class is decorated with @Service() / @Repository() / @Controller(),
|
|
17
|
-
but its enclosing module isn't passed to bootstrap({ modules: [...] }).
|
|
18
|
-
• The class isn't decorated at all (decorators register the binding).
|
|
19
|
-
• You're injecting a token (created with createToken()) that nothing
|
|
20
|
-
provides — add a Container.register(TOKEN, ...) call or a module that
|
|
21
|
-
binds it.`,fix:`If \`${tokenName}\` lives in a module, add the module to bootstrap:
|
|
22
|
-
|
|
23
|
-
bootstrap({
|
|
24
|
-
modules: [
|
|
25
|
-
UsersModule, // add this
|
|
26
|
-
OtherModule,
|
|
27
|
-
],
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
If it's a custom token, register it explicitly:
|
|
31
|
-
|
|
32
|
-
const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')
|
|
33
|
-
Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#registering-services`,context:{token:tokenName}})}function requestScopeMiddlewareMissingError(tokenName){return new KickError({code:`KICK002`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" — request scope middleware not mounted`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` but no AsyncLocalStorage frame is wired.
|
|
34
|
-
The framework's request-scope middleware sets up that frame; without it,
|
|
35
|
-
REQUEST-scoped resolutions have nowhere to cache the per-request instance.`,fix:`Add \`requestScopeMiddleware()\` to your global middleware pipeline,
|
|
36
|
-
or let the framework auto-mount it by using \`contextStore: 'auto'\`
|
|
37
|
-
(the default — only check this if you set it to 'manual' explicitly):
|
|
38
|
-
|
|
39
|
-
bootstrap({
|
|
40
|
-
modules,
|
|
41
|
-
// contextStore: 'auto', // default; no need to set
|
|
42
|
-
})
|
|
43
|
-
|
|
44
|
-
If you set \`contextStore: 'manual'\` deliberately (rare), you own the
|
|
45
|
-
ALS wrapping — call \`requestStore.run({...}, () => ...)\` around the
|
|
46
|
-
code that resolves the binding.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function requestScopeOutsideRequestError(tokenName){return new KickError({code:`KICK003`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" outside an HTTP request`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` and was resolved outside
|
|
47
|
-
any HTTP request context. The request-scope middleware is wired, but
|
|
48
|
-
the call happened before a request started (e.g. in a top-level
|
|
49
|
-
import, a constructor, a cron job, a test without setup).`,fix:`If the caller is request-scoped (controller, request-scoped service),
|
|
50
|
-
make sure the call happens inside the request lifecycle, not at module
|
|
51
|
-
load time.
|
|
52
|
-
|
|
53
|
-
In tests, wrap setup in an ALS frame manually:
|
|
54
|
-
|
|
55
|
-
import { requestStore } from '@forinda/kickjs'
|
|
56
|
-
|
|
57
|
-
requestStore.run(
|
|
58
|
-
{ requestId: 'test', instances: new Map(), values: new Map() },
|
|
59
|
-
() => {
|
|
60
|
-
const svc = container.resolve(MyRequestScopedService)
|
|
61
|
-
// ...
|
|
62
|
-
},
|
|
63
|
-
)
|
|
64
|
-
|
|
65
|
-
If the caller is a SINGLETON, change \`${tokenName}\` to TRANSIENT or
|
|
66
|
-
SINGLETON scope, or inject a factory instead of the instance directly.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function envValueMissingError(envKey){return new KickError({code:`KICK004`,summary:`@Value('${envKey}'): environment variable not set and no default provided`,cause:`\`@Value('${envKey}')\` resolved but the env var isn't present and the
|
|
67
|
-
decorator didn't declare a default. Possible reasons:
|
|
68
|
-
• The variable is genuinely missing from your environment / .env file.
|
|
69
|
-
• Your \`src/env.ts\` calls \`loadEnv(envSchema)\` but \`src/index.ts\`
|
|
70
|
-
doesn't import \`./env\` before \`bootstrap()\`. Without that import
|
|
71
|
-
the schema never runs and ConfigService stays empty — \`@Value\`
|
|
72
|
-
only finds the var via the \`process.env\` fallback.`,fix:`Either set the variable in your shell / .env file:
|
|
73
|
-
|
|
74
|
-
${envKey}=...
|
|
75
|
-
|
|
76
|
-
Or add a default at the decorator:
|
|
77
|
-
|
|
78
|
-
@Value('${envKey}', { default: 'fallback' })
|
|
79
|
-
private value!: string
|
|
80
|
-
|
|
81
|
-
If you're using a schema, make sure \`src/env.ts\` is imported from
|
|
82
|
-
\`src/index.ts\` BEFORE bootstrap runs:
|
|
83
|
-
|
|
84
|
-
// src/index.ts
|
|
85
|
-
import 'reflect-metadata'
|
|
86
|
-
import './env' // ← this line is required
|
|
87
|
-
import { bootstrap } from '@forinda/kickjs'
|
|
88
|
-
// ...`,docsUrl:`${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,context:{envKey}})}function moduleRouteMissingControllerError(mountPath){return new KickError({code:`KICK005`,summary:`Module route at ${mountPath} requires either 'controller' or 'router'`,cause:`A module's \`routes()\` returned an entry for \`${mountPath}\` but didn't
|
|
89
|
-
specify how to build the router. The framework needs either a decorated
|
|
90
|
-
controller class (it calls \`buildRoutes()\` internally) or a hand-built
|
|
91
|
-
Express Router.`,fix:`Pass \`controller:\` for the common case:
|
|
92
|
-
|
|
93
|
-
routes() {
|
|
94
|
-
return {
|
|
95
|
-
path: '${mountPath}',
|
|
96
|
-
controller: UsersController,
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
Or pass \`router:\` for full control:
|
|
101
|
-
|
|
102
|
-
routes() {
|
|
103
|
-
return {
|
|
104
|
-
path: '${mountPath}',
|
|
105
|
-
router: myExpressRouter,
|
|
106
|
-
}
|
|
107
|
-
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{mountPath}})}function duplicateRouteError(method,path,owner,prior){return new KickError({code:`KICK006`,summary:`Duplicate route: ${method} ${path} is registered twice`,cause:`\`${owner}\` registers \`${method} ${path}\`, but that verb + path is
|
|
108
|
-
already claimed by \`${prior}\`. Only one handler can win at dispatch
|
|
109
|
-
time, and which one depends on the engine — while \`kick typegen\` and
|
|
110
|
-
the typed client may describe the other. Param names are ignored when
|
|
111
|
-
comparing (\`/:id\` and \`/:taskId\` are the same route).`,fix:`Change one of the two paths, remove the duplicate handler, or mount
|
|
112
|
-
the second controller under a different module path / version:
|
|
113
|
-
|
|
114
|
-
routes() {
|
|
115
|
-
return { path: '/tasks', controller: TasksController, version: 2 }
|
|
116
|
-
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{method,path,owner,prior}})}const INJECTION_TOKEN=Symbol.for(`@kickjs/InjectionToken`);function createToken(name){return Object.freeze({[INJECTION_TOKEN]:!0,name})}function isInjectionToken(value){return typeof value==`object`&&!!value&&value[INJECTION_TOKEN]===!0}const log=createLogger(`Container`);function createReg(fields){return{kind:`unknown`,resolveCount:0,postConstructStatus:`skipped`,dependencies:[],...fields}}function tokenName(token){return typeof token==`symbol`?token.toString():isInjectionToken(token)?token.name:token?.name||String(token)}function getPersistentStore(){return globalThis.__kickjs_persistent||(globalThis.__kickjs_persistent={factories:[],instances:[],resolvedInstances:new Map}),globalThis.__kickjs_persistent}var Container=class Container{static instance;registrations=new Map;resolving=new Set;changeListeners=new Set;pendingChanges=[];notifyTimer=null;static DEBOUNCE_MS=50;static _onReady=null;static _onReset=null;static _onCreate=null;static _envResolver=null;isGlobal=!1;static _requestStoreProvider=null;static getInstance(){return Container.instance||(Container.instance=new Container,Container.instance.isGlobal=!0),Container._onReady&&=(Container._onReady(Container.instance),null),Container.instance}static reset(){Container.instance=new Container,Container.instance.isGlobal=!0,Container._onReset?.(Container.instance);let store=getPersistentStore();for(let{token,factory,scope}of store.factories)if(!Container.instance.has(token)){let name=tokenName(token),existing=store.resolvedInstances.get(name);Container.instance.registrations.set(token,createReg({target:Object,scope,factory,kind:`factory`,instance:existing,resolveCount:+!!existing,postConstructStatus:existing?`completed`:`skipped`}))}for(let{token,instance}of store.instances)Container.instance.has(token)||Container.instance.registrations.set(token,createReg({target:instance.constructor,scope:`singleton`,instance,kind:`instance`,postConstructStatus:`completed`,resolveCount:1}))}static create(){let container=new Container;return Container._onCreate?.(container),container}register(token,target,scope=`singleton`){let kind=getClassMeta(METADATA.CLASS_KIND,target,`unknown`),reg=createReg({target,scope,kind,dependencies:this.extractDependencies(target)});this.registrations.set(token,reg),typeof token==`function`&&token.name&&this.registrations.set(`__hmr__${token.name}`,reg),this.emit(token,`registered`,kind)}registerFactory(token,factory,scope=`singleton`){let store=getPersistentStore(),name=tokenName(token),factoryUnchanged=(this.isGlobal?store.factories.find(r=>tokenName(r.token)===name):void 0)?.factory===factory,existingInstance=this.isGlobal&&factoryUnchanged?store.resolvedInstances.get(name):void 0;if(this.isGlobal&&!factoryUnchanged&&store.resolvedInstances.delete(name),this.registrations.set(token,createReg({target:Object,scope,factory,kind:`factory`,instance:existingInstance,resolveCount:+!!existingInstance,postConstructStatus:existingInstance?`completed`:`skipped`})),this.isGlobal){let idx=store.factories.findIndex(r=>tokenName(r.token)===name);idx>=0?store.factories[idx]={token,factory,scope}:store.factories.push({token,factory,scope})}this.emit(name,`registered`,`factory`)}registerInstance(token,instance){let store=getPersistentStore(),name=tokenName(token);if(this.registrations.set(token,createReg({target:instance.constructor,scope:`singleton`,instance,kind:`instance`,postConstructStatus:`completed`,resolveCount:1,firstResolvedAt:Date.now(),lastResolvedAt:Date.now()})),this.isGlobal){store.resolvedInstances.set(name,instance);let idx=store.instances.findIndex(r=>tokenName(r.token)===name);idx>=0?store.instances[idx]={token,instance}:store.instances.push({token,instance})}this.emit(name,`registered`,`instance`)}has(token){return this.registrations.has(token)}getRegistrations(){let entries=[];for(let[token,reg]of this.registrations)entries.push({token:tokenName(token),scope:reg.scope,kind:reg.kind,instantiated:reg.scope===`singleton`?reg.instance!==void 0:reg.resolveCount>0,resolveCount:reg.resolveCount,lastResolvedAt:reg.lastResolvedAt,firstResolvedAt:reg.firstResolvedAt,resolveDurationMs:reg.resolveDurationMs,postConstructStatus:reg.postConstructStatus,dependencies:reg.dependencies});return entries}resolve(token){let reg=this.registrations.get(token);if(!reg&&typeof token==`function`&&token.name&&(reg=this.registrations.get(`__hmr__${token.name}`)),!reg)throw noProviderError(tokenName(token));if(reg.scope===`singleton`&®.instance!==void 0)return reg.resolveCount++,reg.lastResolvedAt=Date.now(),this.emit(token,`resolved`,reg.kind),reg.instance;if(reg.scope===`request`){if(!Container._requestStoreProvider)throw requestScopeMiddlewareMissingError(tokenName(token));let store=Container._requestStoreProvider();if(!store)throw requestScopeOutsideRequestError(tokenName(token));if(store.values.has(token))return reg.resolveCount++,reg.lastResolvedAt=Date.now(),this.emit(token,`resolved`,reg.kind),store.values.get(token);if(store.instances.has(token))return reg.resolveCount++,reg.lastResolvedAt=Date.now(),this.emit(token,`resolved`,reg.kind),store.instances.get(token);if(reg.factory){let start=performance.now(),instance=reg.factory();return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),store.instances.set(token,instance),this.emit(token,`resolved`,reg.kind),instance}let start=performance.now(),instance=this.createInstance(reg);return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),store.instances.set(token,instance),this.emit(token,`resolved`,reg.kind),instance}if(reg.factory){let start=performance.now(),instance=reg.factory();return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),reg.scope===`singleton`&&(reg.instance=instance,this.isGlobal&&getPersistentStore().resolvedInstances.set(tokenName(token),instance)),this.emit(token,`resolved`,reg.kind),instance}if(this.resolving.has(token)){let chain=[...this.resolving].map(tokenName);throw chain.push(tokenName(token)),Error(`Circular dependency detected: ${chain.join(` -> `)}`)}this.resolving.add(token);try{let start=performance.now(),instance=this.createInstance(reg);return reg.resolveDurationMs=performance.now()-start,reg.resolveCount++,reg.lastResolvedAt=Date.now(),reg.firstResolvedAt||(reg.firstResolvedAt=Date.now()),reg.scope===`singleton`&&(reg.instance=instance),this.emit(token,`resolved`,reg.kind),instance}finally{this.resolving.delete(token)}}bootstrap(){}onChange(callback){return this.changeListeners.add(callback),()=>this.changeListeners.delete(callback)}invalidate(token){let name=tokenName(token),reg=this.registrations.get(token)??this.registrations.get(`__hmr__${name}`);if(reg&&!getPersistentStore().resolvedInstances.has(name)){reg.instance=void 0,reg.resolveCount=0,reg.postConstructStatus=`skipped`,this.emit(name,`invalidated`,reg.kind);for(let[depToken,depReg]of this.registrations)depReg.dependencies.includes(name)&&this.invalidate(depToken)}}emit(rawToken,event,kind){if(this.changeListeners.size===0)return;let token=tokenName(rawToken),existing=this.pendingChanges.find(p=>p.token===token&&p.event===event);existing?existing.timestamp=Date.now():this.pendingChanges.push({token,event,kind,timestamp:Date.now()}),this.notifyTimer&&clearTimeout(this.notifyTimer),this.notifyTimer=setTimeout(()=>{let batch=this.pendingChanges.splice(0);if(batch.length!==0)for(let listener of this.changeListeners)try{listener(batch)}catch{}},Container.DEBOUNCE_MS),this.notifyTimer.unref?.()}flushChanges(){this.notifyTimer&&=(clearTimeout(this.notifyTimer),null);let batch=this.pendingChanges.splice(0);if(batch.length!==0)for(let listener of this.changeListeners)try{listener(batch)}catch{}}buildPlan(reg){let paramTypes=getClassMeta(METADATA.PARAM_TYPES,reg.target,[]),injectTokens=getMetaRecord(METADATA.INJECT,reg.target),maxInjectIndex=Object.keys(injectTokens).length>0?Math.max(...Object.keys(injectTokens).map(Number))+1:0,paramCount=Math.max(paramTypes.length,maxInjectIndex),ctorTokens=[];for(let index=0;index<paramCount;index++){let token=injectTokens[index]||paramTypes[index];if(!token)throw Error(`Cannot resolve constructor parameter at index ${index} of ${tokenName(reg.target)}. No @Inject token and no design:paramtypes metadata (tsx/ts-node don't emit it). Add @Inject(Token) to every constructor parameter.`);if(reg.scope===`singleton`){let depReg=this.registrations.get(token);if(depReg&&depReg.scope===`request`){let parent=tokenName(reg.target),dep=tokenName(token),fix=getClassMetaOrUndefined(METADATA.CLASS_KIND,reg.target)===`controller`?`@Controller() is always SINGLETON, so inject "${dep}" with @Autowired() instead of the constructor.`:`Give "${parent}" TRANSIENT or REQUEST scope (e.g. @Service({ scope: Scope.REQUEST })), or inject "${dep}" with @Autowired() instead of the constructor.`;throw Error(`Cannot inject REQUEST-scoped "${dep}" into SINGLETON "${parent}". Singletons outlive requests. ${fix}`)}}ctorTokens.push(token)}let autowiredProps=getMetaMap(METADATA.AUTOWIRED,reg.target.prototype),autowired=[];for(let[prop,token]of autowiredProps){let resolvedToken=token||getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE,reg.target.prototype,prop);resolvedToken&&autowired.push([prop,resolvedToken])}let values=[...getMetaMap(METADATA.VALUE,reg.target.prototype).entries()],assetProps=getMetaMap(METADATA.ASSET,reg.target.prototype),assets=[];for(let[prop,config]of assetProps){let slashIdx=config.assetKey.indexOf(`/`);if(slashIdx===-1)throw Error(`@Asset('${config.assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);assets.push([prop,{namespace:config.assetKey.slice(0,slashIdx),key:config.assetKey.slice(slashIdx+1)}])}return{ctorTokens,autowired,values,assets,postConstruct:getClassMetaOrUndefined(METADATA.POST_CONSTRUCT,reg.target.prototype)}}createInstance(reg){let plan=reg.plan??=this.buildPlan(reg),args=[];for(let token of plan.ctorTokens)args.push(this.resolve(token));let instance=new reg.target(...args);this.injectProperties(instance,plan);let postConstruct=plan.postConstruct;if(postConstruct&&typeof instance[postConstruct]==`function`)try{let result=instance[postConstruct]();result&&typeof result.then==`function`?(reg.postConstructStatus=`pending`,result.then(()=>{reg.postConstructStatus=`completed`}).catch(()=>{reg.postConstructStatus=`failed`}),log.warn(`@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise but the container is synchronous. The async operation will not be awaited.`)):reg.postConstructStatus=`completed`}catch(err){reg.postConstructStatus=`failed`,log.error(err,`@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`)}return instance}extractDependencies(target){let paramTypes=getClassMeta(METADATA.PARAM_TYPES,target,[]),injectTokens=getMetaRecord(METADATA.INJECT,target),ctorDeps=paramTypes.map((type,index)=>tokenName(injectTokens[index]||type)),autowiredProps=getMetaMap(METADATA.AUTOWIRED,target.prototype),propDeps=[];for(let[prop,token]of autowiredProps){let resolvedToken=token||getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE,target.prototype,prop);resolvedToken&&propDeps.push(tokenName(resolvedToken))}return[...new Set([...ctorDeps,...propDeps])]}injectProperties(instance,plan){for(let[prop,resolvedToken]of plan.autowired)Object.defineProperty(instance,prop,{get:()=>{let value=this.resolve(resolvedToken);return this.registrations.get(resolvedToken)?.scope===`singleton`&&Object.defineProperty(instance,prop,{value,enumerable:!0,configurable:!0,writable:!1}),value},enumerable:!0,configurable:!0});for(let[prop,config]of plan.values)Object.defineProperty(instance,prop,{get(){if(Container._envResolver){let val=Container._envResolver(config.envKey);if(val!==void 0)return val}let val=process.env[config.envKey];if(val!==void 0)return val;if(config.defaultValue!==void 0)return config.defaultValue;throw envValueMissingError(config.envKey)},enumerable:!0,configurable:!0});for(let[prop,{namespace,key}]of plan.assets)Object.defineProperty(instance,prop,{get(){return resolveAssetViaSlot(namespace,key)},enumerable:!0,configurable:!0})}};export{isInjectionToken as a,KickError as c,createToken as i,formatKickError as l,tokenName as n,duplicateRouteError as o,INJECTION_TOKEN as r,moduleRouteMissingControllerError as s,Container as t,_setAssetResolver as u};
|
|
117
|
-
//# sourceMappingURL=container-DF8FRoY8.mjs.map
|