@forinda/kickjs 5.16.0 → 5.18.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-D_uzU-QA.d.mts +2121 -0
- package/dist/adapter-D_uzU-QA.d.mts.map +1 -0
- package/dist/{context-decorator-DDZ30BIW.d.mts → app-module-CuAS6hJC.d.mts} +184 -4
- package/dist/app-module-CuAS6hJC.d.mts.map +1 -0
- package/dist/application-BU5N6o_M.mjs +12 -0
- package/dist/application-BU5N6o_M.mjs.map +1 -0
- package/dist/{application-CAnpDQ8d.d.mts → application-pbx53JnX.d.mts} +31 -5
- package/dist/application-pbx53JnX.d.mts.map +1 -0
- package/dist/{bootstrap-CFK2aAjA.mjs → bootstrap-CFog4v_L.mjs} +3 -3
- package/dist/{bootstrap-CFK2aAjA.mjs.map → bootstrap-CFog4v_L.mjs.map} +1 -1
- package/dist/{bootstrap-8DDzBjhx.d.mts → bootstrap-DzfBj6Ja.d.mts} +2 -2
- package/dist/{bootstrap-8DDzBjhx.d.mts.map → bootstrap-DzfBj6Ja.d.mts.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-BW5taOVX.mjs → config-Di3HlRTS.mjs} +3 -3
- package/dist/{config-BW5taOVX.mjs.map → config-Di3HlRTS.mjs.map} +1 -1
- package/dist/{container-D1gfs6__.mjs → container-BiGimG12.mjs} +3 -3
- package/dist/{container-D1gfs6__.mjs.map → container-BiGimG12.mjs.map} +1 -1
- package/dist/context-leZajQAj.mjs +12 -0
- package/dist/context-leZajQAj.mjs.map +1 -0
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.d.mts +1 -1
- package/dist/core/errors.mjs +2 -2
- package/dist/core/errors.mjs.map +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-Db2uyqtM.mjs → core-Y_xSqZ7v.mjs} +3 -3
- package/dist/{core-Db2uyqtM.mjs.map → core-Y_xSqZ7v.mjs.map} +1 -1
- package/dist/{env-nwsfCpdy.mjs → env-BoMBrGWs.mjs} +3 -3
- package/dist/{env-nwsfCpdy.mjs.map → env-BoMBrGWs.mjs.map} +1 -1
- package/dist/{errors-CRCTjEUK.d.mts → errors-n0H96eEz.d.mts} +3 -1
- package/dist/errors-n0H96eEz.d.mts.map +1 -0
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.mjs +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +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 +2 -2
- package/dist/http/middleware/upload.mjs +3 -3
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.mjs +2 -2
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.d.mts +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +2 -2
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/http/runtimes/fastify.d.mts +66 -0
- package/dist/http/runtimes/fastify.d.mts.map +1 -0
- package/dist/http/runtimes/fastify.mjs +13 -0
- package/dist/http/runtimes/fastify.mjs.map +1 -0
- package/dist/http/runtimes/h3.d.mts +29 -0
- package/dist/http/runtimes/h3.d.mts.map +1 -0
- package/dist/http/runtimes/h3.mjs +12 -0
- package/dist/http/runtimes/h3.mjs.map +1 -0
- package/dist/{index-kEmG8nWU.d.mts → index-BtWJ9SLP.d.mts} +53 -7
- package/dist/{index-kEmG8nWU.d.mts.map → index-BtWJ9SLP.d.mts.map} +1 -1
- package/dist/index.d.mts +12 -17
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{metadata-Cll3P0N0.mjs → metadata-Pvgc-K8a.mjs} +2 -2
- package/dist/{metadata-Cll3P0N0.mjs.map → metadata-Pvgc-K8a.mjs.map} +1 -1
- package/dist/query-B3PhfU6M.mjs +12 -0
- package/dist/query-B3PhfU6M.mjs.map +1 -0
- package/dist/request-scope-BaM8_e_8.mjs +12 -0
- package/dist/request-scope-BaM8_e_8.mjs.map +1 -0
- package/dist/router-builder-Bh3qSiDz.d.mts +39 -0
- package/dist/router-builder-Bh3qSiDz.d.mts.map +1 -0
- package/dist/{spa-IRFC2eMN.d.mts → spa-BdvZFXJz.d.mts} +3 -2
- package/dist/spa-BdvZFXJz.d.mts.map +1 -0
- package/dist/{upload-D6edAELH.d.mts → upload-Bc_rBRtE.d.mts} +37 -2
- package/dist/upload-Bc_rBRtE.d.mts.map +1 -0
- package/dist/{views-BCl-mETX.d.mts → views-DcTVDiOh.d.mts} +31 -7
- package/dist/views-DcTVDiOh.d.mts.map +1 -0
- package/package.json +29 -1
- package/dist/adapter-CkpcZwzZ.d.mts +0 -407
- package/dist/adapter-CkpcZwzZ.d.mts.map +0 -1
- package/dist/app-module-BTzb-Vd6.d.mts +0 -92
- package/dist/app-module-BTzb-Vd6.d.mts.map +0 -1
- package/dist/application-CAnpDQ8d.d.mts.map +0 -1
- package/dist/application-DnnqoDWx.mjs +0 -12
- package/dist/application-DnnqoDWx.mjs.map +0 -1
- package/dist/context-Dnt2Di7p.d.mts +0 -434
- package/dist/context-Dnt2Di7p.d.mts.map +0 -1
- package/dist/context-MD7Mc_o_.mjs +0 -12
- package/dist/context-MD7Mc_o_.mjs.map +0 -1
- package/dist/context-decorator-DDZ30BIW.d.mts.map +0 -1
- package/dist/errors-CRCTjEUK.d.mts.map +0 -1
- package/dist/execution-context-B4cfhivz.d.mts +0 -98
- package/dist/execution-context-B4cfhivz.d.mts.map +0 -1
- package/dist/index-frSEHiL_.d.mts +0 -796
- package/dist/index-frSEHiL_.d.mts.map +0 -1
- package/dist/plugin-BQCn6zyj.d.mts +0 -260
- package/dist/plugin-BQCn6zyj.d.mts.map +0 -1
- package/dist/query-D-FiLfmd.mjs +0 -12
- package/dist/query-D-FiLfmd.mjs.map +0 -1
- package/dist/router-builder-oQpcQMWl.d.mts +0 -31
- package/dist/router-builder-oQpcQMWl.d.mts.map +0 -1
- package/dist/spa-IRFC2eMN.d.mts.map +0 -1
- package/dist/upload-D6edAELH.d.mts.map +0 -1
- package/dist/views-BCl-mETX.d.mts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"application-DnnqoDWx.mjs","names":[],"sources":["../src/http/middleware/request-scope.ts","../src/http/application.ts"],"sourcesContent":["import crypto from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\nimport { requestStore, type RequestStore } from '../request-store'\n\n/**\n * Marker symbol stamped on the function returned by {@link requestScopeMiddleware}.\n *\n * `Application.setup()` uses {@link isRequestScopeMiddleware} to detect whether\n * the user-supplied middleware list already contains the request-scope wrapper,\n * and skips its automatic auto-mount when one is found. Lets adopters control\n * the exact position of the ALS frame in their pipeline (e.g., after a custom\n * tracing wrapper) without ending up with two nested frames.\n */\n// `Symbol.for(...)` returns a plain `symbol` (not `unique symbol`), but the\n// runtime detection marker doesn't need the unique nominal property — it only\n// needs the interned-slot reference equality that `Symbol.for` already provides.\nconst REQUEST_SCOPE_MIDDLEWARE_MARKER = Symbol.for('@kickjs/requestScopeMiddleware')\n\n/**\n * Wraps each request in an AsyncLocalStorage context.\n * Enables REQUEST-scoped DI and automatic requestId propagation to logs.\n *\n * Should be mounted early in the middleware pipeline (before route handlers).\n * `Application` mounts this automatically unless `contextStore: 'manual'` is set\n * or the user already includes one in their middleware list.\n */\nexport function requestScopeMiddleware() {\n const mw = (req: Request, _res: Response, next: NextFunction) => {\n const requestIdHeader = req.headers['x-request-id']\n const requestId =\n (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID()\n const store: RequestStore = {\n requestId,\n instances: new Map(),\n // Explicit generic locks the \"string keys only\" decision\n // (architecture.md §20.12 #4) at construction time, so accidental\n // non-string keys can't slip in via the inferred Map<any, any>.\n values: new Map<string, unknown>(),\n }\n // Surface the requestId on req so the standalone requestId() middleware\n // (when also mounted) reuses this value instead of generating a divergent\n // second one. Without this, log lines that read from the ALS store would\n // disagree with the X-Request-Id response header for any request that\n // didn't carry an inbound x-request-id header.\n ;(req as Request & { requestId?: string }).requestId = requestId\n requestStore.run(store, () => next())\n }\n ;(mw as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] = true\n return mw\n}\n\n/**\n * Returns `true` when `value` is the function produced by {@link requestScopeMiddleware}.\n *\n * Detection uses a `Symbol.for(...)` marker so the check survives different\n * copies of `@forinda/kickjs` loaded under different module identities (e.g.,\n * a published package alongside a workspace-linked one during local dev).\n */\nexport function isRequestScopeMiddleware(value: unknown): boolean {\n if (typeof value !== 'function') return false\n return (value as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] === true\n}\n","import http from 'node:http'\nimport express, { type Express, type RequestHandler } from 'express'\nimport {\n Container,\n createLogger,\n Logger,\n normalizePath,\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 { getClassMeta } from '../core/metadata'\nimport { requestId } from './middleware/request-id'\nimport { notFoundHandler, errorHandler } from './middleware/error-handler'\nimport { requestScopeMiddleware, isRequestScopeMiddleware } from './middleware/request-scope'\nimport { _setExternalContributorSources, buildRoutes } from './router-builder'\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\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') */\n apiPrefix?: string\n /** Default API version (default: 1) — routes become /{prefix}/v{version}/{path} */\n defaultVersion?: number\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 * @deprecated Use {@link ApplicationOptions.middlewares} (plural).\n * Kept as an alias for back-compat; `middlewares` wins when both are\n * set.\n */\n middleware?: 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 /** 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. Receives the raw Express\n * `(req, res, next)` args. When omitted, the built-in handler returns\n * `{ message: 'Not Found' }` with status 404.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onNotFound: (req, res) => {\n * res.status(404).json({ error: 'Route not found', path: req.originalUrl })\n * },\n * })\n * ```\n */\n onNotFound?: (req: any, res: any, next: any) => void\n\n /**\n * Custom global error handler. Receives `(err, req, res, next)` — the\n * standard Express error-handling signature. When omitted, the built-in\n * handler formats ZodError, HttpException, and unexpected errors.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onError: (err, req, res, next) => {\n * logger.error(err)\n * res.status(err.status ?? 500).json({ error: err.message })\n * },\n * })\n * ```\n */\n onError?: (err: any, req: any, res: any, next: any) => 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 */\nexport class Application {\n private app: Express\n private container: Container\n private httpServer: http.Server | null = null\n private readonly adapters: AppAdapter[]\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.app = 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 handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void {\n if (next) {\n this.app(req as any, res as any, next)\n } else {\n this.app(req as any, res as any)\n }\n }\n\n /**\n * Full setup pipeline:\n * 1. Adapter beforeMount hooks (early routes — docs, health)\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\n * 6. Adapter middleware (phase: beforeRoutes)\n * 7. Module route mounting\n * 8. Adapter middleware (phase: afterRoutes)\n * 9. Error handlers (notFound + global)\n * 10. Adapter beforeStart hooks\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 app: this.app,\n container: this.container,\n server,\n env,\n isProduction: env === 'production',\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 this.app.disable('x-powered-by')\n this.app.set('trust proxy', this.options.trustProxy ?? false)\n\n // ── 2a. In-flight request tracking ──────────────────────────────\n this.app.use(this.requestTrackingMiddleware())\n\n // ── 2b. Health check endpoints (before middleware, at root) ──────\n this.mountHealthEndpoints()\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.app.use(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.app.use(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\n const autoHelmet = this.options.security?.helmet !== false\n if (autoHelmet) {\n try {\n const { helmet: helmetFn } = await import('./middleware/helmet')\n this.app.use(helmetFn())\n } catch {\n // helmet middleware not available — skip silently\n }\n }\n\n const userMiddlewares = this.options.middlewares ?? this.options.middleware\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.app.use(requestId())\n this.app.use(express.json({ limit: this.options.jsonLimit ?? '1mb' }))\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 const allModuleEntries: AppModuleEntry[] = moduleRegistry.entries\n const modules = allModuleEntries.map((entry) => {\n // Discriminate class vs instance: classes are functions whose\n // `prototype` carries the AppModule shape; defineModule output is\n // a plain object with `routes`, `register`, `contributors`. Calling\n // `new` on a plain object throws, so we branch up-front rather\n // than try/catch.\n const mod: AppModule = typeof entry === 'function' ? new (entry as AppModuleClass)() : 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 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 const mountPath = `${apiPrefix}/v${version}${normalizePath(route.path)}`\n // Derive the router from `controller` when one wasn't passed\n // explicitly. The common-case shape is `{ path, controller }` —\n // the framework owns `buildRoutes(controller)` so adopters don't\n // import + call it themselves. Adopters who hand-build a router\n // (composing multiple controllers, mounting third-party routers)\n // pass `router` explicitly and we use it as-is.\n const router = route.router ?? buildRoutes(route.controller)\n if (!router) {\n throw moduleRouteMissingControllerError(mountPath)\n }\n this.app.use(mountPath, router)\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 this.app.use(this.options.onNotFound ?? notFoundHandler())\n this.app.use(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 * 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.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\n try {\n Container.reset()\n this.container = Container.getInstance()\n this.app = 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 this.app = prevApp\n this.container = prevContainer\n return\n }\n\n if (this.httpServer) {\n this.httpServer.removeAllListeners('request')\n this.httpServer.on('request', this.app)\n log.debug('HMR: Express 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(): Promise<void> {\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 (this.httpServer) {\n this.httpServer.close(() => {})\n }\n\n // Step 2: Wait for in-flight requests to drain (or timeout)\n if (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 const results = await Promise.allSettled([\n ...this.plugins.map((plugin) => Promise.resolve(plugin.shutdown?.())),\n ...this.adapters.map((adapter) => Promise.resolve(adapter.shutdown?.())),\n ])\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error({ err: result.reason }, 'Adapter shutdown failed')\n }\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\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 ?? this.options.middleware ?? []\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.app.use(entry.handler)\n continue\n }\n // Copy ReadonlyArray paths to a mutable array — Express's\n // `PathParams` doesn't accept readonly arrays, even though the\n // function never mutates them. Pass-through for non-array shapes.\n const path: string | RegExp | (string | RegExp)[] = Array.isArray(entry.path)\n ? [...entry.path]\n : (entry.path as string | RegExp)\n this.app.use(path, entry.handler)\n }\n }\n\n private mountMiddlewareEntry(entry: MiddlewareEntry): void {\n if (typeof entry === 'function') {\n this.app.use(entry)\n } else {\n this.app.use(entry.path, entry.handler)\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 private mountHealthEndpoints(): void {\n this.app.get('/health/live', (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', uptime: process.uptime() })\n } else {\n res.json({ status: 'ok', uptime: process.uptime() })\n }\n })\n\n this.app.get('/health/ready', async (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', checks: [] })\n return\n }\n const adaptersWithHealth = this.adapters.filter((a) => a.onHealthCheck)\n const checks = await Promise.allSettled(adaptersWithHealth.map((a) => a.onHealthCheck!()))\n const results = checks.map((c, i) => {\n if (c.status === 'fulfilled') return c.value\n return { name: adaptersWithHealth[i].name ?? 'unknown', status: 'down' as const }\n })\n const healthy = results.every((r) => r.status === 'up')\n res.status(healthy ? 200 : 503).json({\n status: healthy ? 'ready' : 'degraded',\n checks: results,\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;8tBAgBA,MAAM,gCAAkC,OAAO,IAAI,gCAAgC,EAUnF,SAAgB,wBAAyB,CACvC,IAAM,IAAM,IAAc,KAAgB,OAAuB,CAC/D,IAAM,gBAAkB,IAAI,QAAQ,gBAC9B,WACH,MAAM,QAAQ,eAAe,EAAI,gBAAgB,GAAK,kBAAoB,OAAO,WAAW,EACzF,MAAsB,CAC1B,UACA,UAAW,IAAI,IAIf,OAAQ,IAAI,GACd,EAMC,IAA0C,UAAY,UACvD,aAAa,IAAI,UAAa,KAAK,CAAC,CACtC,EAEA,MADC,IAA2C,iCAAmC,GACxE,EACT,CASA,SAAgB,yBAAyB,MAAyB,CAEhE,OADI,OAAO,OAAU,WACb,MAA6C,mCAAqC,GADlD,EAE1C,CC9BA,MAAM,IAAM,aAAa,aAAa,EA8PtC,IAAa,YAAb,KAAyB,CAkCM,QAjC7B,IACA,UACA,WAAyC,KACzC,SAEA,QAcA,oBAGK,CAAC,EAGN,kBAA4B,EAE5B,UAAoB,GAEpB,mBAA6B,GAE7B,gBAA6C,CAAC,EAE9C,YAAY,QAA8C,CAA7B,KAAA,QAAA,QAC3B,KAAK,IAAM,QAAQ,EACnB,KAAK,UAAY,UAAU,YAAY,EAKvC,KAAK,QAAU,UAAU,QAAQ,SAAW,CAAC,EAAG,QAAQ,EAOxD,IAAM,YAAc,CAClB,GAAG,KAAK,QAAQ,QAAS,GAAM,EAAE,WAAW,GAAK,CAAC,CAAC,EACnD,GAAI,QAAQ,UAAY,CAAC,CAC3B,EACI,iBAAmB,EACjB,cAAsD,YAAY,IAAK,SAAY,CACvF,GAAI,CAAC,QAAQ,KAAM,CAIjB,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,CACH,CAAC,CACH,CACF"}
|
|
@@ -1,434 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import { i as MetaValue, r as ExecutionContext } from "./execution-context-B4cfhivz.mjs";
|
|
3
|
-
import { i as ProblemDetails } from "./errors-CRCTjEUK.mjs";
|
|
4
|
-
import { g as QueryFieldConfig, y as TypedParsedQuery } from "./index-kEmG8nWU.mjs";
|
|
5
|
-
import { NextFunction, Request, Response } from "express";
|
|
6
|
-
|
|
7
|
-
//#region src/http/context.d.ts
|
|
8
|
-
/**
|
|
9
|
-
* Input shape for the typed problem-detail convenience methods on
|
|
10
|
-
* {@link ProblemSender} (`ctx.problem.notFound`, `.badRequest`, etc.) —
|
|
11
|
-
* RFC 9457 details minus the `status`, which each method pre-fills.
|
|
12
|
-
*/
|
|
13
|
-
type ProblemInput = Omit<ProblemDetails, 'status'>;
|
|
14
|
-
/**
|
|
15
|
-
* Callable response helper for RFC 9457 — Problem Details responses.
|
|
16
|
-
* Returned by `ctx.problem`. Invoke directly for a fully-specified
|
|
17
|
-
* payload, or use the named convenience methods to pre-fill `status` +
|
|
18
|
-
* `title` for the common codes.
|
|
19
|
-
*
|
|
20
|
-
* Each call sets `Content-Type: application/problem+json` and serializes
|
|
21
|
-
* the canonical shape (defaulting `type` to `about:blank` and `title` to
|
|
22
|
-
* the IANA reason phrase per RFC 9457 §3.1.1 / §3.1.4).
|
|
23
|
-
*
|
|
24
|
-
* @example
|
|
25
|
-
* ```ts
|
|
26
|
-
* ctx.problem({
|
|
27
|
-
* type: 'https://api.example.com/problems/out-of-credit',
|
|
28
|
-
* status: 403,
|
|
29
|
-
* detail: 'Your balance is 30, but that costs 50.',
|
|
30
|
-
* balance: 30, // extension per §3.2
|
|
31
|
-
* })
|
|
32
|
-
*
|
|
33
|
-
* ctx.problem.notFound({ detail: 'User abc not found' })
|
|
34
|
-
* ctx.problem.validation(zodResult.error.issues)
|
|
35
|
-
* ```
|
|
36
|
-
*/
|
|
37
|
-
interface ProblemSender {
|
|
38
|
-
(input: ProblemDetails): Response;
|
|
39
|
-
/** 400 Bad Request — RFC 9457. */
|
|
40
|
-
badRequest(input?: ProblemInput): Response;
|
|
41
|
-
/** 401 Unauthorized — RFC 9457. */
|
|
42
|
-
unauthorized(input?: ProblemInput): Response;
|
|
43
|
-
/** 403 Forbidden — RFC 9457. */
|
|
44
|
-
forbidden(input?: ProblemInput): Response;
|
|
45
|
-
/** 404 Not Found — RFC 9457. */
|
|
46
|
-
notFound(input?: ProblemInput): Response;
|
|
47
|
-
/** 409 Conflict — RFC 9457. */
|
|
48
|
-
conflict(input?: ProblemInput): Response;
|
|
49
|
-
/** 422 Unprocessable Entity — RFC 9457. */
|
|
50
|
-
unprocessable(input?: ProblemInput): Response;
|
|
51
|
-
/** 429 Too Many Requests — RFC 9457. */
|
|
52
|
-
tooManyRequests(input?: ProblemInput): Response;
|
|
53
|
-
/** 500 Internal Server Error — RFC 9457. */
|
|
54
|
-
internal(input?: ProblemInput): Response;
|
|
55
|
-
/**
|
|
56
|
-
* 422 with Zod issues serialized into the `errors` extension per
|
|
57
|
-
* RFC 9457 §3.2's array convention. Pass `error.issues` from a Zod
|
|
58
|
-
* `safeParse` failure or `error.issues` from a thrown ZodError.
|
|
59
|
-
*/
|
|
60
|
-
validation(issues: any[], input?: ProblemInput): Response;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Recursively marks every property of `T` as `readonly`. Preserves
|
|
64
|
-
* `Function`, `Date`, and `RegExp` unchanged, and converts `Map` / `Set`
|
|
65
|
-
* to `ReadonlyMap` / `ReadonlySet` so their mutating methods (`set`,
|
|
66
|
-
* `delete`, `add`, `clear`) are removed from the public surface.
|
|
67
|
-
* Tuples keep their positional element types — only their per-element
|
|
68
|
-
* mutability is locked.
|
|
69
|
-
*
|
|
70
|
-
* Exposed as a utility for adopters who want to opt into compile-time
|
|
71
|
-
* sealing of their own shapes. **No longer applied to
|
|
72
|
-
* `RequestContext.{body,params,query,headers,file,files}`** — that
|
|
73
|
-
* broke TS narrowing / discriminated-union drilldowns on typed request
|
|
74
|
-
* payloads. Runtime read-only enforcement now lives in
|
|
75
|
-
* {@link makeReadOnlyProxy} (dev-only Proxy that warns on writes,
|
|
76
|
-
* no-op in production).
|
|
77
|
-
*
|
|
78
|
-
* Type-only. No runtime cost. `DeepReadonly<any>` is `any` (TS
|
|
79
|
-
* distributes conditional types over `any`).
|
|
80
|
-
*/
|
|
81
|
-
type DeepReadonly<T> = T extends ((...args: never[]) => unknown) ? T : T extends Date | RegExp ? T : T extends Map<infer K, infer V> ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>> : T extends Set<infer V> ? ReadonlySet<DeepReadonly<V>> : T extends readonly (infer U)[] ? number extends T['length'] ? ReadonlyArray<DeepReadonly<U>> : { readonly [K in keyof T]: DeepReadonly<T[K]> } : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]> } : T;
|
|
82
|
-
/**
|
|
83
|
-
* The shape of a single route entry in `KickRoutes`. Generated by
|
|
84
|
-
* `kick typegen` and consumed via the `Ctx<T>` helper. Each field is
|
|
85
|
-
* `unknown` by default and is filled in as the typegen learns more
|
|
86
|
-
* about the route (URL params from the path, body/query from validation
|
|
87
|
-
* schemas, etc.).
|
|
88
|
-
*/
|
|
89
|
-
interface RouteShape {
|
|
90
|
-
params?: unknown;
|
|
91
|
-
body?: unknown;
|
|
92
|
-
query?: unknown;
|
|
93
|
-
response?: unknown;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Unified request/response abstraction passed to every controller method.
|
|
97
|
-
* Shields handlers from raw Express objects and provides convenience methods.
|
|
98
|
-
*
|
|
99
|
-
* Implements {@link ExecutionContext} so the transport-agnostic Context
|
|
100
|
-
* Contributor pipeline (#107) can run against this concrete HTTP context
|
|
101
|
-
* the same way it will run against future WS / queue / cron contexts.
|
|
102
|
-
*/
|
|
103
|
-
declare class RequestContext<TBody = any, TParams = any, TQuery = any> implements ExecutionContext {
|
|
104
|
-
readonly req: Request;
|
|
105
|
-
readonly res: Response;
|
|
106
|
-
readonly next: NextFunction;
|
|
107
|
-
constructor(req: Request, res: Response, next: NextFunction);
|
|
108
|
-
/**
|
|
109
|
-
* Read-side accessor for the per-request metadata map.
|
|
110
|
-
*
|
|
111
|
-
* Returns the AsyncLocalStorage map (`requestStore.getStore().values`)
|
|
112
|
-
* shared with the Context Contributor pipeline when an ALS frame is
|
|
113
|
-
* active. Returns `null` outside any frame — read-side callers
|
|
114
|
-
* (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as
|
|
115
|
-
* "no metadata" and fall through to their `req.*` defaults. Reads
|
|
116
|
-
* never throw because outside an ALS frame nobody could have written
|
|
117
|
-
* via `ctx.set` anyway, so an empty answer is the truthful one.
|
|
118
|
-
*/
|
|
119
|
-
private metadataReadOnly;
|
|
120
|
-
/**
|
|
121
|
-
* Write-side accessor for the per-request metadata map.
|
|
122
|
-
*
|
|
123
|
-
* Returns the same map as {@link metadataReadOnly} when an ALS frame
|
|
124
|
-
* is active. Throws otherwise — writing to a fallback map outside
|
|
125
|
-
* the ALS frame would silently lose data because other call sites
|
|
126
|
-
* (downstream contributors, request-logger, etc.) read from the
|
|
127
|
-
* canonical store and would never see it. Mount
|
|
128
|
-
* `requestScopeMiddleware()` (Application does this for you in
|
|
129
|
-
* `'auto'` mode) or wrap your test setup in
|
|
130
|
-
* `requestStore.run({...}, () => …)` to fix.
|
|
131
|
-
*/
|
|
132
|
-
private metadataForWrite;
|
|
133
|
-
/**
|
|
134
|
-
* Parsed request body. Wrapped in a dev-only Proxy that warns when
|
|
135
|
-
* adopters try to mutate Zod-validated payloads in place — compute
|
|
136
|
-
* new values and stash them via `ctx.set('key', value)` or a Context
|
|
137
|
-
* Contributor instead. Reach for `ctx.req.body` if you genuinely
|
|
138
|
-
* need the raw, mutable Express handle (rare).
|
|
139
|
-
*
|
|
140
|
-
* In production the Proxy is bypassed and `this.req.body` is
|
|
141
|
-
* returned as-is — no runtime cost on the hot path.
|
|
142
|
-
*/
|
|
143
|
-
get body(): TBody;
|
|
144
|
-
/** Path parameters parsed from the route — read-only, see {@link body}. */
|
|
145
|
-
get params(): TParams;
|
|
146
|
-
/** Parsed query string — read-only, see {@link body}. */
|
|
147
|
-
get query(): TQuery;
|
|
148
|
-
/** Inbound HTTP headers — read-only, see {@link body}. */
|
|
149
|
-
get headers(): Request['headers'];
|
|
150
|
-
get requestId(): string | undefined;
|
|
151
|
-
/**
|
|
152
|
-
* `AbortSignal` that fires when the underlying HTTP request is
|
|
153
|
-
* closed — either because the client disconnected before the
|
|
154
|
-
* response was sent, or because Node's socket-close event ran
|
|
155
|
-
* after a normal response. Multiple `RequestContext` wrappers for
|
|
156
|
-
* the same request (router-builder constructs one per
|
|
157
|
-
* middleware/contributor pipeline / main handler) share a single
|
|
158
|
-
* `AbortController` cached on the underlying `req` object, so the
|
|
159
|
-
* signal is stable across the request lifecycle.
|
|
160
|
-
*
|
|
161
|
-
* Thread it through anything that takes an `AbortSignal` so the
|
|
162
|
-
* work cancels as soon as the client gives up — e.g. a kickjs-db
|
|
163
|
-
* relational query:
|
|
164
|
-
*
|
|
165
|
-
* ```ts
|
|
166
|
-
* @Get('/:id/full')
|
|
167
|
-
* async show(ctx: RequestContext) {
|
|
168
|
-
* const row = await this.repo.findFullById(ctx.params.id, ctx.signal)
|
|
169
|
-
* if (!row) return ctx.notFound()
|
|
170
|
-
* ctx.json(row)
|
|
171
|
-
* }
|
|
172
|
-
* ```
|
|
173
|
-
*
|
|
174
|
-
* The repo passes `signal` to `db.query.<table>.findUnique({ signal })`;
|
|
175
|
-
* if the client disconnects mid-flight, the in-flight query rejects
|
|
176
|
-
* with `RelationalQueryCancelledError` instead of consuming the
|
|
177
|
-
* connection until completion.
|
|
178
|
-
*
|
|
179
|
-
* Implementation note — both `req.on('close')` and `res.on('close')`
|
|
180
|
-
* are wired so the signal aborts regardless of whether the close
|
|
181
|
-
* event lands on the request stream or the response stream first.
|
|
182
|
-
* Subsequent fires are no-ops (`AbortController.abort()` is
|
|
183
|
-
* idempotent).
|
|
184
|
-
*/
|
|
185
|
-
get signal(): AbortSignal;
|
|
186
|
-
/** Session data (requires session middleware) */
|
|
187
|
-
get session(): any;
|
|
188
|
-
/**
|
|
189
|
-
* The authenticated user set by AuthAdapter.
|
|
190
|
-
* Reads from the per-request metadata store first (`ctx.set('user', ...)`),
|
|
191
|
-
* then falls back to `req.user` (set directly by AuthAdapter middleware).
|
|
192
|
-
*
|
|
193
|
-
* Extend the `AuthUser` interface via module augmentation in `@forinda/kickjs-auth`
|
|
194
|
-
* to get full typing.
|
|
195
|
-
*
|
|
196
|
-
* @example
|
|
197
|
-
* ```ts
|
|
198
|
-
* @Get('/me')
|
|
199
|
-
* @Authenticated()
|
|
200
|
-
* getProfile(ctx: RequestContext) {
|
|
201
|
-
* const user = ctx.user
|
|
202
|
-
* if (!user) return ctx.notFound()
|
|
203
|
-
* return ctx.json({ user })
|
|
204
|
-
* }
|
|
205
|
-
* ```
|
|
206
|
-
*/
|
|
207
|
-
get user(): MetaValue<'user', Record<string, any>> | undefined;
|
|
208
|
-
/**
|
|
209
|
-
* Tenant identifier for multi-tenant apps. Reads `user.tenantId` —
|
|
210
|
-
* populated either by `AuthAdapter.testMode({ tenantId })`, a tenant
|
|
211
|
-
* resolver middleware, or manually on the strategy's `mapPayload`.
|
|
212
|
-
*
|
|
213
|
-
* Augment `AuthUser` (or `ContextMeta['user']`) to widen the return
|
|
214
|
-
* type if your user shape guarantees a non-`string | undefined` id.
|
|
215
|
-
*/
|
|
216
|
-
get tenantId(): string | undefined;
|
|
217
|
-
/**
|
|
218
|
-
* Effective role list for the current user. Prefers `user.tenantRoles`
|
|
219
|
-
* (populated by `AuthAdapterOptions.roleResolver` under a tenant) and
|
|
220
|
-
* falls back to `user.roles`. Returns an empty array when the user is
|
|
221
|
-
* absent or the shape has neither field.
|
|
222
|
-
*/
|
|
223
|
-
get roles(): string[];
|
|
224
|
-
/**
|
|
225
|
-
* Parse the request query string into structured filters, sort, pagination, and search.
|
|
226
|
-
* Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
|
|
227
|
-
*
|
|
228
|
-
* Generic over the field config: when passed an inline literal (or
|
|
229
|
-
* `as const`), `filters[].field` and `sort[].field` are narrowed to
|
|
230
|
-
* the exact whitelisted field names. Pass nothing or a non-literal
|
|
231
|
-
* config and you get the loose `string` fallback.
|
|
232
|
-
*
|
|
233
|
-
* @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
|
|
234
|
-
*
|
|
235
|
-
* @example
|
|
236
|
-
* ```ts
|
|
237
|
-
* @Get('/')
|
|
238
|
-
* async list(ctx: RequestContext) {
|
|
239
|
-
* const parsed = ctx.qs({
|
|
240
|
-
* filterable: ['status', 'priority'],
|
|
241
|
-
* sortable: ['createdAt', 'title'],
|
|
242
|
-
* } as const)
|
|
243
|
-
* parsed.filters[0].field // typed as 'status' | 'priority'
|
|
244
|
-
* parsed.sort[0].field // typed as 'createdAt' | 'title'
|
|
245
|
-
* }
|
|
246
|
-
* ```
|
|
247
|
-
*/
|
|
248
|
-
qs<TConfig extends QueryFieldConfig | undefined = undefined>(fieldConfig?: TConfig): TypedParsedQuery<TConfig>;
|
|
249
|
-
/**
|
|
250
|
-
* Single uploaded file (requires `@FileUpload({ mode: 'single' })`).
|
|
251
|
-
* Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.
|
|
252
|
-
* File metadata is set by the upload middleware and shouldn't be
|
|
253
|
-
* mutated downstream.
|
|
254
|
-
*/
|
|
255
|
-
get file(): Express.Multer.File | undefined;
|
|
256
|
-
/**
|
|
257
|
-
* Array of uploaded files (requires `@FileUpload({ mode: 'array' })`).
|
|
258
|
-
* The array (and each entry in dev) is wrapped in a read-only Proxy
|
|
259
|
-
* that warns on `push`/`pop` and per-file mutation. Use
|
|
260
|
-
* `ctx.req.files` if you genuinely need the mutable Express handle.
|
|
261
|
-
*/
|
|
262
|
-
get files(): Express.Multer.File[] | undefined;
|
|
263
|
-
/**
|
|
264
|
-
* Read a value from the per-request metadata store.
|
|
265
|
-
*
|
|
266
|
-
* When `ContextMeta` has been augmented with a matching key, the return
|
|
267
|
-
* type is inferred automatically. For ad-hoc keys, pass a generic:
|
|
268
|
-
* `ctx.get<MyType>('custom')`.
|
|
269
|
-
*/
|
|
270
|
-
get<K extends string>(key: K): MetaValue<K> | undefined;
|
|
271
|
-
/**
|
|
272
|
-
* Write a value to the per-request metadata store. Throws when no
|
|
273
|
-
* AsyncLocalStorage frame is active — see {@link metadataForWrite}
|
|
274
|
-
* for why a silent fallback is the wrong default.
|
|
275
|
-
*/
|
|
276
|
-
set<K extends string>(key: K, value: MetaValue<K>): void;
|
|
277
|
-
json(data: any, status?: number): Response<any, Record<string, any>>;
|
|
278
|
-
created(data: any): Response<any, Record<string, any>>;
|
|
279
|
-
noContent(): Response<any, Record<string, any>>;
|
|
280
|
-
/**
|
|
281
|
-
* @deprecated Prefer {@link ProblemSender.notFound | ctx.problem.notFound()},
|
|
282
|
-
* which emits an RFC 9457 — Problem Details response. This helper stays
|
|
283
|
-
* for backward compatibility and will not be removed.
|
|
284
|
-
*/
|
|
285
|
-
notFound(message?: string): Response<any, Record<string, any>>;
|
|
286
|
-
/**
|
|
287
|
-
* @deprecated Prefer {@link ProblemSender.badRequest | ctx.problem.badRequest()},
|
|
288
|
-
* which emits an RFC 9457 — Problem Details response. This helper stays
|
|
289
|
-
* for backward compatibility and will not be removed.
|
|
290
|
-
*/
|
|
291
|
-
badRequest(message: string): Response<any, Record<string, any>>;
|
|
292
|
-
/**
|
|
293
|
-
* RFC 9457 — Problem Details for HTTP APIs response helper.
|
|
294
|
-
* https://datatracker.ietf.org/doc/html/rfc9457
|
|
295
|
-
*
|
|
296
|
-
* `ctx.problem(...)` sends a canonical problem-detail response with
|
|
297
|
-
* `Content-Type: application/problem+json`. The convenience methods
|
|
298
|
-
* (`ctx.problem.notFound`, `.badRequest`, etc.) pre-fill `status` +
|
|
299
|
-
* `title` for the common codes.
|
|
300
|
-
*
|
|
301
|
-
* `type` defaults to `about:blank` (§3.1.1); `title` defaults to the
|
|
302
|
-
* IANA reason phrase for `status` (§3.1.4). Extension members per §3.2
|
|
303
|
-
* pass through unchanged.
|
|
304
|
-
*
|
|
305
|
-
* @example
|
|
306
|
-
* ```ts
|
|
307
|
-
* ctx.problem({
|
|
308
|
-
* type: 'https://api.example.com/problems/out-of-credit',
|
|
309
|
-
* status: 403,
|
|
310
|
-
* detail: 'Your balance is 30, but that costs 50.',
|
|
311
|
-
* instance: `/account/${ctx.user.id}/messages/${ctx.params.id}`,
|
|
312
|
-
* balance: 30,
|
|
313
|
-
* })
|
|
314
|
-
*
|
|
315
|
-
* ctx.problem.notFound({ detail: 'User abc not found' })
|
|
316
|
-
* ctx.problem.validation(zodResult.error.issues)
|
|
317
|
-
* ```
|
|
318
|
-
*
|
|
319
|
-
* @see {@link ProblemException} for the exception-throwing equivalent
|
|
320
|
-
* (use it from services where `ctx` isn't in scope).
|
|
321
|
-
*/
|
|
322
|
-
get problem(): ProblemSender;
|
|
323
|
-
private sendProblem;
|
|
324
|
-
html(content: string, status?: number): Response<any, Record<string, any>>;
|
|
325
|
-
download(buffer: Buffer, filename: string, contentType?: string): Response<any, Record<string, any>>;
|
|
326
|
-
/**
|
|
327
|
-
* Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
|
|
328
|
-
* Requires a ViewAdapter to be configured in bootstrap().
|
|
329
|
-
*
|
|
330
|
-
* @param template - Template name (without extension, relative to viewsDir)
|
|
331
|
-
* @param data - Data to pass to the template
|
|
332
|
-
*
|
|
333
|
-
* @example
|
|
334
|
-
* ```ts
|
|
335
|
-
* ctx.render('dashboard', { user, title: 'Dashboard' })
|
|
336
|
-
* ctx.render('emails/welcome', { name: 'Alice' })
|
|
337
|
-
* ```
|
|
338
|
-
*/
|
|
339
|
-
render(template: string, data?: Record<string, any>): void;
|
|
340
|
-
/**
|
|
341
|
-
* Parse query params and return a standardized paginated response.
|
|
342
|
-
* Calls `ctx.qs()` internally, then wraps your data with pagination meta.
|
|
343
|
-
*
|
|
344
|
-
* @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
|
|
345
|
-
* @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
|
|
346
|
-
*
|
|
347
|
-
* @example
|
|
348
|
-
* ```ts
|
|
349
|
-
* @Get('/')
|
|
350
|
-
* async list(ctx: RequestContext) {
|
|
351
|
-
* return ctx.paginate(
|
|
352
|
-
* async (parsed) => {
|
|
353
|
-
* const data = await db.select().from(users)
|
|
354
|
-
* .where(query.where).limit(parsed.pagination.limit)
|
|
355
|
-
* .offset(parsed.pagination.offset).all()
|
|
356
|
-
* const total = await db.select({ count: count() }).from(users).get()
|
|
357
|
-
* return { data, total: total?.count ?? 0 }
|
|
358
|
-
* },
|
|
359
|
-
* { filterable: ['name', 'role'], sortable: ['createdAt'] },
|
|
360
|
-
* )
|
|
361
|
-
* }
|
|
362
|
-
* ```
|
|
363
|
-
*/
|
|
364
|
-
paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{
|
|
365
|
-
data: T[];
|
|
366
|
-
total: number;
|
|
367
|
-
}>, fieldConfig?: TConfig): Promise<Response<any, Record<string, any>>>;
|
|
368
|
-
/**
|
|
369
|
-
* Start an SSE (Server-Sent Events) stream.
|
|
370
|
-
* Sets the correct headers and returns helpers to send events.
|
|
371
|
-
*
|
|
372
|
-
* @example
|
|
373
|
-
* ```ts
|
|
374
|
-
* @Get('/events')
|
|
375
|
-
* async stream(ctx: RequestContext) {
|
|
376
|
-
* const sse = ctx.sse()
|
|
377
|
-
*
|
|
378
|
-
* const interval = setInterval(() => {
|
|
379
|
-
* sse.send({ time: new Date().toISOString() }, 'tick')
|
|
380
|
-
* }, 1000)
|
|
381
|
-
*
|
|
382
|
-
* sse.onClose(() => clearInterval(interval))
|
|
383
|
-
* }
|
|
384
|
-
* ```
|
|
385
|
-
*/
|
|
386
|
-
sse(): {
|
|
387
|
-
/** Send an SSE event with optional event name and id */send: (data: any, event?: string, id?: string) => void; /** Send a comment (keeps connection alive) */
|
|
388
|
-
comment: (text: string) => void; /** Register a callback when the client disconnects */
|
|
389
|
-
onClose: (fn: () => void) => void; /** End the SSE stream */
|
|
390
|
-
close: () => void;
|
|
391
|
-
};
|
|
392
|
-
}
|
|
393
|
-
/**
|
|
394
|
-
* Short alias for `RequestContext` parameterised by a route shape.
|
|
395
|
-
*
|
|
396
|
-
* Use with `kick typegen`'s generated `KickRoutes` namespace for
|
|
397
|
-
* fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata
|
|
398
|
-
* typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from
|
|
399
|
-
* `ContextMeta` augmentation and works on all `RequestContext` instances.
|
|
400
|
-
*
|
|
401
|
-
* @example
|
|
402
|
-
* ```ts
|
|
403
|
-
* @Get('/:id')
|
|
404
|
-
* getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {
|
|
405
|
-
* ctx.params.id // typed from RouteShape
|
|
406
|
-
* ctx.body // typed from RouteShape
|
|
407
|
-
* ctx.user // typed from ContextMeta
|
|
408
|
-
* ctx.get('tenant') // typed from ContextMeta
|
|
409
|
-
* }
|
|
410
|
-
* ```
|
|
411
|
-
*/
|
|
412
|
-
type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<TRoute extends {
|
|
413
|
-
body: infer B;
|
|
414
|
-
} ? B : any, TRoute extends {
|
|
415
|
-
params: infer P;
|
|
416
|
-
} ? P : any, TRoute extends {
|
|
417
|
-
query: infer Q;
|
|
418
|
-
} ? Q : any>;
|
|
419
|
-
/**
|
|
420
|
-
* Global ambient registry of typed routes, populated by `kick typegen`.
|
|
421
|
-
*
|
|
422
|
-
* Each interface inside `KickRoutes` corresponds to a controller class;
|
|
423
|
-
* each property is one route method on that controller. The values
|
|
424
|
-
* conform to `RouteShape`.
|
|
425
|
-
*
|
|
426
|
-
* Empty by default — declarations come from `.kickjs/types/routes.d.ts`
|
|
427
|
-
* generated alongside the rest of the typegen output.
|
|
428
|
-
*/
|
|
429
|
-
declare global {
|
|
430
|
-
namespace KickRoutes {}
|
|
431
|
-
} //# sourceMappingURL=context.d.ts.map
|
|
432
|
-
//#endregion
|
|
433
|
-
export { RouteShape as i, DeepReadonly as n, RequestContext as r, Ctx as t };
|
|
434
|
-
//# sourceMappingURL=context-Dnt2Di7p.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-Dnt2Di7p.d.mts","names":[],"sources":["../src/http/context.ts"],"mappings":";;;;;;;;;AAUgB;;;KAOX,YAAA,GAAe,IAAI,CAAC,cAAA;AAAc;AAAA;;;;;;;;;;;;;;;;;;;;;;AAAA,UAyB7B,aAAA;EAAA,CACP,KAAA,EAAO,cAAA,GAAiB,QAAA;EAsBgC;EApBzD,UAAA,CAAW,KAAA,GAAQ,YAAA,GAAe,QAAA;EAFjC;EAID,YAAA,CAAa,KAAA,GAAQ,YAAA,GAAe,QAAA;EAFpC;EAIA,SAAA,CAAU,KAAA,GAAQ,YAAA,GAAe,QAAA;EAJtB;EAMX,QAAA,CAAS,KAAA,GAAQ,YAAA,GAAe,QAAA;EAJhC;EAMA,QAAA,CAAS,KAAA,GAAQ,YAAA,GAAe,QAAA;EANnB;EAQb,aAAA,CAAc,KAAA,GAAQ,YAAA,GAAe,QAAA;EANrC;EAQA,eAAA,CAAgB,KAAA,GAAQ,YAAA,GAAe,QAAA;EAR7B;EAUV,QAAA,CAAS,KAAA,GAAQ,YAAA,GAAe,QAAA;EARhC;;;;;EAcA,UAAA,CAAW,MAAA,SAAe,KAAA,GAAQ,YAAA,GAAe,QAAA;AAAA;;;;;;;;;;;;;;;;;;;;KAsBvC,YAAA,MAAkB,CAAA,cAAc,IAAA,yBACxC,CAAA,GACA,CAAA,SAAU,IAAA,GAAO,MAAA,GACf,CAAA,GACA,CAAA,SAAU,GAAA,qBACR,WAAA,CAAY,YAAA,CAAa,CA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gB,EAAA;IAMhC,OAAA,GAAO,IAAA;IAIP,OAAA,GAAO,EAAA;IAIP,KAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;;KA0BM,GAAA,gBAAmB,UAAA,GAAa,UAAA,IAAc,cAAA,CACxD,MAAA;EAAiB,IAAA;AAAA,IAAkB,CAAA,QACnC,MAAA;EAAiB,MAAA;AAAA,IAAoB,CAAA,QACrC,MAAA;EAAiB,KAAA;AAAA,IAAmB,CAAA;;;;;;;;;;;QAa9B,MAAA;EAAA,UAEI,UAAU;AAAA"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v5.16.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{normalizeProblem}from"./core/errors.mjs";import{i as parseQuery}from"./query-D-FiLfmd.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const signalControllerKey=Symbol.for(`kickjs.requestContext.signalController`),readOnlyProxyCacheKey=Symbol.for(`kickjs.requestContext.readOnlyProxyCache`);function isPlainObjectOrArray(v){if(typeof v!=`object`||!v)return!1;if(Array.isArray(v))return!0;let proto=Object.getPrototypeOf(v);return proto===Object.prototype||proto===null}function makeReadOnlyProxy(target,req,label){if(process.env.NODE_ENV===`production`||!isPlainObjectOrArray(target))return target;let reqObj=req,cache=reqObj[readOnlyProxyCacheKey];cache||(cache=new WeakMap,reqObj[readOnlyProxyCacheKey]=cache);let targetObj=target,cached=cache.get(targetObj);if(cached)return cached;let warnWrite=(verb,prop)=>{console.warn(`[kickjs] Attempted to ${verb} \`ctx.${label}.${String(prop)}\` — request data is read-only. Stash computed values via \`ctx.set('key', value)\` or a Context Contributor, or reach \`ctx.req.${label}\` if you genuinely need the raw mutable handle.`)},proxy=new Proxy(targetObj,{get(t,prop,receiver){let value=Reflect.get(t,prop,receiver);return isPlainObjectOrArray(value)?makeReadOnlyProxy(value,req,`${label}.${String(prop)}`):value},set(_t,prop){return warnWrite(`assign`,prop),!0},deleteProperty(_t,prop){return warnWrite(`delete`,prop),!0},defineProperty(_t,prop){return warnWrite(`Object.defineProperty on`,prop),!0}});return cache.set(targetObj,proxy),proxy}var RequestContext=class{req;res;next;constructor(req,res,next){this.req=req,this.res=res,this.next=next}metadataReadOnly(){return requestStore.getStore()?.values??null}metadataForWrite(){let store=requestStore.getStore();if(store)return store.values;throw Error(`RequestContext.set called outside an AsyncLocalStorage frame. Mount requestScopeMiddleware() before constructing RequestContext, or wrap test setup in requestStore.run({ requestId, instances: new Map(), values: new Map() }, () => ...).`)}get body(){return makeReadOnlyProxy(this.req.body,this.req,`body`)}get params(){return makeReadOnlyProxy(this.req.params,this.req,`params`)}get query(){return makeReadOnlyProxy(this.req.query,this.req,`query`)}get headers(){return makeReadOnlyProxy(this.req.headers,this.req,`headers`)}get requestId(){return this.req.requestId??this.req.headers[`x-request-id`]}get signal(){let req=this.req,cached=req[signalControllerKey];if(cached)return cached.signal;let ctrl=new AbortController;req[signalControllerKey]=ctrl;let abort=()=>ctrl.abort(`request closed`);return this.req.once(`close`,abort),this.res.once(`close`,abort),ctrl.signal}get session(){return this.req.session}get user(){return this.metadataReadOnly()?.get(`user`)??this.req.user}get tenantId(){return this.user?.tenantId}get roles(){let u=this.user;return u?.tenantRoles??u?.roles??[]}qs(fieldConfig){return parseQuery(this.req.query,fieldConfig)}get file(){let f=this.req.file;return f?makeReadOnlyProxy(f,this.req,`file`):void 0}get files(){let f=this.req.files;if(Array.isArray(f))return makeReadOnlyProxy(f,this.req,`files`)}get(key){return this.metadataReadOnly()?.get(key)}set(key,value){this.metadataForWrite().set(key,value)}json(data,status=200){return this.res.status(status).json(data)}created(data){return this.res.status(201).json(data)}noContent(){return this.res.status(204).end()}notFound(message=`Not Found`){return this.res.status(404).json({message})}badRequest(message){return this.res.status(400).json({message})}get problem(){let send=input=>this.sendProblem(input);return send.badRequest=(input={})=>this.sendProblem({status:400,...input}),send.unauthorized=(input={})=>this.sendProblem({status:401,...input}),send.forbidden=(input={})=>this.sendProblem({status:403,...input}),send.notFound=(input={})=>this.sendProblem({status:404,...input}),send.conflict=(input={})=>this.sendProblem({status:409,...input}),send.unprocessable=(input={})=>this.sendProblem({status:422,...input}),send.tooManyRequests=(input={})=>this.sendProblem({status:429,...input}),send.internal=(input={})=>this.sendProblem({status:500,...input}),send.validation=(issues,input={})=>{let errors=(issues||[]).map(issue=>({field:issue.path?.join?.(`.`)??``,message:issue.message??``,code:issue.code}));return this.sendProblem({status:422,detail:issues?.[0]?.message,...input,errors})},send}sendProblem(input){let body=normalizeProblem(input);return this.res.setHeader(`Content-Type`,`application/problem+json`),this.res.status(body.status).json(body)}html(content,status=200){return this.res.status(status).type(`html`).send(content)}download(buffer,filename,contentType=`application/octet-stream`){return this.res.setHeader(`Content-Disposition`,`attachment; filename="${filename}"`),this.res.setHeader(`Content-Type`,contentType),this.res.send(buffer)}render(template,data={}){return this.res.render(template,data)}async paginate(fetcher,fieldConfig){let parsed=this.qs(fieldConfig),{data,total}=await fetcher(parsed),{page,limit}=parsed.pagination,totalPages=Math.ceil(total/limit)||1,response={data,meta:{page,limit,total,totalPages,hasNext:page<totalPages,hasPrev:page>1}};return this.json(response)}sse(){this.res.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}),this.res.flushHeaders();let closeCallbacks=[];return this.req.on(`close`,()=>{for(let cb of closeCallbacks)cb()}),{send:(data,event,id)=>{id&&this.res.write(`id: ${id}\n`),event&&this.res.write(`event: ${event}\n`),this.res.write(`data: ${JSON.stringify(data)}\n\n`)},comment:text=>{this.res.write(`: ${text}\n\n`)},onClose:fn=>{closeCallbacks.push(fn)},close:()=>{this.res.end()}}}};export{requestStore as i,getRequestStore as n,getRequestValue as r,RequestContext as t};
|
|
12
|
-
//# sourceMappingURL=context-MD7Mc_o_.mjs.map
|