@forinda/kickjs 10.1.0 → 10.2.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-C5I5e_-i.d.mts +4866 -0
- package/dist/adapter-C5I5e_-i.d.mts.map +1 -0
- package/dist/allowed-hosts-D6qcuK5I.d.mts +46 -0
- package/dist/allowed-hosts-D6qcuK5I.d.mts.map +1 -0
- package/dist/{app-module-DCA65GZZ.d.mts → app-module-Ftz6m7SO.d.mts} +8 -2
- package/dist/app-module-Ftz6m7SO.d.mts.map +1 -0
- package/dist/application-Ch5jT4fj.mjs +14 -0
- package/dist/application-Ch5jT4fj.mjs.map +1 -0
- package/dist/bootstrap-D56HIq1N.mjs +12 -0
- package/dist/{bootstrap-BdyBlBMe.mjs.map → bootstrap-D56HIq1N.mjs.map} +1 -1
- package/dist/bounded-counters-B9dzk5o_.mjs +12 -0
- package/dist/bounded-counters-B9dzk5o_.mjs.map +1 -0
- package/dist/breach-padding-C-Dnq8CS.d.mts +39 -0
- package/dist/breach-padding-C-Dnq8CS.d.mts.map +1 -0
- package/dist/{client-ip-BbLDp03S.mjs → client-ip-lYnBU2PR.mjs} +2 -2
- package/dist/{client-ip-BbLDp03S.mjs.map → client-ip-lYnBU2PR.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/config-BfImCyaG.mjs +12 -0
- package/dist/{config-CJiGeOca.mjs.map → config-BfImCyaG.mjs.map} +1 -1
- package/dist/{container-CS9v9UFU.mjs → container-C2aTj8Cb.mjs} +3 -3
- package/dist/{container-CS9v9UFU.mjs.map → container-C2aTj8Cb.mjs.map} +1 -1
- package/dist/context-C6iKf9hN.mjs +12 -0
- package/dist/context-C6iKf9hN.mjs.map +1 -0
- package/dist/{context-errors-7C5TBYn7.mjs → context-errors-6psUheqc.mjs} +2 -2
- package/dist/{context-errors-7C5TBYn7.mjs.map → context-errors-6psUheqc.mjs.map} +1 -1
- package/dist/{contributor-runner-DBpRR5dl.mjs → contributor-runner-Bn-ipSS5.mjs} +3 -3
- package/dist/{contributor-runner-DBpRR5dl.mjs.map → contributor-runner-Bn-ipSS5.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/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-CFXpwc7m.mjs +12 -0
- package/dist/{core-B0JmdBvX.mjs.map → core-CFXpwc7m.mjs.map} +1 -1
- package/dist/{cors-CsibNTQ6.d.mts → cors-2Bwhyhpt.d.mts} +4 -1
- package/dist/{cors-CsibNTQ6.d.mts.map → cors-2Bwhyhpt.d.mts.map} +1 -1
- package/dist/csrf-C3RRSCMs.mjs +12 -0
- package/dist/csrf-C3RRSCMs.mjs.map +1 -0
- package/dist/{csrf-C73UkRgc.d.mts → csrf-Cy1meSpf.d.mts} +27 -3
- package/dist/csrf-Cy1meSpf.d.mts.map +1 -0
- package/dist/decorate-DkxaoRo5.mjs +13 -0
- package/dist/decorate-DkxaoRo5.mjs.map +1 -0
- package/dist/{decorators-BxNSz9Qt.d.mts → decorators-DaQUNXOn.d.mts} +2 -2
- package/dist/{decorators-BxNSz9Qt.d.mts.map → decorators-DaQUNXOn.d.mts.map} +1 -1
- package/dist/{define-adapter-BLKlUbSL.mjs → define-adapter-BRJ6lXkV.mjs} +2 -2
- package/dist/{define-adapter-BLKlUbSL.mjs.map → define-adapter-BRJ6lXkV.mjs.map} +1 -1
- package/dist/{disposables-CuY2S3bw.mjs → disposables-5nFqc1aC.mjs} +2 -2
- package/dist/{disposables-CuY2S3bw.mjs.map → disposables-5nFqc1aC.mjs.map} +1 -1
- package/dist/errors-By6UueCm.d.mts.map +1 -1
- package/dist/handler-Dl_1fGxE.mjs +12 -0
- package/dist/handler-Dl_1fGxE.mjs.map +1 -0
- package/dist/{helmet-C2QEU6S-.d.mts → helmet-CEOmo516.d.mts} +4 -1
- package/dist/helmet-CEOmo516.d.mts.map +1 -0
- package/dist/host-DTQ5pZgg.mjs +12 -0
- package/dist/host-DTQ5pZgg.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/allowed-hosts.d.mts +3 -0
- package/dist/http/middleware/allowed-hosts.mjs +12 -0
- package/dist/http/middleware/allowed-hosts.mjs.map +1 -0
- package/dist/http/middleware/breach-padding.d.mts +3 -0
- package/dist/http/middleware/breach-padding.mjs +12 -0
- package/dist/http/middleware/breach-padding.mjs.map +1 -0
- package/dist/http/middleware/cors.d.mts +1 -1
- package/dist/http/middleware/cors.mjs +2 -2
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.d.mts +2 -2
- 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.d.mts +1 -1
- package/dist/http/middleware/helmet.mjs +2 -2
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.d.mts +2 -2
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.mjs +2 -2
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +2 -2
- 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 +2 -2
- package/dist/http/middleware/validate.d.mts +2 -2
- package/dist/http/middleware/validate.mjs +2 -2
- package/dist/http/middleware/validate.mjs.map +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 +5 -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.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- 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-CNHSbZTE.d.mts → index-CuiWSnZL.d.mts} +3 -2
- package/dist/index-CuiWSnZL.d.mts.map +1 -0
- package/dist/index.d.mts +16 -18
- package/dist/index.mjs +6 -2
- package/dist/index.mjs.map +1 -1
- package/dist/is-production-tnFh6NCj.mjs +12 -0
- package/dist/is-production-tnFh6NCj.mjs.map +1 -0
- package/dist/{jobs-BQ4t3TAb.mjs → jobs-lLcPhIqq.mjs} +3 -3
- package/dist/{jobs-BQ4t3TAb.mjs.map → jobs-lLcPhIqq.mjs.map} +1 -1
- package/dist/kv-stores-_wz4DEiw.mjs +12 -0
- package/dist/kv-stores-_wz4DEiw.mjs.map +1 -0
- package/dist/{metadata-zvd6AWkE.mjs → metadata-Tc6jhIBi.mjs} +2 -2
- package/dist/{metadata-zvd6AWkE.mjs.map → metadata-Tc6jhIBi.mjs.map} +1 -1
- package/dist/{observers-DZgs48UM.mjs → observers-IGga6yut.mjs} +2 -2
- package/dist/{observers-DZgs48UM.mjs.map → observers-IGga6yut.mjs.map} +1 -1
- package/dist/{query-B_k9qn0R.mjs → query-AnbWMCd6.mjs} +2 -2
- package/dist/{query-B_k9qn0R.mjs.map → query-AnbWMCd6.mjs.map} +1 -1
- package/dist/{rate-limit-Bwed3jOV.d.mts → rate-limit-BgoeahE5.d.mts} +17 -2
- package/dist/rate-limit-BgoeahE5.d.mts.map +1 -0
- package/dist/reply-DjysdCPI.mjs +12 -0
- package/dist/reply-DjysdCPI.mjs.map +1 -0
- package/dist/respond-vPZlRnZR.mjs +12 -0
- package/dist/respond-vPZlRnZR.mjs.map +1 -0
- package/dist/{route-flag-BWuvJsGZ.mjs → route-flag-BjRpxryx.mjs} +3 -3
- package/dist/{route-flag-BWuvJsGZ.mjs.map → route-flag-BjRpxryx.mjs.map} +1 -1
- package/dist/{route-policy-B3vM6bSf.mjs → route-policy-Pffte5M1.mjs} +2 -2
- package/dist/{route-policy-B3vM6bSf.mjs.map → route-policy-Pffte5M1.mjs.map} +1 -1
- package/dist/{router-builder-JvMTp50k.mjs → router-builder-CrWKq6O2.mjs} +3 -3
- package/dist/router-builder-CrWKq6O2.mjs.map +1 -0
- package/dist/{session-B4hOZj90.d.mts → session-ChXx7jG5.d.mts} +31 -4
- package/dist/session-ChXx7jG5.d.mts.map +1 -0
- package/dist/settings-C8VKewNS.d.mts +119 -0
- package/dist/settings-C8VKewNS.d.mts.map +1 -0
- package/dist/settings-CFtEAQUs.mjs +14 -0
- package/dist/settings-CFtEAQUs.mjs.map +1 -0
- package/dist/{upload-config-Dz2INCaa.mjs → upload-config-DLgt4l7F.mjs} +2 -2
- package/dist/{upload-config-Dz2INCaa.mjs.map → upload-config-DLgt4l7F.mjs.map} +1 -1
- package/dist/url-for-Cyh7pJCb.mjs +12 -0
- package/dist/url-for-Cyh7pJCb.mjs.map +1 -0
- package/dist/validate-CzjCbRUn.d.mts +53 -0
- package/dist/validate-CzjCbRUn.d.mts.map +1 -0
- package/dist/web.d.mts +19 -19
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +14 -1
- package/dist/adapter-ClEh-Oos.d.mts +0 -2134
- package/dist/adapter-ClEh-Oos.d.mts.map +0 -1
- package/dist/app-module-DCA65GZZ.d.mts.map +0 -1
- package/dist/application-Dv514EeR.mjs +0 -12
- package/dist/application-Dv514EeR.mjs.map +0 -1
- package/dist/application-oIPzgjfk.d.mts +0 -1589
- package/dist/application-oIPzgjfk.d.mts.map +0 -1
- package/dist/bootstrap-BdyBlBMe.mjs +0 -12
- package/dist/config-CJiGeOca.mjs +0 -12
- package/dist/context-CtL9RxXp.mjs +0 -12
- package/dist/context-CtL9RxXp.mjs.map +0 -1
- package/dist/core-B0JmdBvX.mjs +0 -12
- package/dist/csrf--1t4qDov.mjs +0 -12
- package/dist/csrf--1t4qDov.mjs.map +0 -1
- package/dist/csrf-C73UkRgc.d.mts.map +0 -1
- package/dist/decorate-BHkdkV4l.mjs +0 -11
- package/dist/env-BwzF9MkZ.mjs +0 -13
- package/dist/env-BwzF9MkZ.mjs.map +0 -1
- package/dist/error-handler-BB9wAElm.d.mts +0 -63
- package/dist/error-handler-BB9wAElm.d.mts.map +0 -1
- package/dist/handler-zKfIgNo4.mjs +0 -13
- package/dist/handler-zKfIgNo4.mjs.map +0 -1
- package/dist/helmet-C2QEU6S-.d.mts.map +0 -1
- package/dist/index-CNHSbZTE.d.mts.map +0 -1
- package/dist/kv-stores-Co5k2PYA.d.mts +0 -367
- package/dist/kv-stores-Co5k2PYA.d.mts.map +0 -1
- package/dist/kv-stores-DsfVy2fk.mjs +0 -12
- package/dist/kv-stores-DsfVy2fk.mjs.map +0 -1
- package/dist/module-registry-Daf_P2oD.mjs +0 -12
- package/dist/module-registry-Daf_P2oD.mjs.map +0 -1
- package/dist/rate-limit-Bwed3jOV.d.mts.map +0 -1
- package/dist/reply-BDK9xt7Z.mjs +0 -12
- package/dist/reply-BDK9xt7Z.mjs.map +0 -1
- package/dist/respond-DFRj2-7q.mjs +0 -12
- package/dist/respond-DFRj2-7q.mjs.map +0 -1
- package/dist/router-builder-JvMTp50k.mjs.map +0 -1
- package/dist/router-builder-zWuVIOmd.d.mts +0 -56
- package/dist/router-builder-zWuVIOmd.d.mts.map +0 -1
- package/dist/session-B4hOZj90.d.mts.map +0 -1
- package/dist/upload-CiMtdXWD.d.mts +0 -104
- package/dist/upload-CiMtdXWD.d.mts.map +0 -1
- package/dist/validate-DMYpUnrf.d.mts +0 -25
- package/dist/validate-DMYpUnrf.d.mts.map +0 -1
|
@@ -0,0 +1,4866 @@
|
|
|
1
|
+
|
|
2
|
+
import { s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
|
|
3
|
+
import { i as SettingsDeclaration, s as VarOrigin, t as ConfigVar } from "./settings-C8VKewNS.mjs";
|
|
4
|
+
import { i as Constructor, o as MaybePromise } from "./interfaces-C1hCSoLD.mjs";
|
|
5
|
+
import { g as FileUploadConfig, k as RouteDefinition, o as BaseUploadOptions, x as MiddlewareHandler } from "./decorators-DaQUNXOn.mjs";
|
|
6
|
+
import "./index-CuiWSnZL.mjs";
|
|
7
|
+
import { d as RouteFlagTest, p as RouteFlags, s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
|
|
8
|
+
import { C as MetaValue, S as ExecutionContext, c as ContextDecorator, h as DepValue, m as ContributorRegistrations, o as AnyContributorRegistration, r as AppModuleEntry, t as AppModule, u as ContextDecoratorSpec, x as ContextMetaKey } from "./app-module-Ftz6m7SO.mjs";
|
|
9
|
+
import "./cache-C0qL0NSD.mjs";
|
|
10
|
+
import { i as ProblemDetails } from "./errors-By6UueCm.mjs";
|
|
11
|
+
import { t as ValidationErrorFactory } from "./validate-CzjCbRUn.mjs";
|
|
12
|
+
import { t as AllowedHostsOptions } from "./allowed-hosts-D6qcuK5I.mjs";
|
|
13
|
+
import "./request-id-CVzJ1uHD.mjs";
|
|
14
|
+
import "./csrf-Cy1meSpf.mjs";
|
|
15
|
+
import "./helmet-CEOmo516.mjs";
|
|
16
|
+
import "./breach-padding-C-Dnq8CS.mjs";
|
|
17
|
+
import "./cors-2Bwhyhpt.mjs";
|
|
18
|
+
import { r as RateLimitStore } from "./rate-limit-BgoeahE5.mjs";
|
|
19
|
+
import { a as SessionStore, n as Session, r as SessionData } from "./session-ChXx7jG5.mjs";
|
|
20
|
+
import { S as QueryFieldConfig, T as TypedParsedQuery, t as ParseQueryOptions, v as PaginatedResponse } from "./index-BfT5KZ-M.mjs";
|
|
21
|
+
import "reflect-metadata";
|
|
22
|
+
import http, { IncomingMessage, ServerResponse } from "node:http";
|
|
23
|
+
import https from "node:https";
|
|
24
|
+
import http2 from "node:http2";
|
|
25
|
+
import tls from "node:tls";
|
|
26
|
+
import { ErrorRequestHandler, Express as Express$1, NextFunction, Request as Request$1, RequestHandler, Response as Response$1, Router } from "express";
|
|
27
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
28
|
+
import { Options } from "multer";
|
|
29
|
+
//#region src/core/adapter-conditions.d.ts
|
|
30
|
+
/**
|
|
31
|
+
* `true` keeps the adapter; `false` or a string (the reason) leaves it out.
|
|
32
|
+
* Runs once at startup — keep it synchronous and free of side effects.
|
|
33
|
+
*/
|
|
34
|
+
type AdapterCondition = () => boolean | string;
|
|
35
|
+
/** One adapter's outcome, as `app.getConditionReport()` lists it. */
|
|
36
|
+
interface ConditionOutcome {
|
|
37
|
+
adapter: string;
|
|
38
|
+
enabled: boolean;
|
|
39
|
+
/** Why it was left out; absent when enabled. */
|
|
40
|
+
reason?: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* On when the env variable is set (non-empty) — or equals `value`.
|
|
44
|
+
*
|
|
45
|
+
* when: onEnv('REDIS_URL')
|
|
46
|
+
* when: onEnv('QUEUE_DRIVER', 'redis')
|
|
47
|
+
*/
|
|
48
|
+
declare function onEnv(name: string, value?: string): AdapterCondition;
|
|
49
|
+
/**
|
|
50
|
+
* On when the app can import `name` — for an adapter that needs an optional
|
|
51
|
+
* dependency.
|
|
52
|
+
*
|
|
53
|
+
* when: onPackage('ioredis')
|
|
54
|
+
*/
|
|
55
|
+
declare function onPackage(name: string): AdapterCondition;
|
|
56
|
+
/** On only when every condition is — the first that fails gives the reason. */
|
|
57
|
+
declare function allOf(...conditions: AdapterCondition[]): AdapterCondition;
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/core/failure-analysis.d.ts
|
|
60
|
+
/**
|
|
61
|
+
* Turn a startup failure into advice: what went wrong in words, and what to
|
|
62
|
+
* change — instead of a driver's stack trace that names a socket.
|
|
63
|
+
*
|
|
64
|
+
* @module @forinda/kickjs/core/failure-analysis
|
|
65
|
+
*/
|
|
66
|
+
/** What an analyzer says about an error it recognises. */
|
|
67
|
+
interface FailureAdvice {
|
|
68
|
+
summary: string;
|
|
69
|
+
cause?: string;
|
|
70
|
+
fix: string;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/core/observers.d.ts
|
|
74
|
+
/** Where an error came from. Integrations may report their own sources. */
|
|
75
|
+
type ErrorSource = 'request' | 'uncaught' | 'unhandled-rejection' | 'background' | 'job' | (string & {});
|
|
76
|
+
interface ErrorInfo {
|
|
77
|
+
source: ErrorSource;
|
|
78
|
+
requestId?: string;
|
|
79
|
+
method?: string;
|
|
80
|
+
/** The request URL path, as received. */
|
|
81
|
+
path?: string;
|
|
82
|
+
/** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */
|
|
83
|
+
route?: string;
|
|
84
|
+
/** The status the error was answered with, for request errors. */
|
|
85
|
+
status?: number;
|
|
86
|
+
/** Anything else the reporter knows — a queue and job name, a cron schedule. */
|
|
87
|
+
context?: Record<string, unknown>;
|
|
88
|
+
}
|
|
89
|
+
interface ResponseInfo {
|
|
90
|
+
method: string;
|
|
91
|
+
path: string;
|
|
92
|
+
/** The matched route pattern, or undefined when no route matched (404s). */
|
|
93
|
+
route?: string;
|
|
94
|
+
status: number;
|
|
95
|
+
durationMs: number;
|
|
96
|
+
requestId?: string;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Report an error to every observer. The framework calls this for request
|
|
100
|
+
* errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and
|
|
101
|
+
* queue job failures; call it from your own integrations too (a cron runner,
|
|
102
|
+
* a message consumer). Never throws.
|
|
103
|
+
*/
|
|
104
|
+
declare function reportError(error: unknown, info: ErrorInfo): void;
|
|
105
|
+
/** Report a finished response to every observer. Never throws. */
|
|
106
|
+
declare function reportResponse(info: ResponseInfo): void;
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/core/introspect.d.ts
|
|
109
|
+
/**
|
|
110
|
+
* Per-primitive introspection snapshot — the JSON shape an adapter or
|
|
111
|
+
* plugin's optional `introspect()` hook returns for DevTools.
|
|
112
|
+
*
|
|
113
|
+
* Lives in `@forinda/kickjs` (not `@forinda/kickjs-devtools-kit`) so
|
|
114
|
+
* adopters can type their `introspect()` return without taking on a
|
|
115
|
+
* dep on the kit just to satisfy the contract. The kit's own
|
|
116
|
+
* `IntrospectionSnapshot` type is structurally identical and continues
|
|
117
|
+
* to be the canonical doc location for DevTools-side consumers; the
|
|
118
|
+
* two stay in lockstep — if a field is added on one side it MUST be
|
|
119
|
+
* added on the other (covered by the type-equivalence test in the
|
|
120
|
+
* devtools-kit package).
|
|
121
|
+
*
|
|
122
|
+
* Cheap-by-default principle: `state` and `metrics` should be O(1) to
|
|
123
|
+
* compute (counters, flags, recent samples). Anything that requires a
|
|
124
|
+
* DB round trip or a full DI graph walk belongs behind a separate
|
|
125
|
+
* explicit RPC — DevTools polls topology aggressively.
|
|
126
|
+
*/
|
|
127
|
+
interface IntrospectionSnapshot {
|
|
128
|
+
/**
|
|
129
|
+
* Wire-protocol version this snapshot conforms to. The kit ships a
|
|
130
|
+
* `PROTOCOL_VERSION` constant typed as the literal `1`; we mirror
|
|
131
|
+
* that literal here so structural parity is enforced both ways —
|
|
132
|
+
* an adopter who writes `protocolVersion: 1` satisfies both this
|
|
133
|
+
* type and the kit's `IntrospectionSnapshot`. Bumping is a
|
|
134
|
+
* coordinated kit + framework release; widen this literal in
|
|
135
|
+
* lockstep.
|
|
136
|
+
*/
|
|
137
|
+
protocolVersion: 1;
|
|
138
|
+
/** Stable identity matching the `name` from `definePlugin` / `defineAdapter`. */
|
|
139
|
+
name: string;
|
|
140
|
+
/** Discriminator for what kind of primitive this is. */
|
|
141
|
+
kind: IntrospectionKind;
|
|
142
|
+
/** Optional version string from the plugin / adapter metadata. */
|
|
143
|
+
version?: string;
|
|
144
|
+
/**
|
|
145
|
+
* Reactive state surface — JSON-serialisable snapshot. Keep small
|
|
146
|
+
* (under a few KB) so polling stays cheap.
|
|
147
|
+
*/
|
|
148
|
+
state?: Record<string, unknown>;
|
|
149
|
+
/** DI tokens this primitive registers (`provides`) or consumes (`requires`). */
|
|
150
|
+
tokens?: {
|
|
151
|
+
provides: readonly string[];
|
|
152
|
+
requires: readonly string[];
|
|
153
|
+
};
|
|
154
|
+
/**
|
|
155
|
+
* Per-instance counters — active connections, in-flight jobs, cached
|
|
156
|
+
* items, etc. Numbers only so the DevTools panel can chart trends.
|
|
157
|
+
*/
|
|
158
|
+
metrics?: Record<string, number>;
|
|
159
|
+
/** Self-reported memory footprint estimate, in bytes. Optional. */
|
|
160
|
+
memoryBytes?: number;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* What kind of primitive an introspection snapshot describes. Matches
|
|
164
|
+
* the kit's `IntrospectionKind` and the routing the topology aggregator
|
|
165
|
+
* does when bucketing adapters vs plugins vs middleware vs contributor
|
|
166
|
+
* primitives.
|
|
167
|
+
*/
|
|
168
|
+
type IntrospectionKind = 'plugin' | 'adapter' | 'middleware' | 'contributor';
|
|
169
|
+
/**
|
|
170
|
+
* Convenience function signature for adopter-side helpers that return
|
|
171
|
+
* a complete snapshot. Used by the optional `introspect?()` hook on
|
|
172
|
+
* `AppAdapter` and `KickPlugin`.
|
|
173
|
+
*/
|
|
174
|
+
type IntrospectFn = () => IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
|
|
175
|
+
//#endregion
|
|
176
|
+
//#region src/core/augmentation.d.ts
|
|
177
|
+
/**
|
|
178
|
+
* The canonical `KickJsPluginRegistry` interface that `kick typegen`
|
|
179
|
+
* augments, for typed `dependsOn` between plugins and adapters.
|
|
180
|
+
*
|
|
181
|
+
* See `architecture.md` §21.2.1 (typegen for `dependsOn`) and §21.3.3
|
|
182
|
+
* (standardized augmentation registry) for the design rationale.
|
|
183
|
+
*
|
|
184
|
+
* @module @forinda/kickjs/core/augmentation
|
|
185
|
+
*/
|
|
186
|
+
/**
|
|
187
|
+
* Marker interface that lists every plugin/adapter in the project. The
|
|
188
|
+
* keys are the literal `name` field passed to `defineAdapter` /
|
|
189
|
+
* `definePlugin` (or declared on a `class implements AppAdapter`); the
|
|
190
|
+
* values are the kind tag (`'plugin' | 'adapter'`).
|
|
191
|
+
*
|
|
192
|
+
* The framework ships this empty. `kick typegen` augments it from
|
|
193
|
+
* source so `keyof KickJsPluginRegistry` resolves to a string-literal
|
|
194
|
+
* union of every name in scope — and therefore so do `dependsOn`
|
|
195
|
+
* declarations on plugins/adapters.
|
|
196
|
+
*/
|
|
197
|
+
interface KickJsPluginRegistry {}
|
|
198
|
+
/**
|
|
199
|
+
* Resolves to a string-literal union of every registered plugin/adapter
|
|
200
|
+
* name when the project's typegen has populated `KickJsPluginRegistry`,
|
|
201
|
+
* or to `string` when the registry is empty (no typegen pass yet).
|
|
202
|
+
*
|
|
203
|
+
* Falling back to `string` keeps fresh projects compiling — the typegen
|
|
204
|
+
* narrowing is a progressive enhancement, not a hard prerequisite.
|
|
205
|
+
*/
|
|
206
|
+
type KickJsPluginName = keyof KickJsPluginRegistry extends never ? string : keyof KickJsPluginRegistry & string;
|
|
207
|
+
//#endregion
|
|
208
|
+
//#region src/core/module-registry.d.ts
|
|
209
|
+
/**
|
|
210
|
+
* Imperative receiver passed to {@link KickPlugin.setup} and the
|
|
211
|
+
* top-level `bootstrap({ setup })` callback so adopters can register
|
|
212
|
+
* modules conditionally — based on env flags, runtime config,
|
|
213
|
+
* tenant lists, etc. — instead of being limited to the static
|
|
214
|
+
* `modules: [...]` array.
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* ```ts
|
|
218
|
+
* bootstrap({
|
|
219
|
+
* modules: [HelloModule()], // static — always mounted
|
|
220
|
+
* setup(registry) {
|
|
221
|
+
* if (env.ENABLE_ADMIN) registry.mount(AdminModule())
|
|
222
|
+
* for (const tenant of env.TENANTS) {
|
|
223
|
+
* registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))
|
|
224
|
+
* }
|
|
225
|
+
* },
|
|
226
|
+
* })
|
|
227
|
+
* ```
|
|
228
|
+
*
|
|
229
|
+
* **Currently exposes only `.mount(module)` — the HTTP-feature path.**
|
|
230
|
+
* A future `.use(module)` for non-HTTP modules (queues, cron, workers,
|
|
231
|
+
* DI-only seeds) is planned but not yet implemented; existing non-HTTP
|
|
232
|
+
* modules continue returning `null` from `routes()` and registering
|
|
233
|
+
* via `.mount()`.
|
|
234
|
+
*
|
|
235
|
+
* Same dispatch rules as the static `modules: [...]` array — class
|
|
236
|
+
* entries get `new`-ed at boot, `defineModule` factory output is used
|
|
237
|
+
* directly. The registry doesn't validate the entry shape itself; the
|
|
238
|
+
* Application loader does the typeof discrimination at mount time.
|
|
239
|
+
*/
|
|
240
|
+
interface ModuleRegistry {
|
|
241
|
+
/**
|
|
242
|
+
* Register a module for the full HTTP lifecycle: `register()` runs,
|
|
243
|
+
* `import.meta.glob` decorator side-effects fire, `routes()` is
|
|
244
|
+
* called and its result mounted, `contributors()` are merged at
|
|
245
|
+
* `'module'` precedence and applied to the mounted routes.
|
|
246
|
+
*
|
|
247
|
+
* Modules are mounted in registration order (first call → first
|
|
248
|
+
* mount). Order across sources is: plugin static modules → plugin
|
|
249
|
+
* `setup()` calls → user static modules → user `setup()` callback.
|
|
250
|
+
*/
|
|
251
|
+
mount(module: AppModuleEntry): void;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Internal collector implementing {@link ModuleRegistry}. Application
|
|
255
|
+
* passes one of these to every `setup()` callback during bootstrap;
|
|
256
|
+
* the collected `entries` array is then run through the same
|
|
257
|
+
* class-vs-instance dispatch as the static `modules: [...]` array.
|
|
258
|
+
*
|
|
259
|
+
* Not exported from the public surface — adopters interact only
|
|
260
|
+
* through the {@link ModuleRegistry} interface.
|
|
261
|
+
*/
|
|
262
|
+
declare class MutableModuleRegistry implements ModuleRegistry {
|
|
263
|
+
readonly entries: AppModuleEntry[];
|
|
264
|
+
mount(module: AppModuleEntry): void;
|
|
265
|
+
}
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/core/plugin.d.ts
|
|
268
|
+
/**
|
|
269
|
+
* Plugin interface for extending KickJS applications.
|
|
270
|
+
*
|
|
271
|
+
* Plugins bundle modules, adapters, middleware, and DI bindings into a single
|
|
272
|
+
* reusable unit. They run before the application bootstraps, so they can
|
|
273
|
+
* register services and configure the app before any module loads.
|
|
274
|
+
*
|
|
275
|
+
* @example
|
|
276
|
+
* ```ts
|
|
277
|
+
* import type { KickPlugin } from '@forinda/kickjs'
|
|
278
|
+
*
|
|
279
|
+
* export class CorsPlugin implements KickPlugin {
|
|
280
|
+
* name = 'CorsPlugin'
|
|
281
|
+
*
|
|
282
|
+
* middleware() {
|
|
283
|
+
* return [cors({ origin: '*' })]
|
|
284
|
+
* }
|
|
285
|
+
* }
|
|
286
|
+
*
|
|
287
|
+
* // Usage:
|
|
288
|
+
* bootstrap({
|
|
289
|
+
* modules,
|
|
290
|
+
* plugins: [new CorsPlugin()],
|
|
291
|
+
* })
|
|
292
|
+
* ```
|
|
293
|
+
*
|
|
294
|
+
* @example
|
|
295
|
+
* ```ts
|
|
296
|
+
* // A more complex plugin that bundles modules and adapters
|
|
297
|
+
* export class AuthPlugin implements KickPlugin {
|
|
298
|
+
* name = 'AuthPlugin'
|
|
299
|
+
*
|
|
300
|
+
* constructor(private config: AuthConfig) {}
|
|
301
|
+
*
|
|
302
|
+
* register(container: Container) {
|
|
303
|
+
* container.registerFactory(AUTH_SERVICE, () => new JwtAuthService(this.config))
|
|
304
|
+
* }
|
|
305
|
+
*
|
|
306
|
+
* modules() {
|
|
307
|
+
* return [AuthModule]
|
|
308
|
+
* }
|
|
309
|
+
*
|
|
310
|
+
* adapters() {
|
|
311
|
+
* return [new AuthGuardAdapter(this.config)]
|
|
312
|
+
* }
|
|
313
|
+
*
|
|
314
|
+
* middleware() {
|
|
315
|
+
* return [passport.initialize()]
|
|
316
|
+
* }
|
|
317
|
+
* }
|
|
318
|
+
* ```
|
|
319
|
+
*/
|
|
320
|
+
interface KickPlugin {
|
|
321
|
+
/** Human-readable name for logging, debugging, and `dependsOn` resolution. */
|
|
322
|
+
name: string;
|
|
323
|
+
/**
|
|
324
|
+
* Other plugin names that must mount before this one. The framework
|
|
325
|
+
* topologically sorts plugins at boot — cycles or unknown names throw
|
|
326
|
+
* via {@link MountCycleError} / {@link MissingMountDepError} so bad
|
|
327
|
+
* configurations fail boot rather than corrupt live traffic.
|
|
328
|
+
*
|
|
329
|
+
* Plugins with no `dependsOn` retain their declaration order, so
|
|
330
|
+
* existing apps that don't use this field see no behaviour change.
|
|
331
|
+
*
|
|
332
|
+
* @example
|
|
333
|
+
* ```ts
|
|
334
|
+
* class MonitoringPlugin implements KickPlugin {
|
|
335
|
+
* name = 'MonitoringPlugin'
|
|
336
|
+
* // OTel must initialize traces before request logger reads them
|
|
337
|
+
* dependsOn = ['OtelPlugin']
|
|
338
|
+
* }
|
|
339
|
+
* ```
|
|
340
|
+
*/
|
|
341
|
+
dependsOn?: readonly KickJsPluginName[];
|
|
342
|
+
/**
|
|
343
|
+
* Register DI bindings before modules load.
|
|
344
|
+
* Use this to provide services that modules depend on.
|
|
345
|
+
*/
|
|
346
|
+
register?(container: Container): void;
|
|
347
|
+
/**
|
|
348
|
+
* Return modules to be loaded alongside user modules. Plugin
|
|
349
|
+
* modules are loaded before user modules.
|
|
350
|
+
*
|
|
351
|
+
* Accepts both class form (`SomeModule extends AppModule`) and
|
|
352
|
+
* instance form (output of {@link defineModule}'s factory call,
|
|
353
|
+
* e.g. `TasksModule({ scope: 'admin' })`) — the bootstrap loader
|
|
354
|
+
* discriminates and either `new`-s the class or uses the instance
|
|
355
|
+
* directly.
|
|
356
|
+
*
|
|
357
|
+
* Static path — for conditional / dynamic registration, use
|
|
358
|
+
* {@link KickPlugin.setup} instead.
|
|
359
|
+
*/
|
|
360
|
+
modules?(): AppModuleEntry[];
|
|
361
|
+
/**
|
|
362
|
+
* Imperative module registration hook. Receives a {@link ModuleRegistry}
|
|
363
|
+
* the plugin can call `.mount(module)` on to register modules
|
|
364
|
+
* conditionally — e.g. based on injected config, env flags, or a
|
|
365
|
+
* tenant list resolved at boot.
|
|
366
|
+
*
|
|
367
|
+
* Runs after the static {@link KickPlugin.modules} array is collected
|
|
368
|
+
* but before user modules and the user-level `setup()` callback. The
|
|
369
|
+
* plugin sees the same dispatch rules as everything else: class
|
|
370
|
+
* entries get `new`-ed, factory output is used directly.
|
|
371
|
+
*
|
|
372
|
+
* @example
|
|
373
|
+
* ```ts
|
|
374
|
+
* definePlugin<{ tenants: string[] }>({
|
|
375
|
+
* name: 'MultiTenantPlugin',
|
|
376
|
+
* build: (config) => ({
|
|
377
|
+
* setup(registry) {
|
|
378
|
+
* for (const tenant of config.tenants) {
|
|
379
|
+
* registry.mount(TenantModule.scoped(tenant, { id: tenant }))
|
|
380
|
+
* }
|
|
381
|
+
* },
|
|
382
|
+
* }),
|
|
383
|
+
* })
|
|
384
|
+
* ```
|
|
385
|
+
*/
|
|
386
|
+
setup?(registry: ModuleRegistry): void;
|
|
387
|
+
/**
|
|
388
|
+
* Return adapter instances to be added to the application.
|
|
389
|
+
* Plugin adapters are added before user adapters.
|
|
390
|
+
*/
|
|
391
|
+
adapters?(): AppAdapter[];
|
|
392
|
+
/**
|
|
393
|
+
* Return connect-style handlers — `(req, res, next)` — for the global
|
|
394
|
+
* pipeline. Each is mounted through the runtime's `useConnect` seam, so
|
|
395
|
+
* these work on Express, Fastify and h3 alike; only the `req` / `res`
|
|
396
|
+
* shapes differ per engine. Plugin middleware runs before user-defined
|
|
397
|
+
* middleware, and carries no `phase` / `path` — use an adapter's
|
|
398
|
+
* {@link AppAdapter.middleware} for scoped or phased entries.
|
|
399
|
+
*/
|
|
400
|
+
middleware?(): any[];
|
|
401
|
+
/**
|
|
402
|
+
* Return Context Contributors (#107) the plugin ships. Contributors
|
|
403
|
+
* returned here merge into the per-route pipeline at the **`'adapter'`
|
|
404
|
+
* precedence level** — same as those returned by adapters the plugin
|
|
405
|
+
* ships via {@link KickPlugin.adapters}, and for the same reason: a
|
|
406
|
+
* plugin is a cross-cutting bundle, narrower than the global default
|
|
407
|
+
* but broader than a per-module hook.
|
|
408
|
+
*
|
|
409
|
+
* Use when a plugin wants to ship a typed contributor without standing
|
|
410
|
+
* up an accompanying adapter. For full coverage of the precedence
|
|
411
|
+
* matrix (method > class > module > adapter > global) see
|
|
412
|
+
* `docs/guide/context-decorators.md`.
|
|
413
|
+
*
|
|
414
|
+
* @example
|
|
415
|
+
* ```ts
|
|
416
|
+
* import { defineContextDecorator, type KickPlugin } from '@forinda/kickjs'
|
|
417
|
+
*
|
|
418
|
+
* const LoadFlags = defineContextDecorator({
|
|
419
|
+
* key: 'flags',
|
|
420
|
+
* resolve: (ctx) => fetchFlags(ctx.requestId!),
|
|
421
|
+
* })
|
|
422
|
+
*
|
|
423
|
+
* export class FlagsPlugin implements KickPlugin {
|
|
424
|
+
* name = 'FlagsPlugin'
|
|
425
|
+
* contributors() {
|
|
426
|
+
* return [LoadFlags.registration]
|
|
427
|
+
* }
|
|
428
|
+
* }
|
|
429
|
+
* ```
|
|
430
|
+
*/
|
|
431
|
+
contributors?(): ContributorRegistrations;
|
|
432
|
+
/** Settings sections this plugin needs — validated at startup, bound before any hook runs. */
|
|
433
|
+
settings?(): readonly SettingsDeclaration[];
|
|
434
|
+
/**
|
|
435
|
+
* Called after the application has fully bootstrapped.
|
|
436
|
+
* Use for post-startup logic like logging, health registration, etc.
|
|
437
|
+
*/
|
|
438
|
+
onReady?(container: Container): void | Promise<void>;
|
|
439
|
+
/**
|
|
440
|
+
* Observe every error the app reports — request errors (any status; filter
|
|
441
|
+
* on `info.status`), uncaught exceptions, unhandled rejections, failed
|
|
442
|
+
* `waitUntil` work, failed queue jobs, and anything passed to
|
|
443
|
+
* `reportError()`. Observe-only: the response is not yours to change, and a
|
|
444
|
+
* throw here is logged and skipped. The place to wire Sentry & co.
|
|
445
|
+
*/
|
|
446
|
+
onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
|
|
447
|
+
/**
|
|
448
|
+
* Observe every finished response — method, path, the matched route
|
|
449
|
+
* pattern, status, duration. Only timed while something listens.
|
|
450
|
+
*/
|
|
451
|
+
onResponse?(info: ResponseInfo): void | Promise<void>;
|
|
452
|
+
/**
|
|
453
|
+
* Called during application shutdown — release what this plugin owns
|
|
454
|
+
* (connections, intervals, subscriptions).
|
|
455
|
+
*
|
|
456
|
+
* Runs on a real shutdown AND on **every HMR reload**, so it is a hot path
|
|
457
|
+
* in dev, not an exit-only courtesy.
|
|
458
|
+
*
|
|
459
|
+
* Close only what you own. Never close the shared HTTP server: in dev it is
|
|
460
|
+
* Vite's listener, and closing it leaves the port dead with no rebind. The
|
|
461
|
+
* framework closes it itself on a real shutdown.
|
|
462
|
+
*
|
|
463
|
+
* Time-boxed: `shutdownTimeout` on a real shutdown, `min(shutdownTimeout,
|
|
464
|
+
* 5s)` on a reload. Overruns are logged by name and skipped.
|
|
465
|
+
*/
|
|
466
|
+
shutdown?(): void | Promise<void>;
|
|
467
|
+
/**
|
|
468
|
+
* Optional DevTools introspection hook (architecture.md §23). Returns
|
|
469
|
+
* a snapshot describing this plugin's current state, metrics, and DI
|
|
470
|
+
* tokens. DevTools awaits the result, so async work is fine — but keep
|
|
471
|
+
* the implementation cheap (counters + flags, no DB round trips) since
|
|
472
|
+
* the topology endpoint polls on a short interval.
|
|
473
|
+
*
|
|
474
|
+
* The return type lives in `@forinda/kickjs` itself
|
|
475
|
+
* ({@link IntrospectionSnapshot}) so adopters can author `introspect()`
|
|
476
|
+
* without importing the kit just to satisfy the contract. The kit's
|
|
477
|
+
* own `IntrospectionSnapshot` type stays structurally identical;
|
|
478
|
+
* either import works.
|
|
479
|
+
*/
|
|
480
|
+
introspect?(): IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
|
|
481
|
+
/**
|
|
482
|
+
* Optional DevTools tabs this plugin contributes (architecture.md §23).
|
|
483
|
+
* Same shape as {@link AppAdapter.devtoolsTabs}; the kit's
|
|
484
|
+
* `DevtoolsTabDescriptor` types it for plugin authors.
|
|
485
|
+
*/
|
|
486
|
+
devtoolsTabs?(): readonly unknown[];
|
|
487
|
+
}
|
|
488
|
+
//#endregion
|
|
489
|
+
//#region src/core/define-plugin.d.ts
|
|
490
|
+
/**
|
|
491
|
+
* Options passed to {@link definePlugin}. Mirrors the spec in
|
|
492
|
+
* `architecture.md` §21.3.1 + §21.2.2 (Phase A "lite").
|
|
493
|
+
*/
|
|
494
|
+
interface DefinePluginOptions<TConfig> {
|
|
495
|
+
/** Stable identity used for logging, `dependsOn` lookups, and `.scoped()` namespacing. */
|
|
496
|
+
name: string;
|
|
497
|
+
/** Optional plugin version — surfaced to DevTools and `kick add` compatibility checks (Phase B). */
|
|
498
|
+
version?: string;
|
|
499
|
+
/**
|
|
500
|
+
* Peer-version ranges this plugin needs from the framework or other
|
|
501
|
+
* plugins. Recorded as metadata; runtime enforcement lands in §21.4.4.
|
|
502
|
+
*/
|
|
503
|
+
requires?: {
|
|
504
|
+
kickjs?: string;
|
|
505
|
+
};
|
|
506
|
+
/** Default config merged under any caller overrides. */
|
|
507
|
+
defaults?: Partial<TConfig>;
|
|
508
|
+
/** Builds the underlying {@link KickPlugin} from the resolved config. */
|
|
509
|
+
build(config: TConfig, ctx: BuildContext): Omit<KickPlugin, 'name'>;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Hook context handed to a plugin/adapter `build` function. `name` is the
|
|
513
|
+
* resolved instance name (the bare definition name for the bare call,
|
|
514
|
+
* or `${defName}:${scope}` for `.scoped()`). `scoped` is the discriminator
|
|
515
|
+
* authors use to namespace DI tokens or resource keys.
|
|
516
|
+
*/
|
|
517
|
+
interface BuildContext {
|
|
518
|
+
name: string;
|
|
519
|
+
scoped: boolean;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Async-config form of a plugin or adapter — `inject` lists DI tokens to
|
|
523
|
+
* resolve from the container, then `useFactory` produces the config.
|
|
524
|
+
*
|
|
525
|
+
* Plugins resolve this lazily inside `onReady`, so any module/adapter/
|
|
526
|
+
* middleware/contributor a plugin contributes via `build` is **not
|
|
527
|
+
* available** when `.async()` is used. Use the bare/`.scoped()` form for
|
|
528
|
+
* plugins that need to register modules or middleware.
|
|
529
|
+
*/
|
|
530
|
+
interface PluginAsyncOptions<TConfig> {
|
|
531
|
+
inject?: ReadonlyArray<unknown>;
|
|
532
|
+
useFactory(...deps: any[]): TConfig | Promise<TConfig>;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Factory returned by {@link definePlugin}. Callable form is the singleton
|
|
536
|
+
* (`AuthPlugin(config)`); `.scoped()` and `.async()` are the multi-instance
|
|
537
|
+
* and deferred-config forms.
|
|
538
|
+
*/
|
|
539
|
+
interface PluginFactory<TConfig> {
|
|
540
|
+
(config?: Partial<TConfig>): KickPlugin;
|
|
541
|
+
scoped(scopeName: string, config?: Partial<TConfig>): KickPlugin;
|
|
542
|
+
async(opts: PluginAsyncOptions<TConfig>): KickPlugin;
|
|
543
|
+
/** Read-only access to the original definition — useful for DevTools introspection. */
|
|
544
|
+
readonly definition: Readonly<DefinePluginOptions<TConfig>>;
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Build a {@link KickPlugin} factory from a typed definition. See
|
|
548
|
+
* `architecture.md` §21.2.2 for the design rationale.
|
|
549
|
+
*
|
|
550
|
+
* @example
|
|
551
|
+
* ```ts
|
|
552
|
+
* const FlagsPlugin = definePlugin<FlagsConfig>({
|
|
553
|
+
* name: 'FlagsPlugin',
|
|
554
|
+
* defaults: { defaultTtl: 60_000 },
|
|
555
|
+
* build(config) {
|
|
556
|
+
* return {
|
|
557
|
+
* register(container) {
|
|
558
|
+
* container.registerInstance(FLAGS, makeProvider(config))
|
|
559
|
+
* },
|
|
560
|
+
* }
|
|
561
|
+
* },
|
|
562
|
+
* })
|
|
563
|
+
*
|
|
564
|
+
* bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })
|
|
565
|
+
* ```
|
|
566
|
+
*/
|
|
567
|
+
declare function definePlugin<TConfig = Record<string, unknown>>(options: DefinePluginOptions<TConfig>): PluginFactory<TConfig>;
|
|
568
|
+
//#endregion
|
|
569
|
+
//#region src/core/define-module.d.ts
|
|
570
|
+
/**
|
|
571
|
+
* Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}
|
|
572
|
+
* and {@link DefinePluginOptions} so adopters learn one mental model
|
|
573
|
+
* across all three primitives.
|
|
574
|
+
*
|
|
575
|
+
* The optional `TExtra` generic lets a module ship public methods
|
|
576
|
+
* beyond the standard {@link AppModule} contract — they're preserved
|
|
577
|
+
* on the returned module instance so external callers (tests, sibling
|
|
578
|
+
* modules) can invoke them directly.
|
|
579
|
+
*/
|
|
580
|
+
interface DefineModuleOptions<TConfig, TExtra = unknown> {
|
|
581
|
+
/**
|
|
582
|
+
* Stable identity surfaced in diagnostics, route logs, and
|
|
583
|
+
* `.scoped()` namespacing. Required because boot-time error
|
|
584
|
+
* messages reference modules by name — anonymous modules make
|
|
585
|
+
* cycles + missing-dep errors hard to localize.
|
|
586
|
+
*/
|
|
587
|
+
name: string;
|
|
588
|
+
/** Optional version string surfaced in diagnostics. */
|
|
589
|
+
version?: string;
|
|
590
|
+
/**
|
|
591
|
+
* Optional kickjs version constraint. Enforced by the framework
|
|
592
|
+
* when implemented; today it lives on the definition for
|
|
593
|
+
* documentation and forward compatibility.
|
|
594
|
+
*/
|
|
595
|
+
requires?: {
|
|
596
|
+
kickjs?: string;
|
|
597
|
+
};
|
|
598
|
+
/**
|
|
599
|
+
* Default config merged with overrides at instantiation time
|
|
600
|
+
* (`MyModule({ field: x })`). Call-site overrides win.
|
|
601
|
+
*/
|
|
602
|
+
defaults?: Partial<TConfig>;
|
|
603
|
+
/**
|
|
604
|
+
* Build the AppModule shape from the resolved config and context.
|
|
605
|
+
* `ctx.name` is the resolved instance name (the bare definition
|
|
606
|
+
* name for the default call, or `${name}:${scope}` for
|
|
607
|
+
* `.scoped()`); `ctx.scoped` discriminates so the build function
|
|
608
|
+
* can branch on namespacing if needed.
|
|
609
|
+
*
|
|
610
|
+
* Return any extension methods alongside the standard
|
|
611
|
+
* {@link AppModule} surface — they're typed via `TExtra` and stay
|
|
612
|
+
* accessible on the resulting instance.
|
|
613
|
+
*/
|
|
614
|
+
build(config: TConfig, ctx: BuildContext): AppModule & TExtra;
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}
|
|
618
|
+
* — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),
|
|
619
|
+
* inspect (`MyModule.definition`).
|
|
620
|
+
*
|
|
621
|
+
* `.async()` is intentionally **not** part of the module factory
|
|
622
|
+
* surface. Module config has no async-resolution window: `register()`
|
|
623
|
+
* and `routes()` both run synchronously during bootstrap, before any
|
|
624
|
+
* adapter `beforeStart` hook fires. Adopters that need async-resolved
|
|
625
|
+
* config push it into an adapter (which has `beforeStart`), then
|
|
626
|
+
* inject the resolved value into the module via DI tokens.
|
|
627
|
+
*/
|
|
628
|
+
interface ModuleFactory<TConfig, TExtra = unknown> {
|
|
629
|
+
(config?: Partial<TConfig>): AppModule & TExtra;
|
|
630
|
+
scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra;
|
|
631
|
+
readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>;
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Build an {@link AppModule} factory from a typed definition. Pairs
|
|
635
|
+
* with {@link defineAdapter}, {@link definePlugin}, and
|
|
636
|
+
* {@link defineContextDecorator} as the fourth `define*` primitive
|
|
637
|
+
* — adopters write modules the same way they write adapters and
|
|
638
|
+
* plugins.
|
|
639
|
+
*
|
|
640
|
+
* The returned factory produces real {@link AppModule} instances
|
|
641
|
+
* that drop into `bootstrap({ modules })` directly. The legacy
|
|
642
|
+
* class form (`class TasksModule implements AppModule { ... }`) keeps
|
|
643
|
+
* working — `bootstrap` accepts either shape.
|
|
644
|
+
*
|
|
645
|
+
* @example
|
|
646
|
+
* ```ts
|
|
647
|
+
* interface TasksConfig {
|
|
648
|
+
* scope: 'public' | 'admin'
|
|
649
|
+
* }
|
|
650
|
+
*
|
|
651
|
+
* const TasksModule = defineModule<TasksConfig>({
|
|
652
|
+
* name: 'TasksModule',
|
|
653
|
+
* defaults: { scope: 'public' },
|
|
654
|
+
* build: (config, { name }) => ({
|
|
655
|
+
* register(container) {
|
|
656
|
+
* container.registerInstance(`tasks:scope:${name}`, config.scope)
|
|
657
|
+
* },
|
|
658
|
+
* routes() {
|
|
659
|
+
* return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }
|
|
660
|
+
* },
|
|
661
|
+
* contributors() {
|
|
662
|
+
* return [LoadTenant.registration]
|
|
663
|
+
* },
|
|
664
|
+
* }),
|
|
665
|
+
* })
|
|
666
|
+
*
|
|
667
|
+
* bootstrap({
|
|
668
|
+
* modules: [
|
|
669
|
+
* TasksModule(), // public scope (defaults)
|
|
670
|
+
* TasksModule.scoped('admin', { scope: 'admin' }),
|
|
671
|
+
* ],
|
|
672
|
+
* })
|
|
673
|
+
* ```
|
|
674
|
+
*/
|
|
675
|
+
declare function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(options: DefineModuleOptions<TConfig, TExtra>): ModuleFactory<TConfig, TExtra>;
|
|
676
|
+
//#endregion
|
|
677
|
+
//#region src/core/define-modules.d.ts
|
|
678
|
+
/**
|
|
679
|
+
* Chainable registry returned by {@link defineModules}. Extends
|
|
680
|
+
* `Array<AppModuleEntry>` so it drops into `bootstrap({ modules })`
|
|
681
|
+
* unchanged — the framework loader already iterates the array, so a
|
|
682
|
+
* `ModuleList` IS a valid `modules` value with no special handling.
|
|
683
|
+
*
|
|
684
|
+
* The added affordance is `.mount(module)` returning `this` so
|
|
685
|
+
* adopters can build the list fluently:
|
|
686
|
+
*
|
|
687
|
+
* ```ts
|
|
688
|
+
* const modules = defineModules()
|
|
689
|
+
* .mount(HelloModule())
|
|
690
|
+
* .mount(AdminModule())
|
|
691
|
+
*
|
|
692
|
+
* bootstrap({ modules })
|
|
693
|
+
* ```
|
|
694
|
+
*
|
|
695
|
+
* **Why not just use a plain array?** Two reasons. First, the
|
|
696
|
+
* fluent shape reads more naturally for module-list construction —
|
|
697
|
+
* adopters used to `definePlugin().scoped(...)` / `defineAdapter(...)`
|
|
698
|
+
* see the same call-then-call pattern. Second, the registry is the
|
|
699
|
+
* stable extension point: a future `.use(module)` for non-HTTP
|
|
700
|
+
* modules (queues, cron, workers) lands as a method on `ModuleList`
|
|
701
|
+
* without breaking the `Array<AppModuleEntry>` superclass contract.
|
|
702
|
+
*/
|
|
703
|
+
declare class ModuleList extends Array<AppModuleEntry> {
|
|
704
|
+
/**
|
|
705
|
+
* Append a module to the list. Returns `this` for chaining.
|
|
706
|
+
*
|
|
707
|
+
* Accepts both class form (`SomeModule extends AppModule`) and
|
|
708
|
+
* `defineModule` factory output — same as the underlying
|
|
709
|
+
* `bootstrap({ modules })` array. The framework loader
|
|
710
|
+
* discriminates `typeof entry === 'function'` at boot.
|
|
711
|
+
*/
|
|
712
|
+
mount(module: AppModuleEntry): this;
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Build a {@link ModuleList} for the application. Optional vararg
|
|
716
|
+
* lets adopters seed the list inline; subsequent `.mount()` calls
|
|
717
|
+
* append.
|
|
718
|
+
*
|
|
719
|
+
* @example
|
|
720
|
+
* ```ts
|
|
721
|
+
* import { bootstrap, defineModules } from '@forinda/kickjs'
|
|
722
|
+
* import { HelloModule } from './modules/hello/hello.module'
|
|
723
|
+
* import { AdminModule } from './modules/admin/admin.module'
|
|
724
|
+
*
|
|
725
|
+
* // Fluent — most common
|
|
726
|
+
* const modules = defineModules()
|
|
727
|
+
* .mount(HelloModule())
|
|
728
|
+
* .mount(AdminModule())
|
|
729
|
+
*
|
|
730
|
+
* // Or seeded inline + chained
|
|
731
|
+
* const modules2 = defineModules(HelloModule()).mount(AdminModule())
|
|
732
|
+
*
|
|
733
|
+
* await bootstrap({ modules })
|
|
734
|
+
* ```
|
|
735
|
+
*
|
|
736
|
+
* The returned value is an `AppModuleEntry[]` subclass — `bootstrap`
|
|
737
|
+
* accepts it directly without any special-casing. For conditional /
|
|
738
|
+
* dynamic registration at bootstrap time (env flags, runtime config,
|
|
739
|
+
* tenant lists), use the `setup(registry)` callback on `bootstrap`
|
|
740
|
+
* instead — both surfaces compose.
|
|
741
|
+
*/
|
|
742
|
+
declare function defineModules(...initial: AppModuleEntry[]): ModuleList;
|
|
743
|
+
//#endregion
|
|
744
|
+
//#region src/core/jobs.d.ts
|
|
745
|
+
/** Metadata keys — the same ones `@forinda/kickjs-queue` used, so existing readers keep working. */
|
|
746
|
+
declare const JOB_META: {
|
|
747
|
+
readonly JOB: 'kick/queue/job';
|
|
748
|
+
readonly PROCESS: 'kick/queue/process';
|
|
749
|
+
};
|
|
750
|
+
/** What a `@Process` method records. */
|
|
751
|
+
interface ProcessDefinition {
|
|
752
|
+
/** Method name on the class. */
|
|
753
|
+
handlerName: string;
|
|
754
|
+
/** Job name it handles; `undefined` handles every job in the queue. */
|
|
755
|
+
jobName?: string;
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* The least a job tool hands over. Runners pass their own job object through
|
|
759
|
+
* unchanged — BullMQ's `Job`, a Cloudflare message — so a handler can still
|
|
760
|
+
* reach tool-specific fields (`job.attemptsMade`, `job.updateProgress()`).
|
|
761
|
+
*/
|
|
762
|
+
interface JobLike<Data = unknown> {
|
|
763
|
+
name: string;
|
|
764
|
+
data: Data;
|
|
765
|
+
id?: string;
|
|
766
|
+
}
|
|
767
|
+
/** Mark a class as handling jobs on `queue`. The class is a DI singleton. */
|
|
768
|
+
declare function Job(queue: string): ClassDecorator;
|
|
769
|
+
/** Mark a method as handling `jobName` — or, without a name, every job its queue gets. */
|
|
770
|
+
declare function Process(jobName?: string): MethodDecorator;
|
|
771
|
+
/** One handler: its queue, job name (absent for a catch-all), class and method. */
|
|
772
|
+
interface JobHandler extends ProcessDefinition {
|
|
773
|
+
queue: string;
|
|
774
|
+
target: Function;
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Every `@Process` method of a `@Job` class the container can resolve.
|
|
778
|
+
* Classes it doesn't know (not in a module, or from before an HMR reload)
|
|
779
|
+
* are skipped.
|
|
780
|
+
*/
|
|
781
|
+
declare function listJobHandlers(container: {
|
|
782
|
+
has(token: unknown): boolean;
|
|
783
|
+
}): JobHandler[];
|
|
784
|
+
/** The queues something handles — what a runner subscribes to. */
|
|
785
|
+
declare function listJobQueues(container: {
|
|
786
|
+
has(token: unknown): boolean;
|
|
787
|
+
}): string[];
|
|
788
|
+
/** Thrown when a queue receives a job no `@Process` method handles. */
|
|
789
|
+
declare class NoJobHandlerError extends Error {
|
|
790
|
+
readonly queue: string;
|
|
791
|
+
readonly jobName: string;
|
|
792
|
+
constructor(queue: string, jobName: string);
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Run one job: pick the `@Process` method for `job.name` (or the queue's
|
|
796
|
+
* catch-all), resolve its class from the container and call it with `job`
|
|
797
|
+
* as given. A failure is reported to the error observers (`source: 'job'`)
|
|
798
|
+
* and rethrown, so the tool's own retry and dead-letter handling still
|
|
799
|
+
* applies. A job nothing handles throws {@link NoJobHandlerError} rather
|
|
800
|
+
* than being acknowledged and lost.
|
|
801
|
+
*/
|
|
802
|
+
declare function runJob(container: {
|
|
803
|
+
has(token: unknown): boolean;
|
|
804
|
+
resolve(token: unknown): unknown;
|
|
805
|
+
}, queue: string, job: JobLike,
|
|
806
|
+
/** Extra fields for the error report — e.g. the tool's attempt count. */
|
|
807
|
+
report?: Record<string, unknown>): Promise<unknown>;
|
|
808
|
+
/**
|
|
809
|
+
* Something about where a job was dispatched from that its handler should
|
|
810
|
+
* run with — the tenant, a trace id, the acting user. Captured when the job
|
|
811
|
+
* is dispatched, carried in its data, and restored around the handler.
|
|
812
|
+
*/
|
|
813
|
+
interface JobContextCarrier<T = unknown> {
|
|
814
|
+
/** Unique: the field it travels under. */
|
|
815
|
+
key: string;
|
|
816
|
+
/** The value to carry, or `undefined` for nothing. */
|
|
817
|
+
capture(): T | undefined;
|
|
818
|
+
/** Run the handler with the value back in place. */
|
|
819
|
+
restore<R>(value: T, run: () => R): R;
|
|
820
|
+
}
|
|
821
|
+
/** The field a job's data carries its context in. Removed before the handler sees the data. */
|
|
822
|
+
declare const JOB_CONTEXT_FIELD = "__kickContext";
|
|
823
|
+
/** Carry a value from dispatch to handler for every job. Registering a key again replaces it. */
|
|
824
|
+
declare function registerJobContext<T>(carrier: JobContextCarrier<T>): void;
|
|
825
|
+
/**
|
|
826
|
+
* `data` with the current job context added — for a {@link JobDispatcher}
|
|
827
|
+
* implementation to call before enqueueing. Any `__kickContext` already in
|
|
828
|
+
* `data` is removed first: only this call may set it, so a dispatcher that
|
|
829
|
+
* enqueues caller-supplied data without it lets that data choose the context. Only plain-object data can carry
|
|
830
|
+
* it; anything else, or nothing to carry, is returned as is.
|
|
831
|
+
*/
|
|
832
|
+
declare function stampJobContext<Data>(data: Data): Data;
|
|
833
|
+
/** Enqueue a job — implemented by whichever adapter runs the jobs. */
|
|
834
|
+
interface JobDispatcher {
|
|
835
|
+
dispatch<Data = unknown>(queue: string, name: string, data: Data, options?: Record<string, unknown>): Promise<unknown>;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* The active job dispatcher. Inject it to enqueue without naming the tool:
|
|
839
|
+
* `@Inject(JOB_DISPATCHER) private jobs!: JobDispatcher`.
|
|
840
|
+
*/
|
|
841
|
+
declare const JOB_DISPATCHER: InjectionToken<JobDispatcher>;
|
|
842
|
+
//#endregion
|
|
843
|
+
//#region src/core/disposables.d.ts
|
|
844
|
+
/**
|
|
845
|
+
* Registry for framework-owned resources that hold timers or other handles
|
|
846
|
+
* outside the adapter/plugin lifecycle — e.g. the in-memory session and
|
|
847
|
+
* rate-limit stores' cleanup intervals. `Application.shutdown()` drains it so
|
|
848
|
+
* startup and shutdown stay symmetric even for resources created lazily by
|
|
849
|
+
* middleware factories.
|
|
850
|
+
*
|
|
851
|
+
* Intervals are `.unref()`'d so they never wedge process exit — this registry
|
|
852
|
+
* exists for IN-PROCESS teardown (test suites, HMR, multi-app hosts) where
|
|
853
|
+
* each un-disposed store would otherwise leak a live interval + backing Map
|
|
854
|
+
* per app instance.
|
|
855
|
+
*/
|
|
856
|
+
type Disposable = () => void | Promise<void>;
|
|
857
|
+
/** Register a cleanup callback. Returns an unregister function. */
|
|
858
|
+
declare function registerDisposable(fn: Disposable): () => void;
|
|
859
|
+
/** Run and clear all registered disposables. Errors are swallowed per-entry. */
|
|
860
|
+
declare function disposeAll(): Promise<void>;
|
|
861
|
+
//#endregion
|
|
862
|
+
//#region src/core/kick-error.d.ts
|
|
863
|
+
/**
|
|
864
|
+
* Structured framework error with code, cause, and actionable fix hint.
|
|
865
|
+
*
|
|
866
|
+
* The goal is "the developer who hits this knows what to do next." A
|
|
867
|
+
* cryptic `Error('No binding found for: UserService')` becomes a
|
|
868
|
+
* multi-line explanation pointing at the likely cause, the exact code
|
|
869
|
+
* change to apply, and a docs link.
|
|
870
|
+
*
|
|
871
|
+
* `.message` carries the full multi-line plain-text body so Node's
|
|
872
|
+
* default `Error.toString()` and unhandled-exception printing still
|
|
873
|
+
* surface the helpful version. Call {@link formatKickError} to render a
|
|
874
|
+
* colorized version for terminals.
|
|
875
|
+
*
|
|
876
|
+
* Per-error factories live in `kick-errors.ts` — those are the public
|
|
877
|
+
* entry points framework code uses. `KickError` is exported so adopters
|
|
878
|
+
* can build their own structured errors using the same shape.
|
|
879
|
+
*/
|
|
880
|
+
interface KickErrorInit {
|
|
881
|
+
/** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */
|
|
882
|
+
code: string;
|
|
883
|
+
/** One-line headline. */
|
|
884
|
+
summary: string;
|
|
885
|
+
/** Multi-line explanation of why this happened. */
|
|
886
|
+
cause?: string;
|
|
887
|
+
/** Multi-line actionable fix — show exact code if possible. */
|
|
888
|
+
fix?: string;
|
|
889
|
+
/** Absolute URL to the docs page that covers this error. */
|
|
890
|
+
docsUrl?: string;
|
|
891
|
+
/** Arbitrary structured fields for log consumers / debug tooling. */
|
|
892
|
+
context?: Record<string, unknown>;
|
|
893
|
+
}
|
|
894
|
+
declare class KickError extends Error {
|
|
895
|
+
readonly code: string;
|
|
896
|
+
readonly summary: string;
|
|
897
|
+
readonly cause?: string;
|
|
898
|
+
readonly fix?: string;
|
|
899
|
+
readonly docsUrl?: string;
|
|
900
|
+
readonly context?: Record<string, unknown>;
|
|
901
|
+
constructor(init: KickErrorInit);
|
|
902
|
+
}
|
|
903
|
+
interface FormatKickErrorOptions {
|
|
904
|
+
/**
|
|
905
|
+
* Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /
|
|
906
|
+
* `FORCE_COLOR` env vars honoured). Pass `false` for log files,
|
|
907
|
+
* structured loggers, or HTTP response bodies.
|
|
908
|
+
*/
|
|
909
|
+
color?: boolean;
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Render a {@link KickErrorInit} (or {@link KickError} instance) into a
|
|
913
|
+
* multi-line human-readable string. Identical layout regardless of
|
|
914
|
+
* colour — the colour flag only toggles ANSI codes.
|
|
915
|
+
*/
|
|
916
|
+
declare function formatKickError(err: KickErrorInit | KickError, options?: FormatKickErrorOptions): string;
|
|
917
|
+
//#endregion
|
|
918
|
+
//#region src/core/metadata.d.ts
|
|
919
|
+
/**
|
|
920
|
+
* Typed utilities for reflect-metadata operations.
|
|
921
|
+
*
|
|
922
|
+
* Replaces scattered Reflect.defineMetadata/getMetadata calls with a single
|
|
923
|
+
* source of truth. If we later move to Stage 3 decorators or a WeakMap-based
|
|
924
|
+
* store, only this file changes — all 24+ consumer files stay untouched.
|
|
925
|
+
*
|
|
926
|
+
* Keys may be symbols, strings, or `InjectionToken<T>` objects produced by
|
|
927
|
+
* `createToken()`. Using `createToken` is the preferred pattern because the
|
|
928
|
+
* token's phantom type flows through the helpers, enabling type-safe reads.
|
|
929
|
+
*/
|
|
930
|
+
type MetaKey = symbol | string | InjectionToken<unknown>;
|
|
931
|
+
/** Set metadata on a class (or prototype for property decorators) */
|
|
932
|
+
declare function setClassMeta<T>(key: MetaKey, value: T, target: object): void;
|
|
933
|
+
/** Set metadata on a specific method */
|
|
934
|
+
declare function setMethodMeta<T>(key: MetaKey, value: T, target: object, method: string): void;
|
|
935
|
+
/** Get metadata from a class, returning `fallback` if not set */
|
|
936
|
+
declare function getClassMeta<T>(key: MetaKey, target: object, fallback: T): T;
|
|
937
|
+
/** Get metadata from a specific method, returning `fallback` if not set */
|
|
938
|
+
declare function getMethodMeta<T>(key: MetaKey, target: object, method: string, fallback: T): T;
|
|
939
|
+
/** Check if metadata exists on a class */
|
|
940
|
+
declare function hasClassMeta(key: MetaKey, target: object): boolean;
|
|
941
|
+
/** Get metadata from a class with no default (returns undefined if absent) */
|
|
942
|
+
declare function getClassMetaOrUndefined<T>(key: MetaKey, target: object): T | undefined;
|
|
943
|
+
/** Get metadata from a method with no default (returns undefined if absent) */
|
|
944
|
+
declare function getMethodMetaOrUndefined<T>(key: MetaKey, target: object, method: string): T | undefined;
|
|
945
|
+
/** Append items to an array stored in class metadata */
|
|
946
|
+
declare function pushClassMeta<T>(key: MetaKey, target: object, ...items: T[]): void;
|
|
947
|
+
/** Append items to an array stored in method metadata */
|
|
948
|
+
declare function pushMethodMeta<T>(key: MetaKey, target: object, method: string, ...items: T[]): void;
|
|
949
|
+
/** Set a key/value in a Map stored in class metadata */
|
|
950
|
+
declare function setInMetaMap<K, V>(key: MetaKey, target: object, mapKey: K, mapValue: V): void;
|
|
951
|
+
/** Get a Map from class metadata (returns empty Map if absent) */
|
|
952
|
+
declare function getMetaMap<K, V>(key: MetaKey, target: object): Map<K, V>;
|
|
953
|
+
/** Set a key/value in a Record stored in class metadata */
|
|
954
|
+
declare function setInMetaRecord<V>(key: MetaKey, target: object, recKey: string | number, recValue: V): void;
|
|
955
|
+
/** Get a Record from class metadata (returns empty object if absent) */
|
|
956
|
+
declare function getMetaRecord<V>(key: MetaKey, target: object): Record<string | number, V>;
|
|
957
|
+
//#endregion
|
|
958
|
+
//#region src/core/circuit-breaker.d.ts
|
|
959
|
+
/**
|
|
960
|
+
* Circuit Breaker pattern for external service calls.
|
|
961
|
+
*
|
|
962
|
+
* Protects your application from cascading failures when downstream
|
|
963
|
+
* services are unhealthy by short-circuiting requests after a
|
|
964
|
+
* configurable failure threshold.
|
|
965
|
+
*
|
|
966
|
+
* @example
|
|
967
|
+
* ```ts
|
|
968
|
+
* const breaker = new CircuitBreaker('payment-api', {
|
|
969
|
+
* failureThreshold: 5,
|
|
970
|
+
* resetTimeout: 30_000,
|
|
971
|
+
* })
|
|
972
|
+
*
|
|
973
|
+
* const result = await breaker.execute(() => fetch('https://payment.example.com/charge'))
|
|
974
|
+
* ```
|
|
975
|
+
*/
|
|
976
|
+
type CircuitBreakerState = 'closed' | 'open' | 'half_open';
|
|
977
|
+
interface CircuitBreakerOptions {
|
|
978
|
+
/** Number of consecutive failures before the circuit opens. */
|
|
979
|
+
failureThreshold: number;
|
|
980
|
+
/** Milliseconds to wait before transitioning from OPEN to HALF_OPEN. */
|
|
981
|
+
resetTimeout: number;
|
|
982
|
+
/** Max requests allowed in HALF_OPEN state before deciding (default 1). */
|
|
983
|
+
halfOpenMax?: number;
|
|
984
|
+
}
|
|
985
|
+
interface CircuitBreakerStats {
|
|
986
|
+
failures: number;
|
|
987
|
+
successes: number;
|
|
988
|
+
state: CircuitBreakerState;
|
|
989
|
+
lastFailure?: Date;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Error thrown when the circuit is open and calls are being rejected.
|
|
993
|
+
*/
|
|
994
|
+
declare class CircuitOpenError extends Error {
|
|
995
|
+
readonly breakerName: string;
|
|
996
|
+
constructor(breakerName: string);
|
|
997
|
+
}
|
|
998
|
+
declare class CircuitBreaker {
|
|
999
|
+
readonly name: string;
|
|
1000
|
+
private state;
|
|
1001
|
+
private failures;
|
|
1002
|
+
private successes;
|
|
1003
|
+
private halfOpenAttempts;
|
|
1004
|
+
private lastFailure?;
|
|
1005
|
+
private openedAt?;
|
|
1006
|
+
private readonly failureThreshold;
|
|
1007
|
+
private readonly resetTimeout;
|
|
1008
|
+
private readonly halfOpenMax;
|
|
1009
|
+
constructor(name: string, options: CircuitBreakerOptions);
|
|
1010
|
+
/**
|
|
1011
|
+
* Execute an async function through the circuit breaker.
|
|
1012
|
+
* Throws `CircuitOpenError` if the circuit is open.
|
|
1013
|
+
*/
|
|
1014
|
+
execute<T>(fn: () => Promise<T>): Promise<T>;
|
|
1015
|
+
/** Returns the current circuit state. */
|
|
1016
|
+
getState(): CircuitBreakerState;
|
|
1017
|
+
/** Returns current statistics. */
|
|
1018
|
+
getStats(): CircuitBreakerStats;
|
|
1019
|
+
/** Manually reset the circuit breaker to CLOSED state. */
|
|
1020
|
+
reset(): void;
|
|
1021
|
+
private onSuccess;
|
|
1022
|
+
private onFailure;
|
|
1023
|
+
private maybeTransitionToHalfOpen;
|
|
1024
|
+
}
|
|
1025
|
+
//#endregion
|
|
1026
|
+
//#region src/core/context-errors.d.ts
|
|
1027
|
+
/**
|
|
1028
|
+
* Errors thrown by the Context Contributor pipeline.
|
|
1029
|
+
*
|
|
1030
|
+
* `MissingContributorError`, `ContributorCycleError`, and
|
|
1031
|
+
* `DuplicateContributorError` are startup-time errors raised during
|
|
1032
|
+
* pipeline build (topo-sort + validation), not per-request — a
|
|
1033
|
+
* misconfigured app fails to boot rather than fails a request. Per the
|
|
1034
|
+
* locked design in `architecture.md` §20.4, the pipeline is validated
|
|
1035
|
+
* once when each route is mounted and the resolved order is cached on
|
|
1036
|
+
* the route.
|
|
1037
|
+
*
|
|
1038
|
+
* `MissingContextValueError` is the one request-time error here: it is
|
|
1039
|
+
* raised by `ctx.require(key)` when a value a handler declared it needs
|
|
1040
|
+
* is absent. See its doc comment for why that case can't be caught at
|
|
1041
|
+
* startup today.
|
|
1042
|
+
*/
|
|
1043
|
+
/**
|
|
1044
|
+
* A contributor declared `dependsOn: ['<key>']` but no other contributor
|
|
1045
|
+
* (at any precedence level) produces that key for the same route.
|
|
1046
|
+
*
|
|
1047
|
+
* @example
|
|
1048
|
+
* ```text
|
|
1049
|
+
* MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id
|
|
1050
|
+
* declared at src/contributors/load-project.ts:42:18
|
|
1051
|
+
* ```
|
|
1052
|
+
*/
|
|
1053
|
+
declare class MissingContributorError extends Error {
|
|
1054
|
+
readonly key: string;
|
|
1055
|
+
readonly dependent: string;
|
|
1056
|
+
readonly route?: string;
|
|
1057
|
+
readonly dependentDefinedAt?: string;
|
|
1058
|
+
constructor(key: string, dependent: string, route?: string, dependentDefinedAt?: string);
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* `ctx.require(key)` found no value under `key` in the per-request
|
|
1062
|
+
* metadata store.
|
|
1063
|
+
*
|
|
1064
|
+
* Thrown at request time, by design. `ctx.get(key)` returns
|
|
1065
|
+
* `T | undefined` for every key, so the usual workaround is a
|
|
1066
|
+
* non-null assertion — `ctx.get('tenant')!` — which compiles whether or
|
|
1067
|
+
* not the route actually carries the contributor that produces it. On
|
|
1068
|
+
* an authorization value that is the worst possible thing to leave
|
|
1069
|
+
* untypeable: dropping the decorator produces no diagnostic anywhere,
|
|
1070
|
+
* and the handler reads `undefined` as though it were a real value.
|
|
1071
|
+
*
|
|
1072
|
+
* `ctx.require()` converts that silent hole into a loud, named failure
|
|
1073
|
+
* that points at the missing contributor.
|
|
1074
|
+
*
|
|
1075
|
+
* A handler typed with a generated route type (`Ctx<KickRoutes…>`) also
|
|
1076
|
+
* gets compile-time narrowing, so a dropped decorator fails `tsc` rather
|
|
1077
|
+
* than reaching this error at all. This error remains the backstop for
|
|
1078
|
+
* routes typegen couldn't prove (module/adapter/bootstrap registrations),
|
|
1079
|
+
* handlers typed as plain `RequestContext`, and contributors that ran but
|
|
1080
|
+
* resolved to `undefined`. See `architecture.md` §20.14.
|
|
1081
|
+
*
|
|
1082
|
+
* @example
|
|
1083
|
+
* ```text
|
|
1084
|
+
* MissingContextValueError: No context value for 'tenantPerm' on GET /projects/:id
|
|
1085
|
+
* Nothing wrote this key before the handler ran. Either the contributor
|
|
1086
|
+
* that produces it isn't applied to this route, or it ran and resolved
|
|
1087
|
+
* to undefined (check `optional: true` contributors).
|
|
1088
|
+
* ```
|
|
1089
|
+
*/
|
|
1090
|
+
declare class MissingContextValueError extends Error {
|
|
1091
|
+
readonly key: string;
|
|
1092
|
+
readonly route?: string;
|
|
1093
|
+
constructor(key: string, route?: string);
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field
|
|
1097
|
+
* lists the keys in the order they form the loop, with the first key
|
|
1098
|
+
* repeated at the end so the path reads naturally.
|
|
1099
|
+
*
|
|
1100
|
+
* @example
|
|
1101
|
+
* ```text
|
|
1102
|
+
* ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant
|
|
1103
|
+
* ```
|
|
1104
|
+
*/
|
|
1105
|
+
declare class ContributorCycleError extends Error {
|
|
1106
|
+
readonly cycle: readonly string[];
|
|
1107
|
+
readonly route?: string;
|
|
1108
|
+
constructor(cycle: readonly string[], route?: string);
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Two contributors at the same precedence level both produce the same key
|
|
1112
|
+
* for the same route. Precedence resolution (method > class > module >
|
|
1113
|
+
* adapter > global, per architecture.md §20.4) silently drops
|
|
1114
|
+
* lower-precedence duplicates; this error fires only when ties occur
|
|
1115
|
+
* within a single level — e.g., two method-level decorators declaring
|
|
1116
|
+
* `key: 'tenant'`.
|
|
1117
|
+
*
|
|
1118
|
+
* `sources` is best-effort identifying labels for each conflicting
|
|
1119
|
+
* registration (typically the decorator's call site or registering
|
|
1120
|
+
* module/adapter name).
|
|
1121
|
+
*
|
|
1122
|
+
* @example
|
|
1123
|
+
* ```text
|
|
1124
|
+
* DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain
|
|
1125
|
+
* ```
|
|
1126
|
+
*/
|
|
1127
|
+
declare class DuplicateContributorError extends Error {
|
|
1128
|
+
readonly key: string;
|
|
1129
|
+
readonly sources: readonly string[];
|
|
1130
|
+
constructor(key: string, sources: readonly string[]);
|
|
1131
|
+
}
|
|
1132
|
+
//#endregion
|
|
1133
|
+
//#region src/core/contributor-pipeline.d.ts
|
|
1134
|
+
/**
|
|
1135
|
+
* Where a contributor was registered, ordered by precedence
|
|
1136
|
+
* (lower index wins). Mirrors `architecture.md` §20.4.
|
|
1137
|
+
*
|
|
1138
|
+
* Levels (highest → lowest precedence):
|
|
1139
|
+
* - `'method'` — `@LoadX` on a controller method.
|
|
1140
|
+
* - `'class'` — `@LoadX` on a controller class.
|
|
1141
|
+
* - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.
|
|
1142
|
+
* - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies
|
|
1143
|
+
* to every module's routes.
|
|
1144
|
+
* - `'global'` — `ApplicationOptions.contributors`. App-wide default.
|
|
1145
|
+
*/
|
|
1146
|
+
type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global';
|
|
1147
|
+
/**
|
|
1148
|
+
* Input row to {@link buildPipeline}. Pairs a registration with its origin
|
|
1149
|
+
* so dedup can apply the precedence rule and diagnostic errors can name
|
|
1150
|
+
* the offending site.
|
|
1151
|
+
*
|
|
1152
|
+
* `registration` is the type-erased {@link AnyContributorRegistration}
|
|
1153
|
+
* — the runner doesn't care about each registration's narrow `D` /
|
|
1154
|
+
* `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic
|
|
1155
|
+
* contributors in the same `externalSources` / `contributors()`
|
|
1156
|
+
* array. The narrow generics from `defineContextDecorator` survive
|
|
1157
|
+
* at the *definition* site (where `resolve` is typed); they're erased
|
|
1158
|
+
* here so collections compose without `as any` casts.
|
|
1159
|
+
*/
|
|
1160
|
+
interface SourcedRegistration {
|
|
1161
|
+
registration: AnyContributorRegistration;
|
|
1162
|
+
source: ContributorSource;
|
|
1163
|
+
/** Human label surfaced in DuplicateContributorError messages. */
|
|
1164
|
+
label?: string;
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* Resolved, validated, topo-sorted pipeline ready for execution.
|
|
1168
|
+
*
|
|
1169
|
+
* `contributors` is in execution order — every entry's `dependsOn`
|
|
1170
|
+
* keys appear earlier. `keys` is the set of all keys this pipeline
|
|
1171
|
+
* produces; the runner uses it for fast existence checks and the
|
|
1172
|
+
* builder uses it for missing-dep validation.
|
|
1173
|
+
*/
|
|
1174
|
+
interface ContributorPipeline {
|
|
1175
|
+
readonly contributors: readonly AnyContributorRegistration[];
|
|
1176
|
+
readonly keys: ReadonlySet<string>;
|
|
1177
|
+
}
|
|
1178
|
+
interface BuildPipelineOptions {
|
|
1179
|
+
/** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */
|
|
1180
|
+
route?: string;
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Build, validate, and topo-sort a contributor pipeline.
|
|
1184
|
+
*
|
|
1185
|
+
* Pipeline:
|
|
1186
|
+
*
|
|
1187
|
+
* 1. Group sources by precedence (method > class > module > adapter > global).
|
|
1188
|
+
* 2. Within each precedence level, two contributors with the same `key`
|
|
1189
|
+
* raise {@link DuplicateContributorError}.
|
|
1190
|
+
* 3. Across levels, the highest-precedence contributor wins each key
|
|
1191
|
+
* (lower-precedence duplicates are silently dropped — that is the
|
|
1192
|
+
* documented override mechanism, not an error).
|
|
1193
|
+
* 4. Every key referenced by `dependsOn` must be produced by the
|
|
1194
|
+
* surviving set, otherwise {@link MissingContributorError}.
|
|
1195
|
+
* 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after
|
|
1196
|
+
* the queue drains form a cycle → {@link ContributorCycleError}
|
|
1197
|
+
* with a reconstructed path.
|
|
1198
|
+
*
|
|
1199
|
+
* Pure function — no DI, no I/O. Safe to call once at startup per
|
|
1200
|
+
* route and cache the result.
|
|
1201
|
+
*/
|
|
1202
|
+
declare function buildPipeline(sources: readonly SourcedRegistration[], options?: BuildPipelineOptions): ContributorPipeline;
|
|
1203
|
+
//#endregion
|
|
1204
|
+
//#region src/core/contributor-runner.d.ts
|
|
1205
|
+
interface RunContributorsOptions {
|
|
1206
|
+
/** Pre-built, validated, topo-sorted pipeline. */
|
|
1207
|
+
pipeline: ContributorPipeline;
|
|
1208
|
+
/** The execution context contributors read from and write into. */
|
|
1209
|
+
ctx: ExecutionContext;
|
|
1210
|
+
/** DI container used to resolve declared `deps`. */
|
|
1211
|
+
container: Container;
|
|
1212
|
+
/**
|
|
1213
|
+
* Route flags in force for the matched route, used to honour a
|
|
1214
|
+
* registration's `skipWhen` / `onlyWhen`. Omitted outside a route (the
|
|
1215
|
+
* pipeline then runs every contributor, as before).
|
|
1216
|
+
*/
|
|
1217
|
+
flags?: RouteFlags;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.
|
|
1221
|
+
*
|
|
1222
|
+
* Sequential — one contributor at a time, in the topo order chosen at
|
|
1223
|
+
* pipeline-build time. Per `architecture.md` §20.10, V1 does not run
|
|
1224
|
+
* contributors in parallel even within the same topo level; that is a
|
|
1225
|
+
* V2 follow-up gated on profiling.
|
|
1226
|
+
*
|
|
1227
|
+
* ## Error matrix (architecture.md §20.9)
|
|
1228
|
+
*
|
|
1229
|
+
* | resolve outcome | optional | onError defined | runner behaviour |
|
|
1230
|
+
* |-----------------|----------|-----------------|--------------------------------------------------|
|
|
1231
|
+
* | throws | true | — | skip; `ctx.get(key)` remains undefined |
|
|
1232
|
+
* | throws | false | yes | call hook; returned value (if any) stored |
|
|
1233
|
+
* | throws | false | no | propagate the original error |
|
|
1234
|
+
* | hook throws | — | yes | propagate the new error |
|
|
1235
|
+
* | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |
|
|
1236
|
+
* | resolves | — | — | `ctx.set(key, value)` |
|
|
1237
|
+
*
|
|
1238
|
+
* Container.resolve() throwing while building `deps` is treated as a
|
|
1239
|
+
* resolve-side throw and flows through the same matrix — adopters who
|
|
1240
|
+
* need different behaviour for missing-DI vs. data-lookup failures can
|
|
1241
|
+
* wrap the container access inside their own `resolve()`.
|
|
1242
|
+
*/
|
|
1243
|
+
declare function runContributors(options: RunContributorsOptions): Promise<void>;
|
|
1244
|
+
//#endregion
|
|
1245
|
+
//#region src/core/mount-sort.d.ts
|
|
1246
|
+
/**
|
|
1247
|
+
* Topological sort for plugins and adapters with `dependsOn` declarations.
|
|
1248
|
+
*
|
|
1249
|
+
* Mirrors the algorithm used by the Context Contributor pipeline
|
|
1250
|
+
* (`contributor-pipeline.ts:topoSort`) but operates on a name-keyed
|
|
1251
|
+
* `MountSortItem` shape rather than a `ContributorRegistration`. Kept
|
|
1252
|
+
* standalone instead of factored generic so that:
|
|
1253
|
+
*
|
|
1254
|
+
* 1. The contributor pipeline doesn't need refactoring (risk reduction).
|
|
1255
|
+
* 2. The error classes can carry plugin/adapter-specific diagnostic
|
|
1256
|
+
* fields (`kind`, `dependent`) without bending the contributor types.
|
|
1257
|
+
*/
|
|
1258
|
+
/**
|
|
1259
|
+
* A plugin or adapter that participates in dependency-ordered mounting.
|
|
1260
|
+
* Both `KickPlugin` and `AppAdapter` satisfy this shape via their `name`
|
|
1261
|
+
* and `dependsOn` fields.
|
|
1262
|
+
*/
|
|
1263
|
+
interface MountSortItem {
|
|
1264
|
+
/** Unique mount name within the plugin/adapter set being sorted. */
|
|
1265
|
+
name: string;
|
|
1266
|
+
/**
|
|
1267
|
+
* Other plugin/adapter names that must mount before this one. Cycles
|
|
1268
|
+
* and missing names fail at boot — same fail-fast contract as the
|
|
1269
|
+
* Context Contributor pipeline (architecture.md §20.4).
|
|
1270
|
+
*/
|
|
1271
|
+
dependsOn?: readonly string[];
|
|
1272
|
+
}
|
|
1273
|
+
/** What kind of mount set the sort is operating on — surfaces in error messages. */
|
|
1274
|
+
type MountKind = 'plugin' | 'adapter';
|
|
1275
|
+
/**
|
|
1276
|
+
* Two items in the same mount set declared the same `name`. Plugin/adapter
|
|
1277
|
+
* names must be unique so `dependsOn` references resolve unambiguously.
|
|
1278
|
+
*/
|
|
1279
|
+
declare class DuplicateMountNameError extends Error {
|
|
1280
|
+
readonly kind: MountKind;
|
|
1281
|
+
readonly mountName: string;
|
|
1282
|
+
constructor(kind: MountKind, mountName: string);
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* A `dependsOn` entry references a plugin/adapter that isn't in the
|
|
1286
|
+
* current set. The dependency might not be installed, might be misspelled,
|
|
1287
|
+
* or might live in a different mount set (plugin referencing an adapter,
|
|
1288
|
+
* or vice versa — they sort independently).
|
|
1289
|
+
*/
|
|
1290
|
+
declare class MissingMountDepError extends Error {
|
|
1291
|
+
readonly kind: MountKind;
|
|
1292
|
+
readonly missing: string;
|
|
1293
|
+
readonly dependent: string;
|
|
1294
|
+
constructor(kind: MountKind, missing: string, dependent: string);
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* The `dependsOn` declarations form a cycle. Boot fails so the cycle
|
|
1298
|
+
* can't poison live traffic. The `cycle` field reports one path through
|
|
1299
|
+
* the offending nodes for diagnostics — formatted `A → B → C → A`.
|
|
1300
|
+
*/
|
|
1301
|
+
declare class MountCycleError extends Error {
|
|
1302
|
+
readonly kind: MountKind;
|
|
1303
|
+
readonly cycle: readonly string[];
|
|
1304
|
+
constructor(kind: MountKind, cycle: readonly string[]);
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Topologically sort `items` so every item with `dependsOn: ['X']` mounts
|
|
1308
|
+
* after `X`. Items without `dependsOn` keep their input order via Kahn's
|
|
1309
|
+
* algorithm with a FIFO queue seeded in input order — preserves the
|
|
1310
|
+
* historical "plugins/adapters mount in declaration order" behaviour for
|
|
1311
|
+
* any set that doesn't use `dependsOn`.
|
|
1312
|
+
*
|
|
1313
|
+
* @param items - mountable items, e.g. plugins or adapters
|
|
1314
|
+
* @param kind - 'plugin' | 'adapter', used in error messages
|
|
1315
|
+
* @returns a new array in valid mount order
|
|
1316
|
+
* @throws {DuplicateMountNameError} two items share a name
|
|
1317
|
+
* @throws {MissingMountDepError} a `dependsOn` references an unknown name
|
|
1318
|
+
* @throws {MountCycleError} the dep graph contains a cycle
|
|
1319
|
+
*/
|
|
1320
|
+
declare function mountSort<T extends MountSortItem>(items: readonly T[], kind: MountKind): T[];
|
|
1321
|
+
//#endregion
|
|
1322
|
+
//#region src/core/define-adapter.d.ts
|
|
1323
|
+
/**
|
|
1324
|
+
* Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}
|
|
1325
|
+
* exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter
|
|
1326
|
+
* symmetry rationale.
|
|
1327
|
+
*
|
|
1328
|
+
* The optional `TExtra` generic lets an adapter ship public methods
|
|
1329
|
+
* beyond the standard {@link AppAdapter} contract — they're preserved
|
|
1330
|
+
* on the returned adapter instance so external callers (tests, peer
|
|
1331
|
+
* adapters) can invoke them directly. See `OtelAdapter.applyRedaction`
|
|
1332
|
+
* for the canonical use case.
|
|
1333
|
+
*/
|
|
1334
|
+
interface DefineAdapterOptions<TConfig, TExtra = unknown> {
|
|
1335
|
+
/**
|
|
1336
|
+
* Stable identity used for logging, `dependsOn` lookups, and `.scoped()`
|
|
1337
|
+
* namespacing. Required for adapters that participate in `dependsOn`
|
|
1338
|
+
* sort — error messages reference adapters by name.
|
|
1339
|
+
*/
|
|
1340
|
+
name: string;
|
|
1341
|
+
version?: string;
|
|
1342
|
+
requires?: {
|
|
1343
|
+
kickjs?: string;
|
|
1344
|
+
};
|
|
1345
|
+
defaults?: Partial<TConfig>;
|
|
1346
|
+
build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra;
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* Async-config form of an adapter. Identical shape to `PluginAsyncOptions`
|
|
1350
|
+
* but resolved during `beforeStart` (the earliest async hook in
|
|
1351
|
+
* `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner
|
|
1352
|
+
* adapter are **not** picked up. Use the bare/`.scoped()` form when you need
|
|
1353
|
+
* those.
|
|
1354
|
+
*/
|
|
1355
|
+
interface AdapterAsyncOptions<TConfig> {
|
|
1356
|
+
inject?: ReadonlyArray<unknown>;
|
|
1357
|
+
useFactory(...deps: any[]): TConfig | Promise<TConfig>;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Factory returned by {@link defineAdapter}. Same surface as
|
|
1361
|
+
* {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn
|
|
1362
|
+
* one mental model for both primitives. Returned instances carry both
|
|
1363
|
+
* the standard {@link AppAdapter} contract and any `TExtra` extension
|
|
1364
|
+
* methods the `build` function exposed.
|
|
1365
|
+
*/
|
|
1366
|
+
interface AdapterFactory<TConfig, TExtra = unknown> {
|
|
1367
|
+
(config?: Partial<TConfig>): AppAdapter & TExtra;
|
|
1368
|
+
scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra;
|
|
1369
|
+
async(opts: AdapterAsyncOptions<TConfig>): AppAdapter;
|
|
1370
|
+
readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>;
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* Build an {@link AppAdapter} factory from a typed definition. See
|
|
1374
|
+
* `architecture.md` §21.3.4 for migration guidance — most first-party
|
|
1375
|
+
* adapter packages collapse to a single `defineAdapter()` call after this
|
|
1376
|
+
* lands.
|
|
1377
|
+
*
|
|
1378
|
+
* @example
|
|
1379
|
+
* ```ts
|
|
1380
|
+
* const TenantAdapter = defineAdapter<TenantConfig>({
|
|
1381
|
+
* name: 'TenantAdapter',
|
|
1382
|
+
* defaults: { strategy: 'header', required: true },
|
|
1383
|
+
* build: (config) => ({
|
|
1384
|
+
* middleware: () => [tenantResolverMiddleware(config)],
|
|
1385
|
+
* beforeStart: ({ container }) => registerTenantFactory(container, config),
|
|
1386
|
+
* }),
|
|
1387
|
+
* })
|
|
1388
|
+
*
|
|
1389
|
+
* bootstrap({
|
|
1390
|
+
* adapters: [
|
|
1391
|
+
* TenantAdapter({ strategy: 'subdomain' }),
|
|
1392
|
+
* TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),
|
|
1393
|
+
* ],
|
|
1394
|
+
* })
|
|
1395
|
+
* ```
|
|
1396
|
+
*/
|
|
1397
|
+
declare function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(options: DefineAdapterOptions<TConfig, TExtra>): AdapterFactory<TConfig, TExtra>;
|
|
1398
|
+
//#endregion
|
|
1399
|
+
//#region src/core/asset-keys.d.ts
|
|
1400
|
+
type AssetKeyStrategy = 'auto' | 'strip' | 'with-extension';
|
|
1401
|
+
interface AssetKeyPair {
|
|
1402
|
+
/** Source-relative path the file was discovered at. */
|
|
1403
|
+
rel: string;
|
|
1404
|
+
/** Final logical key for the manifest, including the namespace prefix. */
|
|
1405
|
+
key: string;
|
|
1406
|
+
}
|
|
1407
|
+
interface GroupAssetKeysOptions {
|
|
1408
|
+
/**
|
|
1409
|
+
* Strategy applied to this namespace. Default `'auto'`.
|
|
1410
|
+
*
|
|
1411
|
+
* Adopters override per-namespace via `assetMap.<ns>.keys` in
|
|
1412
|
+
* kick.config.ts when they want uniform behaviour (e.g. always
|
|
1413
|
+
* include the extension regardless of collisions).
|
|
1414
|
+
*/
|
|
1415
|
+
strategy?: AssetKeyStrategy;
|
|
1416
|
+
}
|
|
1417
|
+
interface GroupAssetKeysResult {
|
|
1418
|
+
pairs: AssetKeyPair[];
|
|
1419
|
+
/**
|
|
1420
|
+
* Number of collision groups resolved by keeping extensions.
|
|
1421
|
+
* Surfaces as an informational log ("auto-resolved N collisions")
|
|
1422
|
+
* so adopters know whether they're relying on auto-mode or not.
|
|
1423
|
+
* Always 0 for `'strip'` (overwrites) and `'with-extension'`
|
|
1424
|
+
* (extensions always preserved, no collision possible).
|
|
1425
|
+
*/
|
|
1426
|
+
collisionGroupsResolved: number;
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* Compute final manifest keys for a namespace's discovered paths,
|
|
1430
|
+
* given the chosen strategy. Pure function — no fs / config / globals
|
|
1431
|
+
* involved.
|
|
1432
|
+
*
|
|
1433
|
+
* @param namespace assetMap key — e.g. `'mails'`, `'pages'`.
|
|
1434
|
+
* @param paths source-relative file paths (POSIX separators) discovered
|
|
1435
|
+
* under the namespace's `src` directory.
|
|
1436
|
+
* @param opts grouping options.
|
|
1437
|
+
*/
|
|
1438
|
+
declare function groupAssetKeys(namespace: string, paths: readonly string[], opts?: GroupAssetKeysOptions): GroupAssetKeysResult;
|
|
1439
|
+
/** Strip the final extension from a path. `'mails/welcome.ejs'` → `'mails/welcome'`. */
|
|
1440
|
+
declare function stripExt(path: string): string;
|
|
1441
|
+
//#endregion
|
|
1442
|
+
//#region src/core/route-policy.d.ts
|
|
1443
|
+
declare class RoutePolicyTable {
|
|
1444
|
+
/** Bucketed by method: an incoming request only scans its own verb. */
|
|
1445
|
+
private readonly byMethod;
|
|
1446
|
+
add(method: string, path: string, flags: RouteFlags | undefined): void;
|
|
1447
|
+
/**
|
|
1448
|
+
* Flags that apply to `method pathname`, or an empty map when the path
|
|
1449
|
+
* matches no flagged route — including when it matches no route at all,
|
|
1450
|
+
* which is exactly the traffic this exists to keep visible.
|
|
1451
|
+
*/
|
|
1452
|
+
lookup(method: string, pathname: string): RouteFlags;
|
|
1453
|
+
/** Drop everything — the Application rebuilds on every HMR reload. */
|
|
1454
|
+
clear(): void;
|
|
1455
|
+
get size(): number;
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* Declare that `handler` wants the policy table.
|
|
1459
|
+
*
|
|
1460
|
+
* Explicit hand-off rather than a module-level singleton, so the table a
|
|
1461
|
+
* middleware reads is always the one belonging to the app that mounted it.
|
|
1462
|
+
*/
|
|
1463
|
+
declare function bindRoutePolicy<T extends object>(handler: T, receive: (table: RoutePolicyTable) => void): T;
|
|
1464
|
+
/** Hand the table to a middleware if it declared the slot. */
|
|
1465
|
+
declare function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void;
|
|
1466
|
+
//#endregion
|
|
1467
|
+
//#region src/http/startup-timeline.d.ts
|
|
1468
|
+
/**
|
|
1469
|
+
* Where startup time goes: each phase of `setup()` / `start()`, and each
|
|
1470
|
+
* adapter hook on its own, so "boot got slow" points at a name.
|
|
1471
|
+
*
|
|
1472
|
+
* @module @forinda/kickjs/http/startup-timeline
|
|
1473
|
+
*/
|
|
1474
|
+
/** One timed step, in the order it ran. */
|
|
1475
|
+
interface StartupStep {
|
|
1476
|
+
/** A phase (`'modules'`, `'routes'`, `'listen'`) or `'<Adapter>.<hook>'`. */
|
|
1477
|
+
name: string;
|
|
1478
|
+
ms: number;
|
|
1479
|
+
}
|
|
1480
|
+
interface StartupTimelineSnapshot {
|
|
1481
|
+
totalMs: number;
|
|
1482
|
+
steps: readonly StartupStep[];
|
|
1483
|
+
}
|
|
1484
|
+
//#endregion
|
|
1485
|
+
//#region src/http/startup-checks.d.ts
|
|
1486
|
+
/** One finding. `error` fails startup; `warning` is logged. */
|
|
1487
|
+
interface CheckMessage {
|
|
1488
|
+
/** Stable ID, e.g. `'KICK-SEC-W001'` — what `silenceChecks` matches. */
|
|
1489
|
+
id: string;
|
|
1490
|
+
level: 'error' | 'warning';
|
|
1491
|
+
message: string;
|
|
1492
|
+
/** What to change. */
|
|
1493
|
+
fix?: string;
|
|
1494
|
+
}
|
|
1495
|
+
/** What a check can look at. */
|
|
1496
|
+
interface CheckContext {
|
|
1497
|
+
/** The options the app was created with. */
|
|
1498
|
+
options: Readonly<Record<string, unknown>>;
|
|
1499
|
+
/** Every mounted route, `{ method, path }`. */
|
|
1500
|
+
routes: ReadonlyArray<{
|
|
1501
|
+
method: string;
|
|
1502
|
+
path: string;
|
|
1503
|
+
}>;
|
|
1504
|
+
production: boolean;
|
|
1505
|
+
}
|
|
1506
|
+
interface StartupCheck {
|
|
1507
|
+
/** Names the check in logs; its messages carry their own IDs. */
|
|
1508
|
+
name: string;
|
|
1509
|
+
/** Run only when `NODE_ENV=production` — for deployment-only advice. */
|
|
1510
|
+
deploy?: boolean;
|
|
1511
|
+
run(ctx: CheckContext): CheckMessage | CheckMessage[] | undefined | void;
|
|
1512
|
+
}
|
|
1513
|
+
/** Declare a check — an identity helper, for the types. */
|
|
1514
|
+
declare function defineCheck(check: StartupCheck): StartupCheck;
|
|
1515
|
+
/** Thrown when a check reports an error; lists every error found. */
|
|
1516
|
+
declare class StartupCheckError extends Error {
|
|
1517
|
+
readonly messages: CheckMessage[];
|
|
1518
|
+
constructor(messages: CheckMessage[]);
|
|
1519
|
+
}
|
|
1520
|
+
//#endregion
|
|
1521
|
+
//#region src/http/reply.d.ts
|
|
1522
|
+
declare const REPLY_BRAND: unique symbol;
|
|
1523
|
+
/**
|
|
1524
|
+
* A status-carrying response payload for return-value handlers. Create via
|
|
1525
|
+
* {@link reply} — the brand is what runtimes detect, and the generics are
|
|
1526
|
+
* what the `kick/routes` response typegen unwraps (`Reply<S, T>` → `T`).
|
|
1527
|
+
*/
|
|
1528
|
+
interface Reply<S extends number = number, T = unknown> {
|
|
1529
|
+
readonly [REPLY_BRAND]: true;
|
|
1530
|
+
readonly status: S;
|
|
1531
|
+
readonly body: T;
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* Wrap a return-value handler's payload with an explicit status code:
|
|
1535
|
+
*
|
|
1536
|
+
* ```ts
|
|
1537
|
+
* @Post('/')
|
|
1538
|
+
* async create(ctx: RequestContext) {
|
|
1539
|
+
* return reply(201, await this.tasks.create(ctx.body))
|
|
1540
|
+
* }
|
|
1541
|
+
* ```
|
|
1542
|
+
*/
|
|
1543
|
+
declare function reply<S extends number, T>(status: S, body: T): Reply<S, T>;
|
|
1544
|
+
declare namespace reply {
|
|
1545
|
+
var ok: <T>(body: T) => Reply<200, T>;
|
|
1546
|
+
var created: <T>(body: T) => Reply<201, T>;
|
|
1547
|
+
var accepted: <T>(body: T) => Reply<202, T>;
|
|
1548
|
+
var noContent: () => Reply<204, undefined>;
|
|
1549
|
+
}
|
|
1550
|
+
/**
|
|
1551
|
+
* The statically-inferred response type of a controller handler — what
|
|
1552
|
+
* `kick typegen` emits into `KickRoutes[...].response`:
|
|
1553
|
+
*
|
|
1554
|
+
* - `Awaited<ReturnType>` of the method
|
|
1555
|
+
* - `Reply<S, T>` unwraps to `T`
|
|
1556
|
+
* - `void`/`undefined` members are dropped (imperative `ctx.json` branches);
|
|
1557
|
+
* a handler that never returns a value stays `unknown`, matching the
|
|
1558
|
+
* pre-inference emission
|
|
1559
|
+
*
|
|
1560
|
+
* ```ts
|
|
1561
|
+
* type R = InferHandlerResponse<UsersController['get']> // → User
|
|
1562
|
+
* ```
|
|
1563
|
+
*/
|
|
1564
|
+
type InferHandlerResponse<H> = H extends ((...args: never[]) => infer R) ? [Exclude<Awaited<R>, void | undefined>] extends [never] ? unknown : UnwrapReply<Exclude<Awaited<R>, void | undefined>> : unknown;
|
|
1565
|
+
type UnwrapReply<A> = A extends Reply<number, infer B> ? B : A extends RuntimeResponse ? unknown : A;
|
|
1566
|
+
declare function isReply(value: unknown): value is Reply;
|
|
1567
|
+
/**
|
|
1568
|
+
* Key of the method a self-sending result carries. A returned value with
|
|
1569
|
+
* `[RESPOND](ctx)` writes its own response — how an integration (an Inertia
|
|
1570
|
+
* page, a rendered view) works as a return value without the framework
|
|
1571
|
+
* knowing its format. Registry symbol, so a second copy of the package still
|
|
1572
|
+
* matches.
|
|
1573
|
+
*/
|
|
1574
|
+
declare const RESPOND: unique symbol;
|
|
1575
|
+
/** A handler return value that writes its own response. */
|
|
1576
|
+
interface Respondable {
|
|
1577
|
+
[RESPOND](ctx: RequestContext): void | PromiseLike<void>;
|
|
1578
|
+
}
|
|
1579
|
+
declare function isRespondable(value: unknown): value is Respondable;
|
|
1580
|
+
/**
|
|
1581
|
+
* Send a handler's RETURN value when the pipeline finished without anything
|
|
1582
|
+
* having written a response. Callers guard on "driver/response unsettled" —
|
|
1583
|
+
* this only decides how to send:
|
|
1584
|
+
*
|
|
1585
|
+
* - `undefined` → not handled (returns false; runtime keeps today's behavior)
|
|
1586
|
+
* - `Respondable` → its `[RESPOND](ctx)` writes the response (may be async)
|
|
1587
|
+
* - `Reply` wrapper → status + body (204 → `ctx.noContent()`)
|
|
1588
|
+
* - anything else → `ctx.json(value)` (200)
|
|
1589
|
+
*
|
|
1590
|
+
* Returns true when a response was produced — a promise of it for an async
|
|
1591
|
+
* `Respondable`, which callers await so its errors reach the error handler.
|
|
1592
|
+
*/
|
|
1593
|
+
declare function applyHandlerResult(ctx: RequestContext, result: unknown): boolean | Promise<boolean>;
|
|
1594
|
+
//#endregion
|
|
1595
|
+
//#region src/http/health-module.d.ts
|
|
1596
|
+
/** One adapter's answer to `onHealthCheck()`. */
|
|
1597
|
+
interface HealthCheckResult {
|
|
1598
|
+
name: string;
|
|
1599
|
+
status: 'up' | 'down';
|
|
1600
|
+
/** Why a check counts as down when it didn't answer for itself. */
|
|
1601
|
+
reason?: 'timeout' | 'error';
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* What the health routes need from the running Application.
|
|
1605
|
+
*
|
|
1606
|
+
* A controller cannot reach `Application` internals, and should not: this is
|
|
1607
|
+
* the whole surface the endpoints depend on, so a replacement module can
|
|
1608
|
+
* satisfy it without knowing anything else.
|
|
1609
|
+
*/
|
|
1610
|
+
interface HealthProbe {
|
|
1611
|
+
/** True once shutdown has begun and traffic should drain away. */
|
|
1612
|
+
isDraining(): boolean;
|
|
1613
|
+
/** Aggregated `onHealthCheck()` results from every adapter that has one. */
|
|
1614
|
+
checks(): Promise<HealthCheckResult[]>;
|
|
1615
|
+
}
|
|
1616
|
+
declare const HEALTH_PROBE: InjectionToken<HealthProbe>;
|
|
1617
|
+
/** Config for {@link healthModule}. */
|
|
1618
|
+
interface HealthModuleConfig {
|
|
1619
|
+
/**
|
|
1620
|
+
* Route flags to put on `GET /health/live` and `GET /health/ready`.
|
|
1621
|
+
*
|
|
1622
|
+
* The framework names no flags, so it cannot decide these probes are
|
|
1623
|
+
* "public" on your behalf — the name is yours, and every consumer that
|
|
1624
|
+
* already reads it (an auth contributor's `skipWhen`, a guard's
|
|
1625
|
+
* `exemptWhen`, `SwaggerAdapter({ publicFlag })`) then covers health with no
|
|
1626
|
+
* further wiring:
|
|
1627
|
+
*
|
|
1628
|
+
* ```ts
|
|
1629
|
+
* bootstrap({ health: { flags: ['auth.public'] } })
|
|
1630
|
+
* ```
|
|
1631
|
+
*
|
|
1632
|
+
* This replaces exempting `/health/live` and `/health/ready` by pathname,
|
|
1633
|
+
* which silently stops matching if the probe paths ever move.
|
|
1634
|
+
*/
|
|
1635
|
+
flags?: RouteFlagDeclarations;
|
|
1636
|
+
/**
|
|
1637
|
+
* Milliseconds each `onHealthCheck()` gets before it counts as down
|
|
1638
|
+
* (`reason: 'timeout'`). Default 2000. Keeps one hung dependency from
|
|
1639
|
+
* hanging the probe itself, which the orchestrator would then time out.
|
|
1640
|
+
*/
|
|
1641
|
+
checkTimeout?: number;
|
|
1642
|
+
}
|
|
1643
|
+
declare class HealthController {
|
|
1644
|
+
private readonly probe;
|
|
1645
|
+
constructor(probe: HealthProbe);
|
|
1646
|
+
/**
|
|
1647
|
+
* Liveness: is the process up. Stays 200 while draining — an orchestrator
|
|
1648
|
+
* restarts a container whose liveness fails, which would kill a graceful
|
|
1649
|
+
* shutdown partway through. Readiness is what turns traffic away.
|
|
1650
|
+
*/
|
|
1651
|
+
live(): Reply<200, {
|
|
1652
|
+
status: string;
|
|
1653
|
+
uptime: number;
|
|
1654
|
+
}>;
|
|
1655
|
+
/** Readiness: is every adapter's dependency answering. */
|
|
1656
|
+
ready(): Promise<Reply<200 | 503, {
|
|
1657
|
+
status: string;
|
|
1658
|
+
checks: HealthCheckResult[];
|
|
1659
|
+
}>>;
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* `GET /health/live` and `GET /health/ready`, mounted at the root.
|
|
1663
|
+
*
|
|
1664
|
+
* A `defineModule` factory like any other module — the framework's own routes
|
|
1665
|
+
* should be declared the way it asks adopters to declare theirs, not through a
|
|
1666
|
+
* shape only the framework can produce.
|
|
1667
|
+
*
|
|
1668
|
+
* Registered automatically unless the app passes `health: false` or supplies a
|
|
1669
|
+
* module of its own. Pass `health: { flags: [...] }` to `bootstrap()` to flag
|
|
1670
|
+
* both probes — see {@link HealthModuleConfig}.
|
|
1671
|
+
*/
|
|
1672
|
+
declare const healthModule: ModuleFactory<HealthModuleConfig, unknown>;
|
|
1673
|
+
//#endregion
|
|
1674
|
+
//#region src/http/application.d.ts
|
|
1675
|
+
/**
|
|
1676
|
+
* A middleware entry in the declarative pipeline.
|
|
1677
|
+
* Can be a bare handler or an object with path scoping.
|
|
1678
|
+
*/
|
|
1679
|
+
type MiddlewareEntry = RequestHandler | {
|
|
1680
|
+
path: string;
|
|
1681
|
+
handler: RequestHandler;
|
|
1682
|
+
};
|
|
1683
|
+
/** Options for {@link Application.shutdown}. */
|
|
1684
|
+
interface ShutdownOptions {
|
|
1685
|
+
/**
|
|
1686
|
+
* Close the HTTP server and drain in-flight requests. Default `true`.
|
|
1687
|
+
*
|
|
1688
|
+
* Set `false` for a dev HMR rebuild, where the server is shared across
|
|
1689
|
+
* reloads — adapters, plugins, and disposables are still torn down, which is
|
|
1690
|
+
* the part a reload needs.
|
|
1691
|
+
*/
|
|
1692
|
+
closeServer?: boolean;
|
|
1693
|
+
}
|
|
1694
|
+
/** See {@link ApplicationOptions.server}. */
|
|
1695
|
+
interface ServerOptions {
|
|
1696
|
+
/** TLS credentials and options (`key`, `cert`, `ca`, `pfx`, `passphrase`, …). */
|
|
1697
|
+
tls?: tls.SecureContextOptions & tls.TlsOptions;
|
|
1698
|
+
/** Serve HTTP/2 with HTTP/1.1 fallback. Requires `tls` and an HTTP/2-capable runtime. */
|
|
1699
|
+
http2?: boolean;
|
|
1700
|
+
/**
|
|
1701
|
+
* Milliseconds an idle keep-alive connection stays open. Default 65000.
|
|
1702
|
+
* Keep it ABOVE your load balancer's idle timeout (AWS ALB: 60s): when the
|
|
1703
|
+
* server closes a connection the balancer is about to reuse, that request
|
|
1704
|
+
* fails with a 502. Node's own default is 5s.
|
|
1705
|
+
*/
|
|
1706
|
+
keepAliveTimeout?: number;
|
|
1707
|
+
/** Milliseconds to receive the request headers. Default `keepAliveTimeout + 1000`. */
|
|
1708
|
+
headersTimeout?: number;
|
|
1709
|
+
/** Milliseconds to receive the whole request. Default 300000; 0 disables. */
|
|
1710
|
+
requestTimeout?: number;
|
|
1711
|
+
}
|
|
1712
|
+
/** A mounted controller route, as `app.getRoutes()` lists it. */
|
|
1713
|
+
interface MountedRouteInfo {
|
|
1714
|
+
method: string;
|
|
1715
|
+
/** Full pattern, prefix and version included: `/api/v1/users/:id`. */
|
|
1716
|
+
pattern: string;
|
|
1717
|
+
controller: string;
|
|
1718
|
+
handler: string;
|
|
1719
|
+
/** Context contributors in execution order, with where each was registered. */
|
|
1720
|
+
contributors: readonly RouteContributor[];
|
|
1721
|
+
}
|
|
1722
|
+
/** What `app.describeConfig()` returns. */
|
|
1723
|
+
interface ConfigDescription {
|
|
1724
|
+
/** The app's env schema (`loadEnv` / `loadEnvFromSchema`), or the base schema. */
|
|
1725
|
+
env: ConfigVar[];
|
|
1726
|
+
/** Declared settings sections, in declaration order, each once. */
|
|
1727
|
+
sections: Array<{
|
|
1728
|
+
prefix: string;
|
|
1729
|
+
declaredBy: string;
|
|
1730
|
+
vars: ConfigVar[];
|
|
1731
|
+
}>;
|
|
1732
|
+
}
|
|
1733
|
+
/** What `app.configOrigins()` returns. */
|
|
1734
|
+
interface ConfigOrigins {
|
|
1735
|
+
/** The app's env schema. */
|
|
1736
|
+
env: VarOrigin[];
|
|
1737
|
+
/** The settings sections the app bound, in binding order. */
|
|
1738
|
+
sections: Array<{
|
|
1739
|
+
prefix: string;
|
|
1740
|
+
vars: VarOrigin[];
|
|
1741
|
+
}>;
|
|
1742
|
+
}
|
|
1743
|
+
interface ApplicationOptions {
|
|
1744
|
+
/**
|
|
1745
|
+
* Feature modules to load. Accepts both class form
|
|
1746
|
+
* (`SomeModule extends AppModule`, instantiated via `new`) and
|
|
1747
|
+
* instance form (output of {@link defineModule}'s factory call,
|
|
1748
|
+
* e.g. `TasksModule({ scope: 'admin' })`) — the loader discriminates
|
|
1749
|
+
* and either `new`-s the class or uses the instance directly.
|
|
1750
|
+
*
|
|
1751
|
+
* Static path — for conditional / dynamic registration, use the
|
|
1752
|
+
* {@link ApplicationOptions.setup} callback instead.
|
|
1753
|
+
*/
|
|
1754
|
+
modules: AppModuleEntry[];
|
|
1755
|
+
/**
|
|
1756
|
+
* Imperative module registration callback. Receives a
|
|
1757
|
+
* {@link ModuleRegistry} you call `.mount(module)` on to register
|
|
1758
|
+
* modules conditionally — based on env flags, runtime config, a
|
|
1759
|
+
* tenant list, etc. Runs after every plugin's `setup()` hook and
|
|
1760
|
+
* after the static `modules: [...]` array is collected.
|
|
1761
|
+
*
|
|
1762
|
+
* @example
|
|
1763
|
+
* ```ts
|
|
1764
|
+
* bootstrap({
|
|
1765
|
+
* modules: [HelloModule()],
|
|
1766
|
+
* setup(registry) {
|
|
1767
|
+
* if (env.ENABLE_ADMIN) registry.mount(AdminModule())
|
|
1768
|
+
* },
|
|
1769
|
+
* })
|
|
1770
|
+
* ```
|
|
1771
|
+
*/
|
|
1772
|
+
setup?(registry: ModuleRegistry): void;
|
|
1773
|
+
/** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */
|
|
1774
|
+
adapters?: AppAdapter[];
|
|
1775
|
+
/** Server port (falls back to PORT env var, then 3000) */
|
|
1776
|
+
port?: number;
|
|
1777
|
+
/**
|
|
1778
|
+
* The Node server `start()` creates in production. Omit for plain HTTP.
|
|
1779
|
+
*
|
|
1780
|
+
* - `{ tls }` — HTTPS on every runtime.
|
|
1781
|
+
* - `{ tls, http2: true }` — HTTP/2 (ALPN `h2`) with HTTP/1.1 fallback, so
|
|
1782
|
+
* HTTP/1.1 clients and WebSocket upgrades keep working. Fastify and h3
|
|
1783
|
+
* only; Express fails at boot with KICK007, and `http2` without `tls`
|
|
1784
|
+
* with KICK008.
|
|
1785
|
+
*
|
|
1786
|
+
* Ignored in dev mode, where Vite owns the server. Most deploys terminate
|
|
1787
|
+
* TLS / HTTP/2 at a proxy and need none of this.
|
|
1788
|
+
*
|
|
1789
|
+
* @example
|
|
1790
|
+
* ```ts
|
|
1791
|
+
* bootstrap({
|
|
1792
|
+
* modules,
|
|
1793
|
+
* runtime: fastifyRuntime(),
|
|
1794
|
+
* server: {
|
|
1795
|
+
* tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
|
1796
|
+
* http2: true,
|
|
1797
|
+
* },
|
|
1798
|
+
* })
|
|
1799
|
+
* ```
|
|
1800
|
+
*/
|
|
1801
|
+
server?: ServerOptions;
|
|
1802
|
+
/** Global API prefix (default: '/api'). Pass `''` to mount at the root. */
|
|
1803
|
+
apiPrefix?: string;
|
|
1804
|
+
/**
|
|
1805
|
+
* Default API version (default: 1) — routes become /{prefix}/v{version}/{path}.
|
|
1806
|
+
*
|
|
1807
|
+
* `false` opts out of URL versioning: routes mount at /{prefix}/{path}.
|
|
1808
|
+
* A module can still version itself by setting `version` on its
|
|
1809
|
+
* `ModuleRoutes` — the per-mount value always wins over this default, in
|
|
1810
|
+
* either direction.
|
|
1811
|
+
*/
|
|
1812
|
+
defaultVersion?: number | false;
|
|
1813
|
+
/**
|
|
1814
|
+
* Global middleware pipeline. Declared in order.
|
|
1815
|
+
* Replaces the hardcoded middleware stack — you control exactly what runs.
|
|
1816
|
+
*
|
|
1817
|
+
* @example
|
|
1818
|
+
* ```ts
|
|
1819
|
+
* bootstrap({
|
|
1820
|
+
* modules,
|
|
1821
|
+
* middlewares: [
|
|
1822
|
+
* helmet(),
|
|
1823
|
+
* cors(),
|
|
1824
|
+
* compression(),
|
|
1825
|
+
* morgan('dev'),
|
|
1826
|
+
* express.json({ limit: '1mb' }),
|
|
1827
|
+
* ],
|
|
1828
|
+
* })
|
|
1829
|
+
* ```
|
|
1830
|
+
*
|
|
1831
|
+
* If omitted, a sensible default is applied:
|
|
1832
|
+
* requestId(), express.json({ limit: '100kb' })
|
|
1833
|
+
*/
|
|
1834
|
+
middlewares?: MiddlewareEntry[];
|
|
1835
|
+
/** Plugins that bundle modules, adapters, middleware, and DI bindings */
|
|
1836
|
+
plugins?: KickPlugin[];
|
|
1837
|
+
/**
|
|
1838
|
+
* Global Context Contributors (#107) that apply to every route in the
|
|
1839
|
+
* application. Merge into the per-route pipeline at the `'global'`
|
|
1840
|
+
* precedence level — they lose to module, adapter, class, and method
|
|
1841
|
+
* contributors with the same key, providing app-wide defaults that any
|
|
1842
|
+
* narrower scope can override.
|
|
1843
|
+
*
|
|
1844
|
+
* @example
|
|
1845
|
+
* ```ts
|
|
1846
|
+
* const StartedAt = defineContextDecorator({
|
|
1847
|
+
* key: 'requestStartedAt',
|
|
1848
|
+
* resolve: () => Date.now(),
|
|
1849
|
+
* })
|
|
1850
|
+
*
|
|
1851
|
+
* bootstrap({
|
|
1852
|
+
* modules,
|
|
1853
|
+
* contributors: [StartedAt.registration],
|
|
1854
|
+
* })
|
|
1855
|
+
* ```
|
|
1856
|
+
*/
|
|
1857
|
+
contributors?: ContributorRegistrations;
|
|
1858
|
+
/**
|
|
1859
|
+
* Backing store strategy for {@link RequestContext} `set/get` and the
|
|
1860
|
+
* Context Contributor pipeline (#107).
|
|
1861
|
+
*
|
|
1862
|
+
* - `'auto'` (default) — Application mounts {@link requestScopeMiddleware}
|
|
1863
|
+
* automatically before any user middleware. If the user-supplied
|
|
1864
|
+
* `middleware` list already includes `requestScopeMiddleware()`,
|
|
1865
|
+
* detection skips the auto-mount so adopters can control its position.
|
|
1866
|
+
* - `'manual'` — Application never mounts the wrapper. The Context
|
|
1867
|
+
* Contributor pipeline still runs on every route — the runner is
|
|
1868
|
+
* inserted by `router-builder` regardless of ALS state. What
|
|
1869
|
+
* degrades without an ALS frame is the *backing store*:
|
|
1870
|
+
* REQUEST-scoped DI throws (no `requestStore.getStore()` to read
|
|
1871
|
+
* from) and `RequestContext.set/get` throws. Use `'manual'` only when you
|
|
1872
|
+
* genuinely intend to wrap requests in your own ALS frame (rare —
|
|
1873
|
+
* multi-tenant adapters used to do this; post-Phase 3 they share
|
|
1874
|
+
* the framework's frame instead).
|
|
1875
|
+
*/
|
|
1876
|
+
contextStore?: 'auto' | 'manual';
|
|
1877
|
+
/**
|
|
1878
|
+
* Controls whether KickJS registers process-level handlers at bootstrap.
|
|
1879
|
+
*
|
|
1880
|
+
* - `'auto'` (default) — register `uncaughtException` /
|
|
1881
|
+
* `unhandledRejection` loggers AND `SIGINT` / `SIGTERM` →
|
|
1882
|
+
* `app.shutdown()` → `process.exit(0)`.
|
|
1883
|
+
* - `'errors-only'` — register the error loggers; skip the signal
|
|
1884
|
+
* handlers. Use this when you have your own shutdown choreographer
|
|
1885
|
+
* (OpenTelemetry SDK, Sentry, custom orchestrator) that calls
|
|
1886
|
+
* `app.shutdown()` itself and you don't want two listeners racing
|
|
1887
|
+
* to call `process.exit`.
|
|
1888
|
+
* - `'manual'` — skip everything. Adopter is responsible for both
|
|
1889
|
+
* error logging and signal-driven shutdown.
|
|
1890
|
+
*
|
|
1891
|
+
* Background: many observability SDKs install their own SIGTERM
|
|
1892
|
+
* handler to flush spans/metrics before the process exits. Two
|
|
1893
|
+
* separate handlers calling `process.exit(0)` race each other and
|
|
1894
|
+
* can truncate the in-flight flush. Setting this to `'errors-only'`
|
|
1895
|
+
* or `'manual'` lets the SDK own the lifecycle while still letting
|
|
1896
|
+
* KickJS surface uncaught exceptions / rejections via the logger.
|
|
1897
|
+
*
|
|
1898
|
+
* The dev mode auto-detect (`__kickjs_httpServer` set by the Vite
|
|
1899
|
+
* plugin) suppresses signal registration regardless of this option,
|
|
1900
|
+
* since Vite owns the lifecycle in development.
|
|
1901
|
+
*/
|
|
1902
|
+
processHooks?: 'auto' | 'errors-only' | 'manual';
|
|
1903
|
+
/**
|
|
1904
|
+
* The HTTP engine driver. Defaults to {@link expressRuntime} — Express stays
|
|
1905
|
+
* the zero-config default, so existing apps are unaffected.
|
|
1906
|
+
*
|
|
1907
|
+
* Any `HttpRuntime` is accepted — pass `fastifyRuntime()` (from
|
|
1908
|
+
* `@forinda/kickjs/fastify`) or a custom engine driver. Defaults to
|
|
1909
|
+
* {@link expressRuntime}. The engine-native escape hatches
|
|
1910
|
+
* (`getRuntimeApp()`, `AdapterContext.app`) follow the active runtime via the
|
|
1911
|
+
* registry (`ActiveRuntime`, spec §4.3b) — Express by default, or the augmented
|
|
1912
|
+
* engine once the `kick/runtime` typegen output is present.
|
|
1913
|
+
*/
|
|
1914
|
+
/**
|
|
1915
|
+
* Mount the built-in `GET /health/live` and `GET /health/ready`.
|
|
1916
|
+
*
|
|
1917
|
+
* On by default. Set `false` to take them over completely — supply your own
|
|
1918
|
+
* module at `/health` and nothing collides. The built-in is registered last,
|
|
1919
|
+
* so an app module claiming the same path already wins without this.
|
|
1920
|
+
*
|
|
1921
|
+
* They mount as an ordinary module, which means they sit inside the
|
|
1922
|
+
* middleware chain: whatever guards the rest of the app guards these too.
|
|
1923
|
+
* Pass `{ flags: [...] }` to put your own route flags on both probes — the
|
|
1924
|
+
* way to make them reachable unauthenticated without exempting a pathname
|
|
1925
|
+
* that can move:
|
|
1926
|
+
*
|
|
1927
|
+
* ```ts
|
|
1928
|
+
* bootstrap({ health: { flags: ['auth.public'] } })
|
|
1929
|
+
* ```
|
|
1930
|
+
*/
|
|
1931
|
+
health?: boolean | HealthModuleConfig;
|
|
1932
|
+
runtime?: HttpRuntime;
|
|
1933
|
+
/**
|
|
1934
|
+
* Requests no route matched, when the app runs inside another handler —
|
|
1935
|
+
* `kick dev`'s Vite server, or `app.handle(req, res, next)` in a host server.
|
|
1936
|
+
*
|
|
1937
|
+
* - `true` (default): Fastify and h3 hand them back to that handler.
|
|
1938
|
+
* - `false`: they are answered here — `onNotFound`, or the built-in 404 /
|
|
1939
|
+
* 405 — the same as in production. Express always answers.
|
|
1940
|
+
*
|
|
1941
|
+
* Set `false` when the app owns its URLs, e.g. pages with an error page,
|
|
1942
|
+
* so dev answers unknown URLs the way production does.
|
|
1943
|
+
*/
|
|
1944
|
+
notFoundFallthrough?: boolean;
|
|
1945
|
+
/** Express `trust proxy` setting */
|
|
1946
|
+
trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean);
|
|
1947
|
+
/**
|
|
1948
|
+
* Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`).
|
|
1949
|
+
* Express applies it to its default parsers, so only when `middlewares` is
|
|
1950
|
+
* not provided; Fastify, h3 and the web entry parse bodies themselves and
|
|
1951
|
+
* always apply it. A larger body answers 413.
|
|
1952
|
+
*/
|
|
1953
|
+
jsonLimit?: string | number;
|
|
1954
|
+
/**
|
|
1955
|
+
* Print the route table on startup. Default: `false`. Set to `true`
|
|
1956
|
+
* to log a per-controller summary (method counts + mount paths) once
|
|
1957
|
+
* the app has mounted. Emitted at `info` level, so it is still subject
|
|
1958
|
+
* to `LOG_LEVEL` filtering (visible at the default `info`; hidden at
|
|
1959
|
+
* `warn`/`error`/`silent`).
|
|
1960
|
+
*/
|
|
1961
|
+
logRouteTable?: boolean;
|
|
1962
|
+
/**
|
|
1963
|
+
* @deprecated Use {@link ApplicationOptions.logRouteTable}. Kept as an
|
|
1964
|
+
* alias for back-compat; `logRouteTable` wins when both are set.
|
|
1965
|
+
*/
|
|
1966
|
+
logRoutesTable?: boolean;
|
|
1967
|
+
/**
|
|
1968
|
+
* Maximum time (ms) to wait for graceful shutdown before forcing exit.
|
|
1969
|
+
* Default: 30000 (30 seconds). Set to 0 to disable forced exit.
|
|
1970
|
+
*/
|
|
1971
|
+
shutdownTimeout?: number;
|
|
1972
|
+
/**
|
|
1973
|
+
* Milliseconds to keep serving after shutdown begins, with `/health/ready`
|
|
1974
|
+
* already answering 503, before the server stops accepting connections.
|
|
1975
|
+
* Load balancers and Kubernetes endpoints take a few seconds to notice an
|
|
1976
|
+
* unready instance; closing at once refuses the requests still routed here.
|
|
1977
|
+
* Default 0. Not counted against `shutdownTimeout`.
|
|
1978
|
+
*/
|
|
1979
|
+
preStopDelay?: number;
|
|
1980
|
+
/**
|
|
1981
|
+
* Enable cluster mode for multi-core utilization.
|
|
1982
|
+
*
|
|
1983
|
+
* When enabled, the primary process forks worker processes that share the
|
|
1984
|
+
* same port via Node's built-in `cluster` module (OS load balancing).
|
|
1985
|
+
*
|
|
1986
|
+
* - `true` — use all available CPU cores
|
|
1987
|
+
* - `{ workers: N }` — use exactly N workers
|
|
1988
|
+
*
|
|
1989
|
+
* Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is
|
|
1990
|
+
* forwarded to all workers.
|
|
1991
|
+
*
|
|
1992
|
+
* @example
|
|
1993
|
+
* ```ts
|
|
1994
|
+
* bootstrap({ modules, cluster: true })
|
|
1995
|
+
* bootstrap({ modules, cluster: { workers: 4 } })
|
|
1996
|
+
* ```
|
|
1997
|
+
*/
|
|
1998
|
+
cluster?: boolean | {
|
|
1999
|
+
workers?: number;
|
|
2000
|
+
};
|
|
2001
|
+
/**
|
|
2002
|
+
* Custom 404 handler for unmatched routes. When omitted, the built-in
|
|
2003
|
+
* handler returns `{ message: 'Not Found' }` with status 404.
|
|
2004
|
+
*
|
|
2005
|
+
* Connect-**shaped**, not Express-**semantic** — see {@link onError} for the
|
|
2006
|
+
* per-runtime table. The same two caveats apply: `next()` is inert on
|
|
2007
|
+
* Fastify and h3, and Express-only request members (`req.originalUrl`,
|
|
2008
|
+
* `req.path`, `req.ip`) are `undefined` there, so read `req.url`.
|
|
2009
|
+
*
|
|
2010
|
+
* @example
|
|
2011
|
+
* ```ts
|
|
2012
|
+
* bootstrap({
|
|
2013
|
+
* modules,
|
|
2014
|
+
* onNotFound: (req, res) => {
|
|
2015
|
+
* // `req.originalUrl` is Express-only — use `req.url` for portability.
|
|
2016
|
+
* res.status(404).json({ error: 'Route not found', path: req.url })
|
|
2017
|
+
* },
|
|
2018
|
+
* })
|
|
2019
|
+
* ```
|
|
2020
|
+
*
|
|
2021
|
+
* Calling `next()` hands the request to the built-in handler — the usual
|
|
2022
|
+
* 404, or the 405 with `Allow` when the path exists under another method —
|
|
2023
|
+
* so a custom handler can answer some requests and leave the rest.
|
|
2024
|
+
*/
|
|
2025
|
+
onNotFound?: (req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void;
|
|
2026
|
+
/**
|
|
2027
|
+
* Custom global error handler, receiving `(err, req, res, next)`. When
|
|
2028
|
+
* omitted, the built-in handler formats ZodError, HttpException, and
|
|
2029
|
+
* unexpected errors.
|
|
2030
|
+
*
|
|
2031
|
+
* The shape is connect-style, but it is NOT "the standard Express error
|
|
2032
|
+
* handler" on every engine — what you actually receive differs, and the
|
|
2033
|
+
* differences bite:
|
|
2034
|
+
*
|
|
2035
|
+
* | | `req` | `res` | `next` |
|
|
2036
|
+
* | --- | --- | --- | --- |
|
|
2037
|
+
* | Express | native `Request` | native `Response` | real `next` |
|
|
2038
|
+
* | Fastify | `request.raw` | reply driver | **no-op** |
|
|
2039
|
+
* | h3 | `event.node.req` | response driver | no-op (or dev fall-through) |
|
|
2040
|
+
*
|
|
2041
|
+
* Two consequences worth knowing before you write one:
|
|
2042
|
+
*
|
|
2043
|
+
* - **`next(err)` does nothing on Fastify and h3.** It is a no-op function
|
|
2044
|
+
* there, so delegating to the default handler silently drops the error.
|
|
2045
|
+
* Send a response yourself rather than passing it on.
|
|
2046
|
+
* - **Express-only request members are `undefined` elsewhere.**
|
|
2047
|
+
* `req.originalUrl`, `req.path`, and `req.ip` do not exist on the raw node
|
|
2048
|
+
* request — use `req.url` and the `x-forwarded-*` headers, or reach for
|
|
2049
|
+
* `ctx.ip` in a contributor / guard where a `RequestContext` is available.
|
|
2050
|
+
*
|
|
2051
|
+
* `res` is typed {@link RuntimeResponse} because that is what every engine
|
|
2052
|
+
* genuinely provides: `status`, `json`, `send`, `setHeader`, `render`,
|
|
2053
|
+
* `writeHead`, `end`. Express's own `Response` satisfies it.
|
|
2054
|
+
*
|
|
2055
|
+
* @example
|
|
2056
|
+
* ```ts
|
|
2057
|
+
* bootstrap({
|
|
2058
|
+
* modules,
|
|
2059
|
+
* onError: (err, req, res) => {
|
|
2060
|
+
* logger.error(err, `${req.method} ${req.url}`) // not `originalUrl`
|
|
2061
|
+
* res.status(err.status ?? 500).json({ error: err.message })
|
|
2062
|
+
* },
|
|
2063
|
+
* })
|
|
2064
|
+
* ```
|
|
2065
|
+
*/
|
|
2066
|
+
onError?: (err: any, req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void;
|
|
2067
|
+
/**
|
|
2068
|
+
* Decide what a failed route validation (`@Validate` / `validate()`) throws.
|
|
2069
|
+
* Receives `{ source, issues, req }` and returns the error — by default a 422
|
|
2070
|
+
* `HttpException` with `[{ field, message }]` details. Return `undefined` to
|
|
2071
|
+
* fall back to the default for that failure.
|
|
2072
|
+
*
|
|
2073
|
+
* ```ts
|
|
2074
|
+
* bootstrap({
|
|
2075
|
+
* validationError: ({ source, issues }) =>
|
|
2076
|
+
* new ProblemException({
|
|
2077
|
+
* status: 400,
|
|
2078
|
+
* title: `Invalid ${source}`,
|
|
2079
|
+
* errors: issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
|
|
2080
|
+
* }),
|
|
2081
|
+
* })
|
|
2082
|
+
* ```
|
|
2083
|
+
*
|
|
2084
|
+
* Applies to this app's routes only.
|
|
2085
|
+
*/
|
|
2086
|
+
validationError?: ValidationErrorFactory;
|
|
2087
|
+
/**
|
|
2088
|
+
* Your own startup checks, run with the built-in ones once the app is
|
|
2089
|
+
* assembled and before it serves a request. A check returning an `error`
|
|
2090
|
+
* fails startup; a `warning` is logged.
|
|
2091
|
+
*
|
|
2092
|
+
* ```ts
|
|
2093
|
+
* const needsDb = defineCheck({
|
|
2094
|
+
* name: 'database url',
|
|
2095
|
+
* deploy: true, // production only
|
|
2096
|
+
* run: () =>
|
|
2097
|
+
* process.env.DATABASE_URL?.includes('localhost')
|
|
2098
|
+
* ? { id: 'APP-W001', level: 'warning', message: 'DATABASE_URL points at localhost' }
|
|
2099
|
+
* : undefined,
|
|
2100
|
+
* })
|
|
2101
|
+
* bootstrap({ modules, checks: [needsDb] })
|
|
2102
|
+
* ```
|
|
2103
|
+
*/
|
|
2104
|
+
checks?: StartupCheck[];
|
|
2105
|
+
/** Check IDs to skip, e.g. `['KICK-SEC-W002']` — a deliberate, reviewable exception. */
|
|
2106
|
+
silenceChecks?: string[];
|
|
2107
|
+
/**
|
|
2108
|
+
* App-wide settings sections ({@link defineSettings}): validated at startup
|
|
2109
|
+
* — a missing or invalid value fails it, naming the variables — and
|
|
2110
|
+
* injectable by their tokens. Modules, adapters and plugins declare their
|
|
2111
|
+
* own with `settings()`.
|
|
2112
|
+
*/
|
|
2113
|
+
settings?: SettingsDeclaration[];
|
|
2114
|
+
/**
|
|
2115
|
+
* Security defaults applied automatically unless opted out.
|
|
2116
|
+
*
|
|
2117
|
+
* When not specified, secure defaults are applied:
|
|
2118
|
+
* - Helmet security headers are auto-injected
|
|
2119
|
+
* - JSON body limit defaults to 1MB
|
|
2120
|
+
*
|
|
2121
|
+
* @example
|
|
2122
|
+
* ```ts
|
|
2123
|
+
* bootstrap({
|
|
2124
|
+
* modules,
|
|
2125
|
+
* security: {
|
|
2126
|
+
* helmet: false, // disable auto-helmet
|
|
2127
|
+
* },
|
|
2128
|
+
* })
|
|
2129
|
+
* ```
|
|
2130
|
+
*/
|
|
2131
|
+
security?: {
|
|
2132
|
+
/** Auto-inject helmet security headers. Default: true */
|
|
2133
|
+
helmet?: boolean;
|
|
2134
|
+
/**
|
|
2135
|
+
* Answer only requests for these hosts — `allowedHosts()` mounted first.
|
|
2136
|
+
* `'.example.com'` matches the domain and its subdomains. The health
|
|
2137
|
+
* probes are exempt: orchestrators send them to the instance's IP.
|
|
2138
|
+
*
|
|
2139
|
+
* ```ts
|
|
2140
|
+
* bootstrap({ security: { allowedHosts: ['example.com', '.example.com'] } })
|
|
2141
|
+
* ```
|
|
2142
|
+
*/
|
|
2143
|
+
allowedHosts?: string[] | AllowedHostsOptions;
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
declare class Application {
|
|
2147
|
+
private readonly options;
|
|
2148
|
+
private app;
|
|
2149
|
+
/** The HTTP engine driver. Defaults to {@link expressRuntime}. */
|
|
2150
|
+
private readonly runtime;
|
|
2151
|
+
private container;
|
|
2152
|
+
private httpServer;
|
|
2153
|
+
/** Set by startWithoutServer() — the serverless path, where cron runs over HTTP. */
|
|
2154
|
+
private handlerMode;
|
|
2155
|
+
/** The observer set this app installed — released on shutdown only if still current. */
|
|
2156
|
+
private observers;
|
|
2157
|
+
/**
|
|
2158
|
+
* Open HTTP/2 sessions. `server.close()` stops new sessions, but on older
|
|
2159
|
+
* Node (22 and earlier) existing ones keep accepting new streams — so
|
|
2160
|
+
* shutdown closes them itself.
|
|
2161
|
+
*/
|
|
2162
|
+
private readonly http2Sessions;
|
|
2163
|
+
/** Forwarding server behind {@link fetch} on Node-based runtimes. */
|
|
2164
|
+
private loopback?;
|
|
2165
|
+
private timeline;
|
|
2166
|
+
private conditionReport;
|
|
2167
|
+
private mountedRoutes;
|
|
2168
|
+
private mountedRouteInfo;
|
|
2169
|
+
private routeUrls;
|
|
2170
|
+
/** Settings prefixes bound in this setup, across its two binding phases. */
|
|
2171
|
+
private settingsPrefixes;
|
|
2172
|
+
private settingsProvided;
|
|
2173
|
+
private handlerFor?;
|
|
2174
|
+
private readonly adapters;
|
|
2175
|
+
/**
|
|
2176
|
+
* Flags of every mounted route, for middleware that runs before routing and
|
|
2177
|
+
* therefore cannot read `ctx.route` (the connect-style rate limiter). Handed
|
|
2178
|
+
* to middleware that declares the slot — see `core/route-policy.ts`.
|
|
2179
|
+
*/
|
|
2180
|
+
private readonly routePolicy;
|
|
2181
|
+
private readonly plugins;
|
|
2182
|
+
/**
|
|
2183
|
+
* Snapshot of every module-level Context Contributor registration
|
|
2184
|
+
* captured during `setup()`. The registrations themselves are
|
|
2185
|
+
* frozen by `defineContextDecorator`, so storing references is
|
|
2186
|
+
* safe — they outlive the module instances they came from.
|
|
2187
|
+
*
|
|
2188
|
+
* Used by {@link getContributors} so DevTools and adopter tooling
|
|
2189
|
+
* can render the module-level contributors alongside the adapter /
|
|
2190
|
+
* plugin / global ones. Populated once per `setup()` call; cleared
|
|
2191
|
+
* at the start of each invocation so a re-setup (test harnesses,
|
|
2192
|
+
* dev-server restarts) doesn't accumulate stale entries.
|
|
2193
|
+
*/
|
|
2194
|
+
private _moduleContributors;
|
|
2195
|
+
/** Number of HTTP requests currently being processed */
|
|
2196
|
+
private _inFlightRequests;
|
|
2197
|
+
/** Whether the application is draining (shutting down gracefully) */
|
|
2198
|
+
private _draining;
|
|
2199
|
+
/** Whether shutdown has already been initiated (prevents double-shutdown) */
|
|
2200
|
+
private _shutdownInitiated;
|
|
2201
|
+
/** Resolvers waiting for in-flight requests to reach zero */
|
|
2202
|
+
private _drainResolvers;
|
|
2203
|
+
constructor(options: ApplicationOptions);
|
|
2204
|
+
/**
|
|
2205
|
+
* Leave out adapters whose `when` says no — and, until nothing changes, any
|
|
2206
|
+
* adapter that `dependsOn` one left out, which could not run without it.
|
|
2207
|
+
*/
|
|
2208
|
+
private applyConditions;
|
|
2209
|
+
/**
|
|
2210
|
+
* Adapters with a `when` condition, and whether each is on — with the reason
|
|
2211
|
+
* when it is not. Served by DevTools at `/_debug/conditions`.
|
|
2212
|
+
*/
|
|
2213
|
+
getConditionReport(): readonly ConditionOutcome[];
|
|
2214
|
+
/** Whether the application is currently draining in-flight requests */
|
|
2215
|
+
get isDraining(): boolean;
|
|
2216
|
+
/** Number of HTTP requests currently being processed */
|
|
2217
|
+
get inFlightRequests(): number;
|
|
2218
|
+
/** Get the DI container instance */
|
|
2219
|
+
getContainer(): Container;
|
|
2220
|
+
/**
|
|
2221
|
+
* Express request handler — delegates to the internal Express app.
|
|
2222
|
+
*
|
|
2223
|
+
* Used by the Vite dev-server plugin to route requests through KickJS:
|
|
2224
|
+
* ```ts
|
|
2225
|
+
* const mod = await ssrLoadModule('virtual:kickjs/app')
|
|
2226
|
+
* mod.app.handle(req, res, next)
|
|
2227
|
+
* ```
|
|
2228
|
+
*
|
|
2229
|
+
* Also works as a standard Node.js request handler for production:
|
|
2230
|
+
* ```ts
|
|
2231
|
+
* http.createServer(app.handle.bind(app))
|
|
2232
|
+
* ```
|
|
2233
|
+
*/
|
|
2234
|
+
/**
|
|
2235
|
+
* Run a web `Request` through the app — routing, middleware, validation,
|
|
2236
|
+
* contributors, error handling — and return its `Response`, with no
|
|
2237
|
+
* listening server required.
|
|
2238
|
+
*
|
|
2239
|
+
* Runtimes with a native fetch (h3) are called directly.
|
|
2240
|
+
* Node-based runtimes (Express, Fastify) are served by forwarding to
|
|
2241
|
+
* a server bound to `127.0.0.1` inside this process, started on first use
|
|
2242
|
+
* and closed by {@link shutdown}; request bodies are buffered on that path.
|
|
2243
|
+
*
|
|
2244
|
+
* Used by `createHandler()` and by adapters (`AdapterContext.fetch`) that
|
|
2245
|
+
* call the app's own routes, such as MCP and AI tool dispatch.
|
|
2246
|
+
*/
|
|
2247
|
+
fetch(request: Request): Promise<Response>;
|
|
2248
|
+
/** The engine app, from the options — one place, so a rebuild (HMR) keeps them all. */
|
|
2249
|
+
private createEngineApp;
|
|
2250
|
+
handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void;
|
|
2251
|
+
/**
|
|
2252
|
+
* Full setup pipeline:
|
|
2253
|
+
* 1. Adapter beforeMount hooks (early routes — e.g. docs UI)
|
|
2254
|
+
* 2. Adapter middleware (phase: beforeGlobal)
|
|
2255
|
+
* 3. Global middleware (user-declared or defaults)
|
|
2256
|
+
* 4. Adapter middleware (phase: afterGlobal)
|
|
2257
|
+
* 5. Module registration + DI bootstrap (the built-in health module mounts
|
|
2258
|
+
* here with everything else — it is NOT an early route)
|
|
2259
|
+
* 6. Adapter middleware (phase: beforeRoutes)
|
|
2260
|
+
* 7. Module route mounting
|
|
2261
|
+
* 8. Adapter middleware (phase: afterRoutes)
|
|
2262
|
+
* 9. Adapter beforeStart hooks
|
|
2263
|
+
* 10. Error handlers (notFound + global)
|
|
2264
|
+
*/
|
|
2265
|
+
/** Build the adapter context object (shared across all hooks) */
|
|
2266
|
+
private adapterCtx;
|
|
2267
|
+
/**
|
|
2268
|
+
* The engine-agnostic HTTP surface handed to adapters as `ctx.http`. Each
|
|
2269
|
+
* call routes through the active runtime over the current `this.app`, so an
|
|
2270
|
+
* adapter written against this works under any runtime.
|
|
2271
|
+
*/
|
|
2272
|
+
private adapterHttp;
|
|
2273
|
+
/**
|
|
2274
|
+
* Call an adapter hook, awaiting async hooks.
|
|
2275
|
+
*
|
|
2276
|
+
* A setup hook (`beforeMount`, `beforeStart`) that throws aborts boot: the
|
|
2277
|
+
* adapter didn't finish wiring itself — a database adapter refusing to
|
|
2278
|
+
* start with pending migrations, say — and serving anyway runs on a
|
|
2279
|
+
* half-built app. `afterStart` runs once the server is already listening,
|
|
2280
|
+
* so its failure is logged and the server keeps going.
|
|
2281
|
+
*/
|
|
2282
|
+
private callHook;
|
|
2283
|
+
/**
|
|
2284
|
+
* Log advice for a hook failure: the failing adapter's own analysis first,
|
|
2285
|
+
* then the framework's. The error itself is still thrown or logged by the
|
|
2286
|
+
* caller — this only adds the explanation in front of it.
|
|
2287
|
+
*/
|
|
2288
|
+
private adviseOnFailure;
|
|
2289
|
+
/**
|
|
2290
|
+
* Where the last startup's time went: each phase and each adapter hook, in
|
|
2291
|
+
* order. Served by devtools at `/_debug/startup`.
|
|
2292
|
+
*/
|
|
2293
|
+
getStartupTimeline(): StartupTimelineSnapshot;
|
|
2294
|
+
/**
|
|
2295
|
+
* The URL of a route, by name — `'Controller.method'` — with its `:params`
|
|
2296
|
+
* filled (encoded) and an optional query string. For links built outside a
|
|
2297
|
+
* request (emails, jobs); inside one, use `ctx.urlFor()`.
|
|
2298
|
+
*
|
|
2299
|
+
* ```ts
|
|
2300
|
+
* app.urlFor('UsersController.show', { id: user.id }) // '/api/v1/users/42'
|
|
2301
|
+
* ```
|
|
2302
|
+
*/
|
|
2303
|
+
urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
|
|
2304
|
+
/** The app's modules — plugins', then its own — in registration order. */
|
|
2305
|
+
private collectModules;
|
|
2306
|
+
/**
|
|
2307
|
+
* Every variable the app reads — its env schema, and each declared settings
|
|
2308
|
+
* section with who declared it — and whether each is required, its default
|
|
2309
|
+
* and description. Reads no environment and validates nothing, so it works
|
|
2310
|
+
* when the environment is missing: it's what `kick env example` writes.
|
|
2311
|
+
* Call it on an app that hasn't started.
|
|
2312
|
+
*/
|
|
2313
|
+
describeConfig(): ConfigDescription;
|
|
2314
|
+
/**
|
|
2315
|
+
* Where each variable the app reads gets its value — env, a `_FILE` secret,
|
|
2316
|
+
* the schema's default, `provide()`, or nothing — for the env schema and
|
|
2317
|
+
* every bound settings section. Names only, never values. Read from the
|
|
2318
|
+
* current environment; call it on a started app.
|
|
2319
|
+
*/
|
|
2320
|
+
configOrigins(): ConfigOrigins;
|
|
2321
|
+
/** Validate settings sections and bind each under its token. */
|
|
2322
|
+
private bindSettings;
|
|
2323
|
+
/** Run the built-in and the app's startup checks against the assembled app. */
|
|
2324
|
+
private runChecks;
|
|
2325
|
+
/** Log the slowest steps — only when startup was slow enough to ask why. */
|
|
2326
|
+
private reportStartup;
|
|
2327
|
+
setup(): Promise<void>;
|
|
2328
|
+
/** Register modules and DI without starting the HTTP server (used by kick tinker) */
|
|
2329
|
+
registerOnly(): Promise<void>;
|
|
2330
|
+
/**
|
|
2331
|
+
* Make the app ready to serve requests handed to it, with no server of its
|
|
2332
|
+
* own — the serverless path behind {@link createHandler}.
|
|
2333
|
+
*
|
|
2334
|
+
* Runs the same `setup()` as {@link start} and the plugins' `onReady`, but
|
|
2335
|
+
* nothing that needs a listening server: there is no port, no `afterStart`
|
|
2336
|
+
* (it receives the `http.Server`), and no process signal handlers.
|
|
2337
|
+
*/
|
|
2338
|
+
startWithoutServer(): Promise<void>;
|
|
2339
|
+
/**
|
|
2340
|
+
* Start the HTTP server.
|
|
2341
|
+
*
|
|
2342
|
+
* In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`
|
|
2343
|
+
* created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real
|
|
2344
|
+
* `http.Server` through `afterStart({ server })` — zero adapter changes needed.
|
|
2345
|
+
*
|
|
2346
|
+
* In **production**: creates its own `http.Server` and binds to the port.
|
|
2347
|
+
*/
|
|
2348
|
+
start(): Promise<void>;
|
|
2349
|
+
/** The production server for {@link ApplicationOptions.server}. */
|
|
2350
|
+
private createNodeServer;
|
|
2351
|
+
private createBareServer;
|
|
2352
|
+
/** HMR rebuild: swap Express handler without restarting the server */
|
|
2353
|
+
rebuild(): Promise<void>;
|
|
2354
|
+
/**
|
|
2355
|
+
* Graceful shutdown with request draining.
|
|
2356
|
+
*
|
|
2357
|
+
* 1. Stops accepting new connections (server.close())
|
|
2358
|
+
* 2. Waits for in-flight requests to complete (up to shutdownTimeout)
|
|
2359
|
+
* 3. Calls adapter.shutdown() for all registered adapters
|
|
2360
|
+
* 4. Force-closes after timeout
|
|
2361
|
+
*
|
|
2362
|
+
* Safe to call multiple times — subsequent calls return the same promise.
|
|
2363
|
+
*/
|
|
2364
|
+
shutdown(options?: ShutdownOptions): Promise<void>;
|
|
2365
|
+
/**
|
|
2366
|
+
* The engine-native app instance, typed from the active runtime
|
|
2367
|
+
* ({@link ActiveRuntime} — Express by default). Prefer this over
|
|
2368
|
+
* {@link getExpressApp}; under a non-Express runtime the type follows the
|
|
2369
|
+
* augmented registry.
|
|
2370
|
+
*/
|
|
2371
|
+
getRuntimeApp(): ActiveRuntime['app'];
|
|
2372
|
+
/**
|
|
2373
|
+
* The active HTTP runtime's identity + capabilities — `name` is `'express'`
|
|
2374
|
+
* (default), `'fastify'`, or `'h3'`; `capabilities` reports what the engine
|
|
2375
|
+
* supports (render / uploads / connectMiddleware / nativeBodyParsing).
|
|
2376
|
+
* Surfaced by DevTools and the VS Code extension so tooling can show which
|
|
2377
|
+
* engine the app is running on. Cheap, side-effect free.
|
|
2378
|
+
*/
|
|
2379
|
+
getActiveRuntime(): {
|
|
2380
|
+
name: string;
|
|
2381
|
+
capabilities: RuntimeCapabilities;
|
|
2382
|
+
};
|
|
2383
|
+
/** @deprecated Use {@link getRuntimeApp}. Returns the engine-native app. */
|
|
2384
|
+
getExpressApp(): Express$1;
|
|
2385
|
+
/** Get registered adapters — used by DevToolsAdapter for peer discovery */
|
|
2386
|
+
getAdapters(): AppAdapter[];
|
|
2387
|
+
/**
|
|
2388
|
+
* Get registered plugins — used by DevToolsAdapter for topology
|
|
2389
|
+
* introspection (architecture.md §23). Read-only; returns the
|
|
2390
|
+
* already-sorted plugin list (post-`dependsOn` topo-sort).
|
|
2391
|
+
*/
|
|
2392
|
+
getPlugins(): readonly KickPlugin[];
|
|
2393
|
+
/**
|
|
2394
|
+
* Snapshot of every Context Contributor reachable from this app —
|
|
2395
|
+
* walks **four** registration sites: adapters, plugins, modules,
|
|
2396
|
+
* and the bootstrap `contributors` option. The devtools Topology
|
|
2397
|
+
* tab consumes this for the Contributors panel; tests + adopters
|
|
2398
|
+
* can call it for diagnostics.
|
|
2399
|
+
*
|
|
2400
|
+
* Per-route (method/class-decorator) registrations are NOT included
|
|
2401
|
+
* here — they live on the route registry rather than on any of
|
|
2402
|
+
* the four collection sites this method walks. A future RPC will
|
|
2403
|
+
* surface them separately.
|
|
2404
|
+
*
|
|
2405
|
+
* Result shape stays minimal — `{ key, source, label, dependsOn }`
|
|
2406
|
+
* — so we don't leak `resolve` closures or other internal fields.
|
|
2407
|
+
* `source` matches the five-level precedence union from
|
|
2408
|
+
* `ContributorSource` (minus `'method'` / `'class'` which require
|
|
2409
|
+
* the per-route walk noted above).
|
|
2410
|
+
*/
|
|
2411
|
+
/**
|
|
2412
|
+
* Every controller route the app mounted, with its full pattern and the
|
|
2413
|
+
* context contributors a request runs, in execution order — decorators
|
|
2414
|
+
* included. Devtools serves this per route.
|
|
2415
|
+
*/
|
|
2416
|
+
getRoutes(): readonly MountedRouteInfo[];
|
|
2417
|
+
getContributors(): ReadonlyArray<{
|
|
2418
|
+
key: string;
|
|
2419
|
+
source: 'method' | 'class' | 'module' | 'adapter' | 'plugin' | 'global';
|
|
2420
|
+
label: string;
|
|
2421
|
+
dependsOn: readonly string[];
|
|
2422
|
+
}>;
|
|
2423
|
+
getHttpServer(): KickServer | null;
|
|
2424
|
+
/**
|
|
2425
|
+
* Decide whether {@link Application} should auto-mount the
|
|
2426
|
+
* {@link requestScopeMiddleware} ALS wrapper.
|
|
2427
|
+
*
|
|
2428
|
+
* Returns `false` when:
|
|
2429
|
+
* - `contextStore: 'manual'` was set (caller manages ALS frames), or
|
|
2430
|
+
* - the user-supplied `middleware` list already includes a
|
|
2431
|
+
* `requestScopeMiddleware()` (detected via the symbol marker stamped
|
|
2432
|
+
* in `middleware/request-scope.ts`).
|
|
2433
|
+
*
|
|
2434
|
+
* Otherwise `true` — preserves the historical default of "always wrap
|
|
2435
|
+
* requests in an ALS frame" so existing apps see no behavior change.
|
|
2436
|
+
*/
|
|
2437
|
+
private shouldAutoMountRequestScope;
|
|
2438
|
+
private collectAdapterMiddleware;
|
|
2439
|
+
private mountMiddlewareList;
|
|
2440
|
+
private mountMiddlewareEntry;
|
|
2441
|
+
/**
|
|
2442
|
+
* `GET /_kick/cron/:scheduleId` — how a serverless platform
|
|
2443
|
+
* (Vercel crons) runs `@Cron` jobs: `kick build:vercel` emits one cron entry
|
|
2444
|
+
* per schedule pointing here. Mounted only in handler mode and only when
|
|
2445
|
+
* `CRON_SECRET` is set; the request must carry `Authorization: Bearer
|
|
2446
|
+
* $CRON_SECRET` (Vercel sends it). Runs every job on that schedule.
|
|
2447
|
+
*/
|
|
2448
|
+
private mountCronTrigger;
|
|
2449
|
+
/** Middleware that tracks in-flight requests for graceful draining */
|
|
2450
|
+
private requestTrackingMiddleware;
|
|
2451
|
+
}
|
|
2452
|
+
//#endregion
|
|
2453
|
+
//#region src/http/conditional.d.ts
|
|
2454
|
+
/**
|
|
2455
|
+
* Conditional requests (RFC 9110 §13): answer `304 Not Modified` when the
|
|
2456
|
+
* client's copy is current, and `412 Precondition Failed` when a write was
|
|
2457
|
+
* based on a stale one. Decided from validators the handler supplies — an
|
|
2458
|
+
* ETag, a last-modified time — before it does the expensive part.
|
|
2459
|
+
*
|
|
2460
|
+
* @module @forinda/kickjs/http/conditional
|
|
2461
|
+
*/
|
|
2462
|
+
/** What identifies the current version of a resource. */
|
|
2463
|
+
interface Validators {
|
|
2464
|
+
/**
|
|
2465
|
+
* An entity tag. Quoted for you if bare: `'v42'` → `"v42"`. Prefix with
|
|
2466
|
+
* `W/` for a weak tag (same meaning, not byte-identical).
|
|
2467
|
+
*/
|
|
2468
|
+
etag?: string;
|
|
2469
|
+
/** When the resource last changed. Compared to the second, as HTTP dates are. */
|
|
2470
|
+
lastModified?: Date;
|
|
2471
|
+
}
|
|
2472
|
+
/** 200: go on and respond. 304 / 412: answer with that status, no body. */
|
|
2473
|
+
type ConditionalOutcome = 200 | 304 | 412;
|
|
2474
|
+
type Headers = Record<string, string | string[] | undefined>;
|
|
2475
|
+
/**
|
|
2476
|
+
* The outcome of a request's preconditions against the current validators,
|
|
2477
|
+
* evaluated in RFC 9110 §13.2.2 order.
|
|
2478
|
+
*/
|
|
2479
|
+
declare function evaluatePreconditions(method: string, headers: Headers, validators: Validators): ConditionalOutcome;
|
|
2480
|
+
//#endregion
|
|
2481
|
+
//#region src/http/metrics.d.ts
|
|
2482
|
+
interface MetricsOptions {
|
|
2483
|
+
/** Where to serve the metrics. Default `/metrics`. */
|
|
2484
|
+
path?: string;
|
|
2485
|
+
/**
|
|
2486
|
+
* Require `Authorization: Bearer <token>` to read them. The endpoint is
|
|
2487
|
+
* mounted before the app's middleware (so a scraper doesn't need your
|
|
2488
|
+
* auth), which also means your auth doesn't cover it — set this unless
|
|
2489
|
+
* the port is only reachable by the scraper.
|
|
2490
|
+
*/
|
|
2491
|
+
token?: string;
|
|
2492
|
+
/** Histogram buckets, in seconds. Default: Prometheus' defaults, 5ms to 10s. */
|
|
2493
|
+
buckets?: number[];
|
|
2494
|
+
}
|
|
2495
|
+
/** The request histogram, keyed by its label set. */
|
|
2496
|
+
declare class RequestHistogram {
|
|
2497
|
+
private readonly series;
|
|
2498
|
+
private readonly buckets;
|
|
2499
|
+
/**
|
|
2500
|
+
* Bounds in seconds — sorted and deduplicated here, since the exposition
|
|
2501
|
+
* format needs them strictly increasing; anything not a finite positive
|
|
2502
|
+
* number is rejected.
|
|
2503
|
+
*/
|
|
2504
|
+
constructor(buckets?: readonly number[]);
|
|
2505
|
+
observe(info: Pick<ResponseInfo, 'method' | 'route' | 'status' | 'durationMs'>): void;
|
|
2506
|
+
render(): string;
|
|
2507
|
+
}
|
|
2508
|
+
/**
|
|
2509
|
+
* Serve Prometheus metrics. Add it to `adapters`:
|
|
2510
|
+
*
|
|
2511
|
+
* ```ts
|
|
2512
|
+
* bootstrap({ modules, adapters: [metricsAdapter({ token: process.env.METRICS_TOKEN })] })
|
|
2513
|
+
* ```
|
|
2514
|
+
*/
|
|
2515
|
+
declare function metricsAdapter(options?: MetricsOptions): AppAdapter;
|
|
2516
|
+
//#endregion
|
|
2517
|
+
//#region src/http/background.d.ts
|
|
2518
|
+
/**
|
|
2519
|
+
* Keep `promise` alive past the response. A rejection is logged (with the
|
|
2520
|
+
* request id when called during a request), never left unhandled.
|
|
2521
|
+
*
|
|
2522
|
+
* @example
|
|
2523
|
+
* ```ts
|
|
2524
|
+
* @Post('/')
|
|
2525
|
+
* async create(ctx: RequestContext) {
|
|
2526
|
+
* const order = await this.orders.create(ctx.body)
|
|
2527
|
+
* ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler
|
|
2528
|
+
* return order
|
|
2529
|
+
* }
|
|
2530
|
+
* ```
|
|
2531
|
+
*/
|
|
2532
|
+
declare function waitUntil(promise: Promise<unknown>): void;
|
|
2533
|
+
/**
|
|
2534
|
+
* Resolve once every registered promise has settled — including work
|
|
2535
|
+
* registered while waiting. Never rejects.
|
|
2536
|
+
*/
|
|
2537
|
+
declare function settleBackgroundWork(): Promise<void>;
|
|
2538
|
+
/**
|
|
2539
|
+
* The platform hook `createHandler()` and the web entry forward background
|
|
2540
|
+
* work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`
|
|
2541
|
+
* from `@vercel/functions` all have this shape.
|
|
2542
|
+
*/
|
|
2543
|
+
interface PlatformContext {
|
|
2544
|
+
waitUntil?(promise: Promise<unknown>): void;
|
|
2545
|
+
}
|
|
2546
|
+
//#endregion
|
|
2547
|
+
//#region src/http/body-policy.d.ts
|
|
2548
|
+
/**
|
|
2549
|
+
* Set to `true` on a request (`req[RAW_BODY] = true`) by middleware that will
|
|
2550
|
+
* read the body stream itself — a tus endpoint, a proxy — so the 415 below
|
|
2551
|
+
* leaves it alone. Mark it in an earlier phase (an adapter's `beforeGlobal`),
|
|
2552
|
+
* consume it later.
|
|
2553
|
+
*/
|
|
2554
|
+
declare const RAW_BODY: unique symbol;
|
|
2555
|
+
//#endregion
|
|
2556
|
+
//#region src/http/cron-adapter.d.ts
|
|
2557
|
+
/** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */
|
|
2558
|
+
declare const CRON_WORKER_ENV = "KICK_CRON_WORKER";
|
|
2559
|
+
interface CronAdapterOptions {
|
|
2560
|
+
/** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */
|
|
2561
|
+
enabled?: boolean;
|
|
2562
|
+
}
|
|
2563
|
+
declare const KickCronAdapter: AdapterFactory<CronAdapterOptions, unknown>;
|
|
2564
|
+
//#endregion
|
|
2565
|
+
//#region src/http/tracing.d.ts
|
|
2566
|
+
declare const HANDLER_CHANNEL = "kickjs:handler";
|
|
2567
|
+
declare const ERROR_CHANNEL = "kickjs:error";
|
|
2568
|
+
declare const RESPONSE_CHANNEL = "kickjs:response";
|
|
2569
|
+
/** What subscribers to `kickjs:handler` receive. */
|
|
2570
|
+
interface HandlerTraceContext {
|
|
2571
|
+
method: string;
|
|
2572
|
+
/** The route pattern, e.g. `/api/v1/users/:id` — the span name APMs want. */
|
|
2573
|
+
route: string;
|
|
2574
|
+
controller?: string;
|
|
2575
|
+
handler?: string;
|
|
2576
|
+
requestId?: string;
|
|
2577
|
+
ctx: RequestContext;
|
|
2578
|
+
}
|
|
2579
|
+
//#endregion
|
|
2580
|
+
//#region src/http/bootstrap.d.ts
|
|
2581
|
+
/**
|
|
2582
|
+
* Bootstrap a KickJS application.
|
|
2583
|
+
*
|
|
2584
|
+
* Creates the Express app, registers modules and adapters, and starts
|
|
2585
|
+
* the HTTP server. In dev mode (`kick dev`), the Vite plugin manages
|
|
2586
|
+
* the server and HMR — source changes are picked up instantly without
|
|
2587
|
+
* losing database connections or WebSocket state.
|
|
2588
|
+
*
|
|
2589
|
+
* @returns The {@link Application} instance.
|
|
2590
|
+
*
|
|
2591
|
+
* @example
|
|
2592
|
+
* ```ts
|
|
2593
|
+
* // src/index.ts
|
|
2594
|
+
* import 'reflect-metadata'
|
|
2595
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
2596
|
+
* import { modules } from './modules'
|
|
2597
|
+
*
|
|
2598
|
+
* export const app = await bootstrap({ modules })
|
|
2599
|
+
* ```
|
|
2600
|
+
*/
|
|
2601
|
+
declare function bootstrap(options: ApplicationOptions): Promise<Application>;
|
|
2602
|
+
//#endregion
|
|
2603
|
+
//#region src/http/handler.d.ts
|
|
2604
|
+
/** A KickJS app exposed as request handlers. See {@link createHandler}. */
|
|
2605
|
+
interface KickHandler {
|
|
2606
|
+
/**
|
|
2607
|
+
* Web-standard handler: `fetch(Request) → Response`. Netlify Functions,
|
|
2608
|
+
* Vercel's fetch export, and anything else that speaks `Request`.
|
|
2609
|
+
*
|
|
2610
|
+
* Pass the platform context (Netlify's `context`, `{ waitUntil }` from
|
|
2611
|
+
* `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after
|
|
2612
|
+
* the response instead of being frozen with the instance.
|
|
2613
|
+
*/
|
|
2614
|
+
fetch(request: Request, platform?: PlatformContext): Promise<Response>;
|
|
2615
|
+
/** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */
|
|
2616
|
+
node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>;
|
|
2617
|
+
/** Set the app up now instead of on the first request (warm-up). */
|
|
2618
|
+
ready(): Promise<Application>;
|
|
2619
|
+
/** Shut adapters down and stop the internal forwarding server, if one started. */
|
|
2620
|
+
close(): Promise<void>;
|
|
2621
|
+
}
|
|
2622
|
+
/**
|
|
2623
|
+
* Build a KickJS app as request handlers instead of a listening server.
|
|
2624
|
+
*
|
|
2625
|
+
* Takes the same options as `bootstrap()`, or a function that imports the
|
|
2626
|
+
* app's entry — the file that calls `bootstrap()`. With the entry, the app
|
|
2627
|
+
* is built from that one `bootstrap({ ... })` call, so the server and the
|
|
2628
|
+
* function never drift apart:
|
|
2629
|
+
*
|
|
2630
|
+
* ```ts
|
|
2631
|
+
* // src/serverless.ts
|
|
2632
|
+
* export const handler = createHandler(() => import('./index'))
|
|
2633
|
+
* ```
|
|
2634
|
+
*
|
|
2635
|
+
* While the entry loads, its `bootstrap()` call builds the app without
|
|
2636
|
+
* starting it — no port, no process signal handlers, no cluster. The app is set up once per process
|
|
2637
|
+
* (per function instance), lazily on the first request, and reused after that.
|
|
2638
|
+
* Nothing listens on a port, `afterStart` does not run, and no process signal
|
|
2639
|
+
* handlers are registered — the platform owns the process.
|
|
2640
|
+
*
|
|
2641
|
+
* `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).
|
|
2642
|
+
* Runtimes built on Node request/response objects — Express, the default —
|
|
2643
|
+
* are served through a server bound to `127.0.0.1` on a random port inside the
|
|
2644
|
+
* same process, started on first use: the `Request` is forwarded to it and its
|
|
2645
|
+
* response returned. Request bodies are buffered on that path; response bodies
|
|
2646
|
+
* stream. Adapters that rewrite the `res` prototype (Express does) make a
|
|
2647
|
+
* direct Request→`res` bridge unreliable, which is why this forwards instead.
|
|
2648
|
+
*
|
|
2649
|
+
* One handler per process: the DI container is process-wide.
|
|
2650
|
+
*
|
|
2651
|
+
* @example
|
|
2652
|
+
* ```ts
|
|
2653
|
+
* // server/src/serverless.ts
|
|
2654
|
+
* import 'reflect-metadata'
|
|
2655
|
+
* import './config'
|
|
2656
|
+
* import { createHandler } from '@forinda/kickjs'
|
|
2657
|
+
* import { modules } from './modules'
|
|
2658
|
+
*
|
|
2659
|
+
* export const handler = createHandler({ modules })
|
|
2660
|
+
*
|
|
2661
|
+
* // netlify/functions/api.mjs
|
|
2662
|
+
* export default (request, context) => handler.fetch(request, context)
|
|
2663
|
+
* export const config = { path: '/api/*' }
|
|
2664
|
+
* ```
|
|
2665
|
+
*/
|
|
2666
|
+
declare function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler;
|
|
2667
|
+
//#endregion
|
|
2668
|
+
//#region src/http/cluster.d.ts
|
|
2669
|
+
interface ClusterOptions {
|
|
2670
|
+
/** Number of worker processes (default: os.cpus().length) */
|
|
2671
|
+
workers?: number;
|
|
2672
|
+
/** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */
|
|
2673
|
+
gracefulShutdownTimeout?: number;
|
|
2674
|
+
/** Delay between worker restarts (ms), default: 1000 */
|
|
2675
|
+
restartDelay?: number;
|
|
2676
|
+
/** Max failures in restartWindow before refusing to restart, default: 5 */
|
|
2677
|
+
maxFailures?: number;
|
|
2678
|
+
/** Time window for counting failures (ms), default: 30000 */
|
|
2679
|
+
restartWindow?: number;
|
|
2680
|
+
}
|
|
2681
|
+
/** Returns true if the current process is the cluster primary */
|
|
2682
|
+
declare function isClusterPrimary(): boolean;
|
|
2683
|
+
//#endregion
|
|
2684
|
+
//#region src/http/define-http-context-decorator.d.ts
|
|
2685
|
+
/**
|
|
2686
|
+
* Curried form returned by {@link DefineHttpContextDecoratorFn.withParams}.
|
|
2687
|
+
* Spell only the per-call params shape `P`; `K` and `D` are inferred
|
|
2688
|
+
* from the spec, and `Ctx` is locked to `RequestContext`.
|
|
2689
|
+
*/
|
|
2690
|
+
interface DefineHttpContextDecoratorWithParams<P extends Record<string, unknown>> {
|
|
2691
|
+
<K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext>;
|
|
2692
|
+
}
|
|
2693
|
+
/**
|
|
2694
|
+
* Public shape of {@link defineHttpContextDecorator} — the positional
|
|
2695
|
+
* call signature plus the curried `.withParams<P>()` helper that fixes
|
|
2696
|
+
* partial-inference for the parameterised case.
|
|
2697
|
+
*/
|
|
2698
|
+
interface DefineHttpContextDecoratorFn {
|
|
2699
|
+
<K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>, P extends Record<string, unknown> = Record<string, never>>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext>;
|
|
2700
|
+
/**
|
|
2701
|
+
* Curried entry point. Spell only `P`; `K` and `D` infer from the
|
|
2702
|
+
* spec. `Ctx` is locked to `RequestContext`.
|
|
2703
|
+
*
|
|
2704
|
+
* ```ts
|
|
2705
|
+
* const LoadTenant = defineHttpContextDecorator.withParams<{
|
|
2706
|
+
* source: 'header' | 'subdomain'
|
|
2707
|
+
* }>()({
|
|
2708
|
+
* key: 'tenant',
|
|
2709
|
+
* deps: { repo: TENANT_REPO }, // D inferred
|
|
2710
|
+
* paramDefaults: { source: 'header' },
|
|
2711
|
+
* resolve: (ctx, { repo }, params) => repo.findFor(ctx, params),
|
|
2712
|
+
* })
|
|
2713
|
+
* ```
|
|
2714
|
+
*/
|
|
2715
|
+
withParams<P extends Record<string, unknown>>(): DefineHttpContextDecoratorWithParams<P>;
|
|
2716
|
+
}
|
|
2717
|
+
declare const defineHttpContextDecorator: DefineHttpContextDecoratorFn;
|
|
2718
|
+
//#endregion
|
|
2719
|
+
//#region src/core/password.d.ts
|
|
2720
|
+
/** scrypt cost. Memory per hash is `128 * N * r` bytes. */
|
|
2721
|
+
interface PasswordHashOptions {
|
|
2722
|
+
/** CPU/memory cost, a power of two. Default `2 ** 14`. */
|
|
2723
|
+
N?: number;
|
|
2724
|
+
/** Block size. Default `8`. */
|
|
2725
|
+
r?: number;
|
|
2726
|
+
/** Parallelism. Default `5`. */
|
|
2727
|
+
p?: number;
|
|
2728
|
+
}
|
|
2729
|
+
/**
|
|
2730
|
+
* Hash a password for storage: `scrypt$N$r$p$salt$hash`, salt and hash in
|
|
2731
|
+
* base64. The same password hashes differently every time.
|
|
2732
|
+
*/
|
|
2733
|
+
declare function hashPassword(password: string, options?: PasswordHashOptions): Promise<string>;
|
|
2734
|
+
/** What {@link verifyPassword} returns. */
|
|
2735
|
+
interface PasswordCheck {
|
|
2736
|
+
/** The password matches. */
|
|
2737
|
+
ok: boolean;
|
|
2738
|
+
/**
|
|
2739
|
+
* The hash was made with a different cost than `options` (the defaults):
|
|
2740
|
+
* hash the password again and store it. Only ever true when `ok` is.
|
|
2741
|
+
*/
|
|
2742
|
+
needsRehash: boolean;
|
|
2743
|
+
}
|
|
2744
|
+
/**
|
|
2745
|
+
* Check a password against a stored hash. Constant-time, and pass
|
|
2746
|
+
* `undefined` for a user that doesn't exist: the password is still hashed,
|
|
2747
|
+
* so a missing account takes as long to reject as a wrong password and the
|
|
2748
|
+
* timing doesn't reveal which accounts exist. A hash not in this format
|
|
2749
|
+
* (another algorithm, or corrupt) fails rather than throws.
|
|
2750
|
+
*/
|
|
2751
|
+
declare function verifyPassword(password: string, stored: string | null | undefined, options?: PasswordHashOptions): Promise<PasswordCheck>;
|
|
2752
|
+
//#endregion
|
|
2753
|
+
//#region src/core/signing.d.ts
|
|
2754
|
+
interface SignerOptions {
|
|
2755
|
+
/**
|
|
2756
|
+
* The signing secret. Pass a list to rotate: the first signs, every one
|
|
2757
|
+
* verifies. Drop the old one once its tokens have expired.
|
|
2758
|
+
*/
|
|
2759
|
+
secret: string | string[];
|
|
2760
|
+
/**
|
|
2761
|
+
* What the tokens are for — `'password-reset'`, `'unsubscribe'`. Signers
|
|
2762
|
+
* with different salts reject each other's tokens even with the same
|
|
2763
|
+
* secret, so a token issued for one purpose can't be used for another.
|
|
2764
|
+
*/
|
|
2765
|
+
salt: string;
|
|
2766
|
+
}
|
|
2767
|
+
interface VerifyOptions {
|
|
2768
|
+
/** Reject tokens older than this, in milliseconds. */
|
|
2769
|
+
maxAge?: number;
|
|
2770
|
+
}
|
|
2771
|
+
/** What {@link Signer.verify} returns. */
|
|
2772
|
+
type SignedCheck<T> = {
|
|
2773
|
+
ok: true;
|
|
2774
|
+
value: T;
|
|
2775
|
+
issuedAt: Date;
|
|
2776
|
+
} | {
|
|
2777
|
+
ok: false;
|
|
2778
|
+
reason: 'invalid' | 'expired';
|
|
2779
|
+
};
|
|
2780
|
+
interface Signer {
|
|
2781
|
+
/** Sign a JSON-serialisable value: `payload.timestamp.signature`, URL-safe. */
|
|
2782
|
+
sign(value: unknown): string;
|
|
2783
|
+
/** Check a token's signature and, with `maxAge`, its age. Never throws. */
|
|
2784
|
+
verify<T = unknown>(token: string, options?: VerifyOptions): SignedCheck<T>;
|
|
2785
|
+
}
|
|
2786
|
+
/** Create a signer for one purpose. */
|
|
2787
|
+
declare function createSigner(options: SignerOptions): Signer;
|
|
2788
|
+
//#endregion
|
|
2789
|
+
//#region src/http/router-builder.d.ts
|
|
2790
|
+
/** @internal — set by Application.setup() before each `mod.routes()` call. */
|
|
2791
|
+
declare function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void;
|
|
2792
|
+
/**
|
|
2793
|
+
* Boot-time duplicate-route guard shared by the node and web mount loops.
|
|
2794
|
+
*
|
|
2795
|
+
* Registers `METHOD /mounted/path` into `registry` and throws
|
|
2796
|
+
* {@link duplicateRouteError} (KICK006) if another handler already claimed
|
|
2797
|
+
* it. Param *names* are ignored — `/tasks/:id` and `/tasks/:taskId` are the
|
|
2798
|
+
* same route at dispatch time, so they collide here too.
|
|
2799
|
+
*
|
|
2800
|
+
* @internal
|
|
2801
|
+
*/
|
|
2802
|
+
declare function assertRouteUnique(registry: Map<string, string>, method: string, fullPath: string, owner: string): void;
|
|
2803
|
+
interface BuildRoutesOptions {
|
|
2804
|
+
/**
|
|
2805
|
+
* Extra contributors to merge into the per-route pipeline at their declared
|
|
2806
|
+
* precedence levels. Pass explicitly when calling buildRouteTable/buildRoutes
|
|
2807
|
+
* outside the Application route-mount loop (typically in tests). When omitted,
|
|
2808
|
+
* falls back to the slot set by Application.setup().
|
|
2809
|
+
*/
|
|
2810
|
+
externalSources?: readonly SourcedRegistration[];
|
|
2811
|
+
/**
|
|
2812
|
+
* Flags the mounting module declares for every route on this controller
|
|
2813
|
+
* (`ModuleRoutes.flags`). Lowest precedence — a class or method declaration
|
|
2814
|
+
* of the same name wins, and `@Flag.off` on a method removes it.
|
|
2815
|
+
*/
|
|
2816
|
+
mountFlags?: RouteFlagDeclarations;
|
|
2817
|
+
}
|
|
2818
|
+
/**
|
|
2819
|
+
* Turn a controller class decorated with @Get, @Post, etc. into a plain-data
|
|
2820
|
+
* {@link RouteEntry}[] — the engine-neutral route table an {@link HttpRuntime}
|
|
2821
|
+
* materializes.
|
|
2822
|
+
*
|
|
2823
|
+
* What used to be per-handler Express `(req, res, next)` closures is now
|
|
2824
|
+
* captured as data: `middlewares` keep their `(ctx, next)` shape, the contributor
|
|
2825
|
+
* pipeline is pre-built into a `contributorRunner` closure, validation / upload
|
|
2826
|
+
* stay as metadata, and the terminal `handler` resolves the controller per-request
|
|
2827
|
+
* (to respect DI scoping) and invokes it. The runtime owns how these get wrapped
|
|
2828
|
+
* onto its engine.
|
|
2829
|
+
*
|
|
2830
|
+
* Routes use only the method-level decorator paths (e.g. @Get('/me') → '/me').
|
|
2831
|
+
* The @Controller path is NOT baked in — it is metadata for Swagger/introspection.
|
|
2832
|
+
* The module's routes().path is the single source of truth for the mount prefix,
|
|
2833
|
+
* which avoids path doubling when both the module and controller specify the path.
|
|
2834
|
+
*
|
|
2835
|
+
* The contributor pipeline is built here, so a cycle or missing `dependsOn`
|
|
2836
|
+
* throws at table-build time (boot) rather than on first request.
|
|
2837
|
+
*/
|
|
2838
|
+
declare function buildRouteTable(controllerClass: any, options?: BuildRoutesOptions): RouteEntry[];
|
|
2839
|
+
//#endregion
|
|
2840
|
+
//#region src/http/runtimes/express.d.ts
|
|
2841
|
+
/**
|
|
2842
|
+
* Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.
|
|
2843
|
+
* Reproduces the legacy handler ordering precisely: validation → upload →
|
|
2844
|
+
* `(ctx, next)` middleware → contributor runner → terminal handler, with
|
|
2845
|
+
* `beforeValidation` contributors ahead of validation. Each step
|
|
2846
|
+
* constructs its own `RequestContext` over the same `req`/`res` — request-scoped
|
|
2847
|
+
* state lives in the AsyncLocalStorage store, not on the ctx instance, so the
|
|
2848
|
+
* per-step instances share state exactly as before.
|
|
2849
|
+
*/
|
|
2850
|
+
declare function materializeRouter(entries: RouteEntry[]): Router;
|
|
2851
|
+
/**
|
|
2852
|
+
* Build an Express Router from a controller class decorated with @Get, @Post,
|
|
2853
|
+
* etc. The public, back-compatible entry point: a thin shim over
|
|
2854
|
+
* {@link buildRouteTable} + {@link materializeRouter}. Returns an
|
|
2855
|
+
* `express.Router` exactly as before — modules pass it to `app.use(path, router)`.
|
|
2856
|
+
*
|
|
2857
|
+
* @see buildRouteTable for the engine-neutral route-table form.
|
|
2858
|
+
*/
|
|
2859
|
+
declare function buildRoutes(controllerClass: any, options?: BuildRoutesOptions): Router;
|
|
2860
|
+
/**
|
|
2861
|
+
* The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;
|
|
2862
|
+
* apps that pass no `runtime` get this and behave exactly as before.
|
|
2863
|
+
*/
|
|
2864
|
+
declare function expressRuntime(): HttpRuntime<Express$1>;
|
|
2865
|
+
//#endregion
|
|
2866
|
+
//#region src/http/request-store.d.ts
|
|
2867
|
+
/** Per-request storage for REQUEST-scoped DI and request context propagation */
|
|
2868
|
+
interface RequestStore {
|
|
2869
|
+
/** Unique request identifier */
|
|
2870
|
+
requestId: string;
|
|
2871
|
+
/**
|
|
2872
|
+
* Per-request singleton cache for REQUEST-scoped services. Keys are
|
|
2873
|
+
* heterogeneous (class constructors, `InjectionToken` objects, raw
|
|
2874
|
+
* strings), so the map type stays `Map<any, any>`.
|
|
2875
|
+
*/
|
|
2876
|
+
instances: Map<any, any>;
|
|
2877
|
+
/**
|
|
2878
|
+
* Per-request key/value bag. Canonical backing store for
|
|
2879
|
+
* `RequestContext.set/get` and the Context Contributor pipeline (#107)
|
|
2880
|
+
* since Phase 3. Anything written here is visible to every concrete
|
|
2881
|
+
* execution context constructed for the same request, regardless of
|
|
2882
|
+
* which middleware/contributor wrote it.
|
|
2883
|
+
*
|
|
2884
|
+
* Keys are constrained to `string` per the locked decision in
|
|
2885
|
+
* `architecture.md` §20.12 (#4); the value type is `unknown` because
|
|
2886
|
+
* the concrete shape at each key is determined by the consumer's
|
|
2887
|
+
* `ContextMeta` augmentation, not by the store itself.
|
|
2888
|
+
*
|
|
2889
|
+
* Prefer the {@link getRequestValue} helper over reaching into this
|
|
2890
|
+
* map directly — it threads the augmented `ContextMeta` shape through
|
|
2891
|
+
* `MetaValue<K>` so consumers get typed reads without an `as` cast.
|
|
2892
|
+
* Writes should flow through `ctx.set(key, value)` or a Context
|
|
2893
|
+
* Contributor's return value — see the `setRequestValue` note below
|
|
2894
|
+
* for why this package intentionally does NOT ship a service-level
|
|
2895
|
+
* write helper.
|
|
2896
|
+
*/
|
|
2897
|
+
values: Map<string, unknown>;
|
|
2898
|
+
/** Set once {@link disposeRequestStore} has run — guards double-dispose. */
|
|
2899
|
+
disposed?: boolean;
|
|
2900
|
+
}
|
|
2901
|
+
/** AsyncLocalStorage instance shared across the framework */
|
|
2902
|
+
declare const requestStore: AsyncLocalStorage<RequestStore>;
|
|
2903
|
+
/**
|
|
2904
|
+
* Get the current request store. Throws if called outside a request context.
|
|
2905
|
+
* Used by the Container to resolve REQUEST-scoped dependencies.
|
|
2906
|
+
*/
|
|
2907
|
+
declare function getRequestStore(): RequestStore;
|
|
2908
|
+
/**
|
|
2909
|
+
* Read a per-request `ContextMeta`-keyed value from outside a controller
|
|
2910
|
+
* (services, repositories, anywhere with no `ctx` reference). Returns
|
|
2911
|
+
* the augmented type for the key — `MetaValue<K>` — so consumers get the
|
|
2912
|
+
* same static safety as `ctx.get(key)` without holding the context.
|
|
2913
|
+
*
|
|
2914
|
+
* Returns `undefined` outside an active request frame (background jobs,
|
|
2915
|
+
* startup code, tests without `requestScopeMiddleware()`) — the helper
|
|
2916
|
+
* is intentionally null-tolerant so calling it from a service that
|
|
2917
|
+
* runs in both request and non-request paths doesn't throw.
|
|
2918
|
+
*
|
|
2919
|
+
* @example
|
|
2920
|
+
* ```ts
|
|
2921
|
+
* declare module '@forinda/kickjs' {
|
|
2922
|
+
* interface ContextMeta { tenant: { id: string; name: string } }
|
|
2923
|
+
* }
|
|
2924
|
+
*
|
|
2925
|
+
* @Service()
|
|
2926
|
+
* class AuditService {
|
|
2927
|
+
* log(action: string) {
|
|
2928
|
+
* const tenant = getRequestValue('tenant') // typed: { id; name } | undefined
|
|
2929
|
+
* db.audit.insert({ action, tenantId: tenant?.id })
|
|
2930
|
+
* }
|
|
2931
|
+
* }
|
|
2932
|
+
* ```
|
|
2933
|
+
*/
|
|
2934
|
+
declare function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined;
|
|
2935
|
+
//#endregion
|
|
2936
|
+
//#region src/http/middleware/request-scope.d.ts
|
|
2937
|
+
/**
|
|
2938
|
+
* Wraps each request in an AsyncLocalStorage context.
|
|
2939
|
+
* Enables REQUEST-scoped DI and automatic requestId propagation to logs.
|
|
2940
|
+
*
|
|
2941
|
+
* Should be mounted early in the middleware pipeline (before route handlers).
|
|
2942
|
+
* `Application` mounts this automatically unless `contextStore: 'manual'` is set
|
|
2943
|
+
* or the user already includes one in their middleware list.
|
|
2944
|
+
*/
|
|
2945
|
+
declare function requestScopeMiddleware(): (req: Request$1, res: Response$1, next: NextFunction) => void;
|
|
2946
|
+
//#endregion
|
|
2947
|
+
//#region src/http/middleware/error-handler.d.ts
|
|
2948
|
+
/**
|
|
2949
|
+
* The slice of the request this handler reads, spelled from node's
|
|
2950
|
+
* `IncomingMessage` rather than Express's `Request`.
|
|
2951
|
+
*
|
|
2952
|
+
* Fastify and h3 hand the error handler `request.raw` — a plain
|
|
2953
|
+
* `IncomingMessage` — so anything Express-only is `undefined` there. This is
|
|
2954
|
+
* the default handler for EVERY runtime, so it must not assume Express.
|
|
2955
|
+
*/
|
|
2956
|
+
interface ErrorRequest {
|
|
2957
|
+
method?: string;
|
|
2958
|
+
url?: string;
|
|
2959
|
+
/** Express-only; absent on the raw node request the other runtimes pass. */
|
|
2960
|
+
originalUrl?: string;
|
|
2961
|
+
headers: Record<string, string | string[] | undefined>;
|
|
2962
|
+
}
|
|
2963
|
+
/** A mounted route, as the catch-all needs to see it. */
|
|
2964
|
+
interface MountedRoute {
|
|
2965
|
+
method: string;
|
|
2966
|
+
/** Full path as mounted, `:param` segments included. */
|
|
2967
|
+
path: string;
|
|
2968
|
+
}
|
|
2969
|
+
/**
|
|
2970
|
+
* Catch-all for unmatched routes.
|
|
2971
|
+
*
|
|
2972
|
+
* Answers RFC 9457 problem details, like every other error the framework
|
|
2973
|
+
* produces — the catch-all was the one path still emitting a bare
|
|
2974
|
+
* `{ message }`, so a client parsing `application/problem+json` had to special
|
|
2975
|
+
* case it.
|
|
2976
|
+
*
|
|
2977
|
+
* Distinguishes a path that does not exist from a path that does not accept
|
|
2978
|
+
* this method. `DELETE /things/1` where only `GET` is mounted is a **405** with
|
|
2979
|
+
* an `Allow` header, not a 404: the resource is there, the verb is not, and
|
|
2980
|
+
* 404 tells a client to stop looking for something that exists. Requires the
|
|
2981
|
+
* mounted route table, so an app that does not pass one keeps answering 404.
|
|
2982
|
+
*/
|
|
2983
|
+
declare function notFoundHandler(routes?: readonly MountedRoute[]): (req: ErrorRequest, res: RuntimeResponse, _next: () => void) => RuntimeResponse;
|
|
2984
|
+
/**
|
|
2985
|
+
* Global error handler.
|
|
2986
|
+
*
|
|
2987
|
+
* Default behavior strips error `details` from the response in production
|
|
2988
|
+
* (NODE_ENV === 'production') so internal context (DB errors, validation
|
|
2989
|
+
* issues, custom payloads) does not leak to clients. Apps that want to
|
|
2990
|
+
* expose details in production — for client-facing field-level validation,
|
|
2991
|
+
* for example — should pass their own `onError` to `bootstrap()` and decide
|
|
2992
|
+
* the policy explicitly.
|
|
2993
|
+
*
|
|
2994
|
+
* Unexpected 500s carry `requestId` in every environment (the correlation
|
|
2995
|
+
* handle back to the log line) and, outside production, the error summary
|
|
2996
|
+
* plus stack. Production bodies stay opaque.
|
|
2997
|
+
*
|
|
2998
|
+
* {@link ProblemException} and plain {@link HttpException} both emit
|
|
2999
|
+
* `application/problem+json` per RFC 9457. `ProblemException` carries a
|
|
3000
|
+
* caller-supplied `type` / `title` / extensions; an `HttpException`'s message
|
|
3001
|
+
* becomes `detail`, with `title` and `type` defaulted from the status. One
|
|
3002
|
+
* shape, so a client never has to branch on which one the app threw.
|
|
3003
|
+
*/
|
|
3004
|
+
declare function errorHandler(): (err: any, req: ErrorRequest, res: RuntimeResponse, _next: () => void) => RuntimeResponse | undefined;
|
|
3005
|
+
//#endregion
|
|
3006
|
+
//#region src/http/middleware/rate-limit-guard.d.ts
|
|
3007
|
+
interface RateLimitGuardOptions {
|
|
3008
|
+
/** Maximum number of requests per window (default: 100). */
|
|
3009
|
+
max?: number;
|
|
3010
|
+
/** Time window in milliseconds (default: 60_000). */
|
|
3011
|
+
windowMs?: number;
|
|
3012
|
+
/** Response message when the limit is exceeded (default: 'Too Many Requests'). */
|
|
3013
|
+
message?: string;
|
|
3014
|
+
/** HTTP status code when the limit is exceeded (default: 429). */
|
|
3015
|
+
statusCode?: number;
|
|
3016
|
+
/**
|
|
3017
|
+
* Rate-limit key per request. Defaults to `ctx.ip`, falling back to
|
|
3018
|
+
* `'global'`. Return a user/tenant id here for authenticated quotas.
|
|
3019
|
+
*
|
|
3020
|
+
* ::: warning Behind a proxy, configure `trustProxy` or every client shares
|
|
3021
|
+
* one bucket
|
|
3022
|
+
* On a node runtime `ctx.ip` is the runtime's vetted client address —
|
|
3023
|
+
* Express derives it from `trust proxy`, Fastify from `trustProxy`. Without
|
|
3024
|
+
* that setting it is the SOCKET address, which behind a load balancer or
|
|
3025
|
+
* Cloudflare is the proxy's, so every caller lands in the same bucket and one
|
|
3026
|
+
* noisy client exhausts the allowance for everyone.
|
|
3027
|
+
*
|
|
3028
|
+
* `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are
|
|
3029
|
+
* deliberately not consulted here: `x-forwarded-for` is client-controllable
|
|
3030
|
+
* unless a proxy overwrites it, so trusting it unconditionally would let a
|
|
3031
|
+
* direct caller mint a fresh allowance per request by varying the header —
|
|
3032
|
+
* evading the limit rather than enforcing it. The header chain
|
|
3033
|
+
* (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the
|
|
3034
|
+
* `@forinda/kickjs/web` edge entry, where there is no socket and the platform
|
|
3035
|
+
* has already terminated the connection.
|
|
3036
|
+
* :::
|
|
3037
|
+
*/
|
|
3038
|
+
keyGenerator?: (ctx: RequestContext) => string;
|
|
3039
|
+
/** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */
|
|
3040
|
+
headers?: boolean;
|
|
3041
|
+
/**
|
|
3042
|
+
* Counter backend. Defaults to a per-isolate in-memory map — fine for a
|
|
3043
|
+
* single node process, useless on edge where isolates recycle: pass a
|
|
3044
|
+
* `KvRateLimitStore` (or Redis-backed store) there.
|
|
3045
|
+
*/
|
|
3046
|
+
store?: RateLimitStore;
|
|
3047
|
+
/** Skip limiting for a request (health checks, allowlists). */
|
|
3048
|
+
skip?: (ctx: RequestContext) => boolean;
|
|
3049
|
+
/**
|
|
3050
|
+
* Skip limiting on routes carrying a route flag — a name, a list of names
|
|
3051
|
+
* (any-of), or a predicate. Declared on the route rather than restated as a
|
|
3052
|
+
* path here, so it cannot drift when `apiPrefix` or a module's `version`
|
|
3053
|
+
* changes:
|
|
3054
|
+
*
|
|
3055
|
+
* ```ts
|
|
3056
|
+
* const Public = defineRouteFlag('auth.public')
|
|
3057
|
+
* rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })
|
|
3058
|
+
* ```
|
|
3059
|
+
*
|
|
3060
|
+
* Only meaningful where a route has been matched — as `@Middleware()` on a
|
|
3061
|
+
* class or method, or in `createWebApp({ middleware })`. Mounted app-wide
|
|
3062
|
+
* ahead of routing there is no route to read, and nothing is exempted.
|
|
3063
|
+
*/
|
|
3064
|
+
exemptWhen?: RouteFlagTest;
|
|
3065
|
+
}
|
|
3066
|
+
/**
|
|
3067
|
+
* Rate limiting as a `(ctx, next)` middleware.
|
|
3068
|
+
*
|
|
3069
|
+
* ```ts
|
|
3070
|
+
* // Edge (Cloudflare Workers) — app-wide:
|
|
3071
|
+
* const app = createWebApp({
|
|
3072
|
+
* h3, modules,
|
|
3073
|
+
* middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],
|
|
3074
|
+
* })
|
|
3075
|
+
*
|
|
3076
|
+
* // Any runtime — per controller/route:
|
|
3077
|
+
* @Middleware(rateLimitGuard({ max: 10 }))
|
|
3078
|
+
* @Post('/login')
|
|
3079
|
+
* ```
|
|
3080
|
+
*/
|
|
3081
|
+
declare function rateLimitGuard(options?: RateLimitGuardOptions): MiddlewareHandler;
|
|
3082
|
+
//#endregion
|
|
3083
|
+
//#region src/http/middleware/kv-stores.d.ts
|
|
3084
|
+
/**
|
|
3085
|
+
* The minimal async KV surface both stores need. Structurally compatible
|
|
3086
|
+
* with a Cloudflare Workers `KVNamespace` binding — pass it straight in:
|
|
3087
|
+
*
|
|
3088
|
+
* ```ts
|
|
3089
|
+
* export default {
|
|
3090
|
+
* fetch(req: Request, env: Env) {
|
|
3091
|
+
* const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })
|
|
3092
|
+
* // ...
|
|
3093
|
+
* },
|
|
3094
|
+
* }
|
|
3095
|
+
* ```
|
|
3096
|
+
*
|
|
3097
|
+
* Anything with the same shape works too (Deno KV wrapper, Upstash Redis
|
|
3098
|
+
* REST client adapter, a Map-backed fake in tests).
|
|
3099
|
+
*/
|
|
3100
|
+
interface KvLike {
|
|
3101
|
+
get(key: string): Promise<string | null>;
|
|
3102
|
+
put(key: string, value: string, options?: {
|
|
3103
|
+
expirationTtl?: number;
|
|
3104
|
+
}): Promise<void>;
|
|
3105
|
+
delete(key: string): Promise<void>;
|
|
3106
|
+
}
|
|
3107
|
+
interface KvRateLimitStoreOptions {
|
|
3108
|
+
/** Window length in ms — must match the `windowMs` given to the limiter. */
|
|
3109
|
+
windowMs: number;
|
|
3110
|
+
/** Key prefix in the KV namespace (default `'rl:'`). */
|
|
3111
|
+
prefix?: string;
|
|
3112
|
+
}
|
|
3113
|
+
/**
|
|
3114
|
+
* {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments
|
|
3115
|
+
* where in-memory counters reset on every isolate.
|
|
3116
|
+
*
|
|
3117
|
+
* KV is eventually consistent and this is a read-modify-write counter, so
|
|
3118
|
+
* limiting is **approximate** under concurrency — bursts racing across
|
|
3119
|
+
* isolates can each read the same count. That is the accepted trade-off for
|
|
3120
|
+
* abuse throttling; use a Durable Object / Redis store when you need an
|
|
3121
|
+
* exact ceiling (billing quotas, strict per-key locks).
|
|
3122
|
+
*/
|
|
3123
|
+
declare class KvRateLimitStore implements RateLimitStore {
|
|
3124
|
+
private readonly kv;
|
|
3125
|
+
private readonly prefix;
|
|
3126
|
+
private readonly windowMs;
|
|
3127
|
+
constructor(kv: KvLike, options: KvRateLimitStoreOptions);
|
|
3128
|
+
increment(key: string): Promise<{
|
|
3129
|
+
totalHits: number;
|
|
3130
|
+
resetTime: Date;
|
|
3131
|
+
}>;
|
|
3132
|
+
decrement(key: string): Promise<void>;
|
|
3133
|
+
reset(key: string): Promise<void>;
|
|
3134
|
+
private read;
|
|
3135
|
+
private write;
|
|
3136
|
+
}
|
|
3137
|
+
interface KvSessionStoreOptions {
|
|
3138
|
+
/** Key prefix in the KV namespace (default `'sess:'`). */
|
|
3139
|
+
prefix?: string;
|
|
3140
|
+
}
|
|
3141
|
+
/**
|
|
3142
|
+
* {@link SessionStore} over a {@link KvLike} namespace. Plug into the node
|
|
3143
|
+
* `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via
|
|
3144
|
+
* REST) so sessions survive restarts and horizontal scaling; TTL expiry is
|
|
3145
|
+
* delegated to the KV layer via `expirationTtl`.
|
|
3146
|
+
*
|
|
3147
|
+
* Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only
|
|
3148
|
+
* refresh), so `session({ rolling: true })` doubles KV operations per
|
|
3149
|
+
* request — per-operation-billed platforms may prefer `rolling: false`.
|
|
3150
|
+
*/
|
|
3151
|
+
declare class KvSessionStore implements SessionStore {
|
|
3152
|
+
private readonly kv;
|
|
3153
|
+
private readonly prefix;
|
|
3154
|
+
constructor(kv: KvLike, options?: KvSessionStoreOptions);
|
|
3155
|
+
get(sid: string): Promise<SessionData | null>;
|
|
3156
|
+
set(sid: string, data: SessionData, maxAge: number): Promise<void>;
|
|
3157
|
+
destroy(sid: string): Promise<void>;
|
|
3158
|
+
touch(sid: string, maxAge: number): Promise<void>;
|
|
3159
|
+
}
|
|
3160
|
+
//#endregion
|
|
3161
|
+
//#region src/http/middleware/upload-config.d.ts
|
|
3162
|
+
/**
|
|
3163
|
+
* Resolves a list of file type identifiers to MIME type strings.
|
|
3164
|
+
* Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).
|
|
3165
|
+
*
|
|
3166
|
+
* @example
|
|
3167
|
+
* ```ts
|
|
3168
|
+
* resolveMimeTypes(['jpg', 'png', 'application/pdf'])
|
|
3169
|
+
* // → ['image/jpeg', 'image/png', 'application/pdf']
|
|
3170
|
+
* ```
|
|
3171
|
+
*/
|
|
3172
|
+
declare function resolveMimeTypes(types: string[]): string[];
|
|
3173
|
+
/**
|
|
3174
|
+
* Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter
|
|
3175
|
+
* from `allowedTypes` (a predicate, or a list of extensions / MIME types /
|
|
3176
|
+
* wildcards). Returned by both the multer middleware (Express) and the
|
|
3177
|
+
* Fastify / h3 / web multipart paths so the accept/reject rule stays
|
|
3178
|
+
* identical across engines. No `allowedTypes` → accept everything.
|
|
3179
|
+
*/
|
|
3180
|
+
declare function buildFileTypeFilter(allowedTypes: BaseUploadOptions['allowedTypes'], customMimeMap?: Record<string, string>): (mimetype: string, filename: string) => boolean;
|
|
3181
|
+
/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */
|
|
3182
|
+
interface UploadedFileLike {
|
|
3183
|
+
fieldname: string;
|
|
3184
|
+
originalname: string;
|
|
3185
|
+
encoding: string;
|
|
3186
|
+
mimetype: string;
|
|
3187
|
+
size: number;
|
|
3188
|
+
buffer: Buffer;
|
|
3189
|
+
}
|
|
3190
|
+
/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */
|
|
3191
|
+
interface RawUploadPart {
|
|
3192
|
+
fieldname: string;
|
|
3193
|
+
filename: string;
|
|
3194
|
+
mimetype: string;
|
|
3195
|
+
buffer: Buffer;
|
|
3196
|
+
}
|
|
3197
|
+
/**
|
|
3198
|
+
* Apply a `@FileUpload` config to already-buffered multipart parts and return
|
|
3199
|
+
* the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type
|
|
3200
|
+
* filter, per-file size limit, and (array mode) max count — throwing
|
|
3201
|
+
* `HttpException` on a violation, mirroring the Express/multer error path.
|
|
3202
|
+
* Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.
|
|
3203
|
+
*/
|
|
3204
|
+
declare function applyUploadConfig(parts: RawUploadPart[], config: FileUploadConfig): {
|
|
3205
|
+
file?: UploadedFileLike;
|
|
3206
|
+
files?: UploadedFileLike[];
|
|
3207
|
+
};
|
|
3208
|
+
//#endregion
|
|
3209
|
+
//#region src/http/middleware/upload.d.ts
|
|
3210
|
+
/**
|
|
3211
|
+
* Upload options for the middleware.
|
|
3212
|
+
* Extends BaseUploadOptions from core (shared with @FileUpload decorator)
|
|
3213
|
+
* and adds Multer-specific storage options.
|
|
3214
|
+
*/
|
|
3215
|
+
interface UploadOptions extends BaseUploadOptions {
|
|
3216
|
+
/** Multer storage config (default: memory storage) */
|
|
3217
|
+
storage?: Options['storage'];
|
|
3218
|
+
/** Multer dest for disk storage shorthand */
|
|
3219
|
+
dest?: string;
|
|
3220
|
+
}
|
|
3221
|
+
declare function single(fieldName: string, options?: UploadOptions): RequestHandler;
|
|
3222
|
+
/**
|
|
3223
|
+
* Multiple file upload middleware. Attaches files to `req.files`.
|
|
3224
|
+
*/
|
|
3225
|
+
declare function array(fieldName: string, maxCount?: number, options?: UploadOptions): RequestHandler;
|
|
3226
|
+
/**
|
|
3227
|
+
* No file upload — just parse multipart form data without file fields.
|
|
3228
|
+
*/
|
|
3229
|
+
declare function none(options?: UploadOptions): RequestHandler;
|
|
3230
|
+
/**
|
|
3231
|
+
* Removes temporary files from disk after the response is sent.
|
|
3232
|
+
* Attach this as Express middleware after the upload middleware.
|
|
3233
|
+
* Works with both `req.file` (single) and `req.files` (array).
|
|
3234
|
+
*
|
|
3235
|
+
* @example
|
|
3236
|
+
* ```ts
|
|
3237
|
+
* @Post('/process')
|
|
3238
|
+
* @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())
|
|
3239
|
+
* async processDocument(ctx: RequestContext) {
|
|
3240
|
+
* ctx.json({ ok: true })
|
|
3241
|
+
* }
|
|
3242
|
+
* ```
|
|
3243
|
+
*/
|
|
3244
|
+
declare function cleanupFiles(): (req: Request$1, res: Response$1, next: NextFunction) => void;
|
|
3245
|
+
/**
|
|
3246
|
+
* Build upload middleware from a @FileUpload decorator config.
|
|
3247
|
+
* Used internally by the router builder when it detects FILE_UPLOAD metadata.
|
|
3248
|
+
* Accepts the same FileUploadConfig interface used by the @FileUpload decorator.
|
|
3249
|
+
*/
|
|
3250
|
+
declare function buildUploadMiddleware(config: FileUploadConfig): RequestHandler;
|
|
3251
|
+
/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */
|
|
3252
|
+
declare const upload: {
|
|
3253
|
+
single: typeof single;
|
|
3254
|
+
array: typeof array;
|
|
3255
|
+
none: typeof none;
|
|
3256
|
+
};
|
|
3257
|
+
//#endregion
|
|
3258
|
+
//#region src/http/middleware/trace-context.d.ts
|
|
3259
|
+
/**
|
|
3260
|
+
* W3C Trace Context header name.
|
|
3261
|
+
* @see https://www.w3.org/TR/trace-context/#traceparent-header
|
|
3262
|
+
*/
|
|
3263
|
+
declare const TRACEPARENT_HEADER = "traceparent";
|
|
3264
|
+
interface TraceContextOptions {
|
|
3265
|
+
/**
|
|
3266
|
+
* When true, respond with a `traceresponse` header containing the trace ID.
|
|
3267
|
+
* Useful for debugging. Default: false.
|
|
3268
|
+
*/
|
|
3269
|
+
propagateResponse?: boolean;
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* Parsed W3C trace context fields.
|
|
3273
|
+
*/
|
|
3274
|
+
interface TraceContext {
|
|
3275
|
+
/** W3C traceparent version (usually '00') */
|
|
3276
|
+
version: string;
|
|
3277
|
+
/** 32-hex-char distributed trace ID */
|
|
3278
|
+
traceId: string;
|
|
3279
|
+
/** 16-hex-char parent span ID */
|
|
3280
|
+
parentSpanId: string;
|
|
3281
|
+
/** 2-hex-char trace flags */
|
|
3282
|
+
flags: string;
|
|
3283
|
+
}
|
|
3284
|
+
/**
|
|
3285
|
+
* Parse a W3C traceparent header value.
|
|
3286
|
+
* Returns null if the format is invalid.
|
|
3287
|
+
*/
|
|
3288
|
+
declare function parseTraceparent(header: string): TraceContext | null;
|
|
3289
|
+
/**
|
|
3290
|
+
* Middleware that extracts W3C `traceparent` header and stores trace context
|
|
3291
|
+
* in the request's AsyncLocalStorage store.
|
|
3292
|
+
*
|
|
3293
|
+
* If no valid `traceparent` header is present, a new traceId is generated
|
|
3294
|
+
* so that every request always has a trace ID available for correlation.
|
|
3295
|
+
*
|
|
3296
|
+
* Must be mounted **after** `requestScopeMiddleware()` (which creates the store).
|
|
3297
|
+
*
|
|
3298
|
+
* @example
|
|
3299
|
+
* ```ts
|
|
3300
|
+
* bootstrap({
|
|
3301
|
+
* middlewares: [
|
|
3302
|
+
* requestScopeMiddleware(),
|
|
3303
|
+
* traceContext(), // extracts or generates traceId
|
|
3304
|
+
* requestLogger(),
|
|
3305
|
+
* express.json(),
|
|
3306
|
+
* ],
|
|
3307
|
+
* })
|
|
3308
|
+
* ```
|
|
3309
|
+
*/
|
|
3310
|
+
declare function traceContext(options?: TraceContextOptions): (req: Request$1, res: Response$1, next: NextFunction) => void;
|
|
3311
|
+
//#endregion
|
|
3312
|
+
//#region src/http/middleware/views.d.ts
|
|
3313
|
+
interface ViewAdapterOptions {
|
|
3314
|
+
/**
|
|
3315
|
+
* Template engine — pass the engine module or a render function.
|
|
3316
|
+
* Supported engines: ejs, pug, handlebars, nunjucks, or any
|
|
3317
|
+
* Express-compatible engine with a __express property.
|
|
3318
|
+
*
|
|
3319
|
+
* @example
|
|
3320
|
+
* ```ts
|
|
3321
|
+
* import ejs from 'ejs'
|
|
3322
|
+
* ViewAdapter({ engine: ejs, ext: 'ejs' })
|
|
3323
|
+
*
|
|
3324
|
+
* import pug from 'pug'
|
|
3325
|
+
* ViewAdapter({ engine: pug, ext: 'pug' })
|
|
3326
|
+
* ```
|
|
3327
|
+
*/
|
|
3328
|
+
engine: any;
|
|
3329
|
+
/** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */
|
|
3330
|
+
ext: string;
|
|
3331
|
+
/** Directory containing template files (default: 'src/views') */
|
|
3332
|
+
viewsDir?: string;
|
|
3333
|
+
/** Default layout template (optional — depends on engine) */
|
|
3334
|
+
layout?: string;
|
|
3335
|
+
}
|
|
3336
|
+
/**
|
|
3337
|
+
* View/template adapter — pluggable template engine support for KickJS.
|
|
3338
|
+
*
|
|
3339
|
+
* Registers an Express view engine and sets the views directory.
|
|
3340
|
+
* Use `ctx.render()` in controllers to render templates.
|
|
3341
|
+
*
|
|
3342
|
+
* Migrated to the `defineAdapter()` factory in v4 — call without `new`.
|
|
3343
|
+
* The pre-v4 `new ViewAdapter({...})` form is gone; see
|
|
3344
|
+
* `docs/guide/migration-v3-to-v4.md` for the rename.
|
|
3345
|
+
*
|
|
3346
|
+
* @example
|
|
3347
|
+
* ```ts
|
|
3348
|
+
* import ejs from 'ejs'
|
|
3349
|
+
* import { ViewAdapter } from '@forinda/kickjs'
|
|
3350
|
+
*
|
|
3351
|
+
* bootstrap({
|
|
3352
|
+
* modules,
|
|
3353
|
+
* adapters: [
|
|
3354
|
+
* ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),
|
|
3355
|
+
* ],
|
|
3356
|
+
* })
|
|
3357
|
+
*
|
|
3358
|
+
* // In a controller:
|
|
3359
|
+
* @Get('/dashboard')
|
|
3360
|
+
* async dashboard(ctx: RequestContext) {
|
|
3361
|
+
* ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })
|
|
3362
|
+
* }
|
|
3363
|
+
* ```
|
|
3364
|
+
*/
|
|
3365
|
+
declare const ViewAdapter: AdapterFactory<ViewAdapterOptions, unknown>;
|
|
3366
|
+
//#endregion
|
|
3367
|
+
//#region src/http/middleware/spa.d.ts
|
|
3368
|
+
interface SpaAdapterOptions {
|
|
3369
|
+
/**
|
|
3370
|
+
* Directory containing the built SPA files (index.html, assets, etc.)
|
|
3371
|
+
* Default: 'dist/client'
|
|
3372
|
+
*
|
|
3373
|
+
* @example
|
|
3374
|
+
* ```ts
|
|
3375
|
+
* // Vue: 'dist'
|
|
3376
|
+
* // React (Vite): 'dist'
|
|
3377
|
+
* // React (CRA): 'build'
|
|
3378
|
+
* // Svelte: 'build'
|
|
3379
|
+
* // Angular: 'dist/my-app/browser'
|
|
3380
|
+
* ```
|
|
3381
|
+
*/
|
|
3382
|
+
clientDir?: string;
|
|
3383
|
+
/**
|
|
3384
|
+
* URL prefix for API routes. SPA fallback only applies to
|
|
3385
|
+
* non-API routes (routes NOT starting with this prefix).
|
|
3386
|
+
* Default: '/api'
|
|
3387
|
+
*
|
|
3388
|
+
* Matching is segment-aware: `/api` excludes `/api` and `/api/users`, but
|
|
3389
|
+
* NOT `/apidocs` — a plain `startsWith` swallowed any path that merely
|
|
3390
|
+
* began with the same letters.
|
|
3391
|
+
*
|
|
3392
|
+
* Set to an array for multiple prefixes:
|
|
3393
|
+
* ```ts
|
|
3394
|
+
* apiPrefix: ['/api', '/graphql', '/_debug']
|
|
3395
|
+
* ```
|
|
3396
|
+
*/
|
|
3397
|
+
apiPrefix?: string | string[];
|
|
3398
|
+
/**
|
|
3399
|
+
* Additional paths to exclude from SPA fallback.
|
|
3400
|
+
* These paths will NOT serve index.html. Segment-aware, like `apiPrefix`.
|
|
3401
|
+
*
|
|
3402
|
+
* @example
|
|
3403
|
+
* ```ts
|
|
3404
|
+
* exclude: ['/health', '/metrics', '/ws']
|
|
3405
|
+
* ```
|
|
3406
|
+
*/
|
|
3407
|
+
exclude?: string[];
|
|
3408
|
+
/**
|
|
3409
|
+
* Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')
|
|
3410
|
+
* Set to false to disable caching headers.
|
|
3411
|
+
*/
|
|
3412
|
+
cacheControl?: string | false;
|
|
3413
|
+
/**
|
|
3414
|
+
* Cache-Control for index.html (default: 'no-cache')
|
|
3415
|
+
* index.html should not be cached to ensure clients get fresh builds.
|
|
3416
|
+
*/
|
|
3417
|
+
indexCacheControl?: string;
|
|
3418
|
+
/**
|
|
3419
|
+
* Serve index.html even when the client did not ask for HTML.
|
|
3420
|
+
* Default: false.
|
|
3421
|
+
*
|
|
3422
|
+
* By default the fallback only fires for requests whose `Accept` header
|
|
3423
|
+
* includes `text/html` — the rule `connect-history-api-fallback` uses. That
|
|
3424
|
+
* keeps a missing `/assets/app.js` a 404 instead of handing back an HTML
|
|
3425
|
+
* document that the browser then fails to parse as JavaScript, which is a
|
|
3426
|
+
* confusing way to discover a broken build.
|
|
3427
|
+
*
|
|
3428
|
+
* Turn this on if you have non-browser clients that deep-link into SPA
|
|
3429
|
+
* routes without an `Accept` header.
|
|
3430
|
+
*/
|
|
3431
|
+
alwaysFallback?: boolean;
|
|
3432
|
+
}
|
|
3433
|
+
/**
|
|
3434
|
+
* Where to look for the built SPA.
|
|
3435
|
+
*
|
|
3436
|
+
* `process.cwd()` is the framework's convention (assets and env files resolve
|
|
3437
|
+
* the same way) and stays the primary base. But a relative `clientDir` then
|
|
3438
|
+
* only works when the process happens to be started from the app directory —
|
|
3439
|
+
* `node server/dist/index.js` run from a monorepo root resolved `../web/dist`
|
|
3440
|
+
* against the root and found nothing, serving no SPA with only a warning.
|
|
3441
|
+
*
|
|
3442
|
+
* So: try cwd first, and only if that misses, retry against the package root
|
|
3443
|
+
* of the entry script. Both are checked for existence before being chosen, so
|
|
3444
|
+
* this can never silently pick a directory that is not there — a genuinely
|
|
3445
|
+
* missing build still lands on the cwd path, which is what the warning names.
|
|
3446
|
+
*
|
|
3447
|
+
* Deliberately not entry-relative FIRST: under `kick dev` the entry is the CLI
|
|
3448
|
+
* binary, whose package root is the CLI itself.
|
|
3449
|
+
*
|
|
3450
|
+
* Exported for tests only — not re-exported from the package index.
|
|
3451
|
+
*/
|
|
3452
|
+
declare function resolveClientDir(clientDir: string, cwd?: string, entry?: string | undefined): string;
|
|
3453
|
+
/**
|
|
3454
|
+
* SPA adapter — serve a Vue, React, Svelte, or Angular build alongside
|
|
3455
|
+
* your KickJS API. API routes are handled by controllers; everything else
|
|
3456
|
+
* falls back to index.html for client-side routing.
|
|
3457
|
+
*
|
|
3458
|
+
* Written against the engine-agnostic `http` surface (`serveStatic` / `use`),
|
|
3459
|
+
* so it runs under Express, Fastify, and h3 alike. The previous version
|
|
3460
|
+
* reached for `express.static`, `req.path`, and `res.send`, all of which are
|
|
3461
|
+
* Express-only — it silently served nothing on the other runtimes.
|
|
3462
|
+
*
|
|
3463
|
+
* Migrated to the `defineAdapter()` factory — call without `new`, as
|
|
3464
|
+
* `ViewAdapter` has since v4.
|
|
3465
|
+
*
|
|
3466
|
+
* @example
|
|
3467
|
+
* ```ts
|
|
3468
|
+
* import { SpaAdapter } from '@forinda/kickjs/spa'
|
|
3469
|
+
*
|
|
3470
|
+
* bootstrap({
|
|
3471
|
+
* modules,
|
|
3472
|
+
* adapters: [
|
|
3473
|
+
* SpaAdapter({
|
|
3474
|
+
* clientDir: 'dist/client', // or 'build', 'dist', etc.
|
|
3475
|
+
* apiPrefix: '/api',
|
|
3476
|
+
* }),
|
|
3477
|
+
* ],
|
|
3478
|
+
* })
|
|
3479
|
+
* ```
|
|
3480
|
+
*
|
|
3481
|
+
* File structure:
|
|
3482
|
+
* ```
|
|
3483
|
+
* dist/
|
|
3484
|
+
* client/ ← SPA build output
|
|
3485
|
+
* index.html
|
|
3486
|
+
* assets/
|
|
3487
|
+
* app.js
|
|
3488
|
+
* style.css
|
|
3489
|
+
* server/ ← KickJS server
|
|
3490
|
+
* ```
|
|
3491
|
+
*/
|
|
3492
|
+
declare const SpaAdapter: AdapterFactory<SpaAdapterOptions, unknown>;
|
|
3493
|
+
//#endregion
|
|
3494
|
+
//#region src/http/url-for.d.ts
|
|
3495
|
+
/**
|
|
3496
|
+
* Build a route's URL from its name — `'UsersController.show'` — instead of
|
|
3497
|
+
* spelling the path where you link to it, so a moved route can't leave a
|
|
3498
|
+
* redirect, a `Location` header or an email link pointing at the old one.
|
|
3499
|
+
*
|
|
3500
|
+
* @module @forinda/kickjs/http/url-for
|
|
3501
|
+
*/
|
|
3502
|
+
/**
|
|
3503
|
+
* Route names `kick typegen` knows: `'Controller.method'` → the route's
|
|
3504
|
+
* shape. Falls back to `string` before typegen has run.
|
|
3505
|
+
*/
|
|
3506
|
+
type RouteName = [keyof KickRoutes.Named] extends [never] ? string : Extract<keyof KickRoutes.Named, string>;
|
|
3507
|
+
type ParamsOf<N> = N extends keyof KickRoutes.Named ? KickRoutes.Named[N] extends {
|
|
3508
|
+
params: infer P;
|
|
3509
|
+
} ? P : Record<string, string | number> : Record<string, string | number>;
|
|
3510
|
+
/** `params` is optional when the route has none, required otherwise. */
|
|
3511
|
+
type UrlForArgs<N> = Record<string, never> extends ParamsOf<N> ? [params?: ParamsOf<N>, query?: UrlQuery] : [params: ParamsOf<N>, query?: UrlQuery];
|
|
3512
|
+
type UrlQuery = Record<string, string | number | boolean | Array<string | number>>;
|
|
3513
|
+
/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */
|
|
3514
|
+
interface UrlBuilder {
|
|
3515
|
+
/**
|
|
3516
|
+
* The URL of a route, by name — `'Controller.method'` — with its `:params`
|
|
3517
|
+
* filled (encoded) and an optional query string.
|
|
3518
|
+
*/
|
|
3519
|
+
urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
|
|
3520
|
+
}
|
|
3521
|
+
/**
|
|
3522
|
+
* The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,
|
|
3523
|
+
* a service building a link:
|
|
3524
|
+
*
|
|
3525
|
+
* ```ts
|
|
3526
|
+
* @Service()
|
|
3527
|
+
* class Mailer {
|
|
3528
|
+
* constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}
|
|
3529
|
+
* resetLink(token: string) {
|
|
3530
|
+
* return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`
|
|
3531
|
+
* }
|
|
3532
|
+
* }
|
|
3533
|
+
* ```
|
|
3534
|
+
*/
|
|
3535
|
+
declare const ROUTE_URLS: InjectionToken<UrlBuilder>;
|
|
3536
|
+
/** One app's route name → full path pattern (`/api/v1/users/:id`). */
|
|
3537
|
+
declare class RouteUrls implements UrlBuilder {
|
|
3538
|
+
private readonly paths;
|
|
3539
|
+
/** First registration wins — a controller mounted twice keeps its first path. */
|
|
3540
|
+
add(name: string, path: string): void;
|
|
3541
|
+
urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
|
|
3542
|
+
build(name: string, params?: Record<string, unknown>, query?: UrlQuery): string;
|
|
3543
|
+
}
|
|
3544
|
+
declare global {
|
|
3545
|
+
namespace KickRoutes {
|
|
3546
|
+
/** `'Controller.method'` → route shape, written by `kick typegen`. */
|
|
3547
|
+
interface Named {}
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
//#endregion
|
|
3551
|
+
//#region src/http/context.d.ts
|
|
3552
|
+
/**
|
|
3553
|
+
* Input shape for the typed problem-detail convenience methods on
|
|
3554
|
+
* {@link ProblemSender} (`ctx.problem.notFound`, `.badRequest`, etc.) —
|
|
3555
|
+
* RFC 9457 details minus the `status`, which each method pre-fills.
|
|
3556
|
+
*/
|
|
3557
|
+
type ProblemInput = Omit<ProblemDetails, 'status'>;
|
|
3558
|
+
/**
|
|
3559
|
+
* Callable response helper for RFC 9457 — Problem Details responses.
|
|
3560
|
+
* Returned by `ctx.problem`. Invoke directly for a fully-specified
|
|
3561
|
+
* payload, or use the named convenience methods to pre-fill `status` +
|
|
3562
|
+
* `title` for the common codes.
|
|
3563
|
+
*
|
|
3564
|
+
* Each call sets `Content-Type: application/problem+json` and serializes
|
|
3565
|
+
* the canonical shape (defaulting `type` to `about:blank` and `title` to
|
|
3566
|
+
* the IANA reason phrase per RFC 9457 §3.1.1 / §3.1.4).
|
|
3567
|
+
*
|
|
3568
|
+
* @example
|
|
3569
|
+
* ```ts
|
|
3570
|
+
* ctx.problem({
|
|
3571
|
+
* type: 'https://api.example.com/problems/out-of-credit',
|
|
3572
|
+
* status: 403,
|
|
3573
|
+
* detail: 'Your balance is 30, but that costs 50.',
|
|
3574
|
+
* balance: 30, // extension per §3.2
|
|
3575
|
+
* })
|
|
3576
|
+
*
|
|
3577
|
+
* ctx.problem.notFound({ detail: 'User abc not found' })
|
|
3578
|
+
* ctx.problem.validation(zodResult.error.issues)
|
|
3579
|
+
* ```
|
|
3580
|
+
*/
|
|
3581
|
+
interface ProblemSender {
|
|
3582
|
+
(input: ProblemDetails): RuntimeResponse;
|
|
3583
|
+
/** 400 Bad Request — RFC 9457. */
|
|
3584
|
+
badRequest(input?: ProblemInput): RuntimeResponse;
|
|
3585
|
+
/** 401 Unauthorized — RFC 9457. */
|
|
3586
|
+
unauthorized(input?: ProblemInput): RuntimeResponse;
|
|
3587
|
+
/** 403 Forbidden — RFC 9457. */
|
|
3588
|
+
forbidden(input?: ProblemInput): RuntimeResponse;
|
|
3589
|
+
/** 404 Not Found — RFC 9457. */
|
|
3590
|
+
notFound(input?: ProblemInput): RuntimeResponse;
|
|
3591
|
+
/** 409 Conflict — RFC 9457. */
|
|
3592
|
+
conflict(input?: ProblemInput): RuntimeResponse;
|
|
3593
|
+
/** 422 Unprocessable Entity — RFC 9457. */
|
|
3594
|
+
unprocessable(input?: ProblemInput): RuntimeResponse;
|
|
3595
|
+
/** 429 Too Many Requests — RFC 9457. */
|
|
3596
|
+
tooManyRequests(input?: ProblemInput): RuntimeResponse;
|
|
3597
|
+
/** 500 Internal Server Error — RFC 9457. */
|
|
3598
|
+
internal(input?: ProblemInput): RuntimeResponse;
|
|
3599
|
+
/**
|
|
3600
|
+
* 422 with Zod issues serialized into the `errors` extension per
|
|
3601
|
+
* RFC 9457 §3.2's array convention. Pass `error.issues` from a Zod
|
|
3602
|
+
* `safeParse` failure or `error.issues` from a thrown ZodError.
|
|
3603
|
+
*/
|
|
3604
|
+
validation(issues: any[], input?: ProblemInput): RuntimeResponse;
|
|
3605
|
+
}
|
|
3606
|
+
/**
|
|
3607
|
+
* Recursively marks every property of `T` as `readonly`. Preserves
|
|
3608
|
+
* `Function`, `Date`, and `RegExp` unchanged, and converts `Map` / `Set`
|
|
3609
|
+
* to `ReadonlyMap` / `ReadonlySet` so their mutating methods (`set`,
|
|
3610
|
+
* `delete`, `add`, `clear`) are removed from the public surface.
|
|
3611
|
+
* Tuples keep their positional element types — only their per-element
|
|
3612
|
+
* mutability is locked.
|
|
3613
|
+
*
|
|
3614
|
+
* Exposed as a utility for adopters who want to opt into compile-time
|
|
3615
|
+
* sealing of their own shapes. **No longer applied to
|
|
3616
|
+
* `RequestContext.{body,params,query,headers,file,files}`** — that
|
|
3617
|
+
* broke TS narrowing / discriminated-union drilldowns on typed request
|
|
3618
|
+
* payloads. Runtime read-only enforcement now lives in
|
|
3619
|
+
* {@link makeReadOnlyProxy} (dev-only Proxy that warns on writes,
|
|
3620
|
+
* no-op in production).
|
|
3621
|
+
*
|
|
3622
|
+
* Type-only. No runtime cost. `DeepReadonly<any>` is `any` (TS
|
|
3623
|
+
* distributes conditional types over `any`).
|
|
3624
|
+
*/
|
|
3625
|
+
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;
|
|
3626
|
+
/**
|
|
3627
|
+
* The shape of a single route entry in `KickRoutes`. Generated by
|
|
3628
|
+
* `kick typegen` and consumed via the `Ctx<T>` helper. Each field is
|
|
3629
|
+
* `unknown` by default and is filled in as the typegen learns more
|
|
3630
|
+
* about the route (URL params from the path, body/query from validation
|
|
3631
|
+
* schemas, etc.).
|
|
3632
|
+
*/
|
|
3633
|
+
interface RouteShape {
|
|
3634
|
+
params?: unknown;
|
|
3635
|
+
body?: unknown;
|
|
3636
|
+
query?: unknown;
|
|
3637
|
+
response?: unknown;
|
|
3638
|
+
/**
|
|
3639
|
+
* Union of context keys `kick typegen` proved are populated for this
|
|
3640
|
+
* route — the keys of every context contributor applied at method or
|
|
3641
|
+
* class level. Drives {@link RequestContext.require} narrowing, so
|
|
3642
|
+
* calling `ctx.require()` for a key this route doesn't carry is a
|
|
3643
|
+
* compile error instead of a request-time throw.
|
|
3644
|
+
*
|
|
3645
|
+
* `string` (the default) means "not proven", not "no keys". Typegen
|
|
3646
|
+
* emits `string` whenever it cannot see the full picture — a
|
|
3647
|
+
* contributor registered at module / adapter / bootstrap level, or an
|
|
3648
|
+
* unrecognised decorator that might bundle contributors of its own.
|
|
3649
|
+
* Narrowing an unprovable route would produce compile errors for keys
|
|
3650
|
+
* that really are present.
|
|
3651
|
+
*/
|
|
3652
|
+
contextKeys?: string;
|
|
3653
|
+
}
|
|
3654
|
+
/**
|
|
3655
|
+
* Unified request/response abstraction passed to every controller method.
|
|
3656
|
+
* Shields handlers from raw Express objects and provides convenience methods.
|
|
3657
|
+
*
|
|
3658
|
+
* Implements {@link ExecutionContext} so the transport-agnostic Context
|
|
3659
|
+
* Contributor pipeline (#107) can run against this concrete HTTP context
|
|
3660
|
+
* the same way it will run against future WS / queue / cron contexts.
|
|
3661
|
+
*/
|
|
3662
|
+
declare class RequestContext<TBody = any, TParams = any, TQuery = any,
|
|
3663
|
+
/**
|
|
3664
|
+
* Context keys proven present for this route. Defaults to
|
|
3665
|
+
* {@link ContextMetaKey} — every key the project has registered — which
|
|
3666
|
+
* collapses to `string` when neither registry has been augmented, so a
|
|
3667
|
+
* handler typed as plain `RequestContext` keeps today's behaviour. That
|
|
3668
|
+
* default is also the deliberate escape hatch when typegen's view of a
|
|
3669
|
+
* route is incomplete.
|
|
3670
|
+
*/
|
|
3671
|
+
TKeys extends ContextMetaKey = ContextMetaKey> implements ExecutionContext<TKeys> {
|
|
3672
|
+
readonly req: ActiveRuntime['request'];
|
|
3673
|
+
readonly res: ActiveRuntime['response'];
|
|
3674
|
+
readonly next: NextFunction;
|
|
3675
|
+
/**
|
|
3676
|
+
* Engine-agnostic response driver the response helpers write through. Under
|
|
3677
|
+
* the Express runtime it IS `res` (Express's Response satisfies
|
|
3678
|
+
* {@link RuntimeResponse} structurally); other runtimes pass a thin wrapper
|
|
3679
|
+
* over their native reply as the optional fourth argument.
|
|
3680
|
+
*/
|
|
3681
|
+
private readonly _response;
|
|
3682
|
+
/**
|
|
3683
|
+
* The route this request matched: its method, path, controller, handler name
|
|
3684
|
+
* and resolved {@link MatchedRoute.flags}.
|
|
3685
|
+
*
|
|
3686
|
+
* Available to anything running inside the matched route — route middleware,
|
|
3687
|
+
* contributors, guards, the handler. Global middleware runs before route
|
|
3688
|
+
* matching, so it sees `undefined` there.
|
|
3689
|
+
*
|
|
3690
|
+
* ```ts
|
|
3691
|
+
* if (ctx.route?.flags.has('auth.public')) return next()
|
|
3692
|
+
* ```
|
|
3693
|
+
*/
|
|
3694
|
+
get route(): MatchedRoute | undefined;
|
|
3695
|
+
constructor(req: ActiveRuntime['request'], res: ActiveRuntime['response'], next: NextFunction, responseDriver?: RuntimeResponse);
|
|
3696
|
+
/**
|
|
3697
|
+
* Memo of the most recent {@link qs} call this request. The query
|
|
3698
|
+
* object is immutable for a request's lifetime, so a repeat call with
|
|
3699
|
+
* the same `(fieldConfig, options)` references returns the cached
|
|
3700
|
+
* parse instead of re-walking the filter/sort strings.
|
|
3701
|
+
*/
|
|
3702
|
+
private _qsMemo?;
|
|
3703
|
+
/** Memoized {@link problem} sender — built lazily on first access. */
|
|
3704
|
+
private _problem?;
|
|
3705
|
+
/**
|
|
3706
|
+
* Read-side accessor for the per-request metadata map.
|
|
3707
|
+
*
|
|
3708
|
+
* Returns the AsyncLocalStorage map (`requestStore.getStore().values`)
|
|
3709
|
+
* shared with the Context Contributor pipeline when an ALS frame is
|
|
3710
|
+
* active. Returns `null` outside any frame — read-side callers
|
|
3711
|
+
* (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as
|
|
3712
|
+
* "no metadata" and fall through to their `req.*` defaults. Reads
|
|
3713
|
+
* never throw because outside an ALS frame nobody could have written
|
|
3714
|
+
* via `ctx.set` anyway, so an empty answer is the truthful one.
|
|
3715
|
+
*/
|
|
3716
|
+
private metadataReadOnly;
|
|
3717
|
+
/**
|
|
3718
|
+
* Write-side accessor for the per-request metadata map.
|
|
3719
|
+
*
|
|
3720
|
+
* Returns the same map as {@link metadataReadOnly} when an ALS frame
|
|
3721
|
+
* is active. Throws otherwise — writing to a fallback map outside
|
|
3722
|
+
* the ALS frame would silently lose data because other call sites
|
|
3723
|
+
* (downstream contributors, request-logger, etc.) read from the
|
|
3724
|
+
* canonical store and would never see it. Mount
|
|
3725
|
+
* `requestScopeMiddleware()` (Application does this for you in
|
|
3726
|
+
* `'auto'` mode) or wrap your test setup in
|
|
3727
|
+
* `requestStore.run({...}, () => …)` to fix.
|
|
3728
|
+
*/
|
|
3729
|
+
private metadataForWrite;
|
|
3730
|
+
/**
|
|
3731
|
+
* Parsed request body. Wrapped in a dev-only Proxy that warns when
|
|
3732
|
+
* adopters try to mutate Zod-validated payloads in place — compute
|
|
3733
|
+
* new values and stash them via `ctx.set('key', value)` or a Context
|
|
3734
|
+
* Contributor instead. Reach for `ctx.req.body` if you genuinely
|
|
3735
|
+
* need the raw, mutable Express handle (rare).
|
|
3736
|
+
*
|
|
3737
|
+
* In production the Proxy is bypassed and `this.req.body` is
|
|
3738
|
+
* returned as-is — no runtime cost on the hot path.
|
|
3739
|
+
*/
|
|
3740
|
+
get body(): TBody;
|
|
3741
|
+
/** Path parameters parsed from the route — read-only, see {@link body}. */
|
|
3742
|
+
get params(): TParams;
|
|
3743
|
+
/** Parsed query string — read-only, see {@link body}. */
|
|
3744
|
+
get query(): TQuery;
|
|
3745
|
+
/** Inbound HTTP headers — read-only, see {@link body}. */
|
|
3746
|
+
get headers(): Request$1['headers'];
|
|
3747
|
+
get requestId(): string | undefined;
|
|
3748
|
+
/**
|
|
3749
|
+
* `AbortSignal` that fires when the underlying HTTP request is
|
|
3750
|
+
* closed — either because the client disconnected before the
|
|
3751
|
+
* response was sent, or because Node's socket-close event ran
|
|
3752
|
+
* after a normal response. Multiple `RequestContext` wrappers for
|
|
3753
|
+
* the same request (router-builder constructs one per
|
|
3754
|
+
* middleware/contributor pipeline / main handler) share a single
|
|
3755
|
+
* `AbortController` cached on the underlying `req` object, so the
|
|
3756
|
+
* signal is stable across the request lifecycle.
|
|
3757
|
+
*
|
|
3758
|
+
* Thread it through anything that takes an `AbortSignal` so the
|
|
3759
|
+
* work cancels as soon as the client gives up — e.g. a kickjs-db
|
|
3760
|
+
* relational query:
|
|
3761
|
+
*
|
|
3762
|
+
* ```ts
|
|
3763
|
+
* @Get('/:id/full')
|
|
3764
|
+
* async show(ctx: RequestContext) {
|
|
3765
|
+
* const row = await this.repo.findFullById(ctx.params.id, ctx.signal)
|
|
3766
|
+
* if (!row) return ctx.notFound()
|
|
3767
|
+
* ctx.json(row)
|
|
3768
|
+
* }
|
|
3769
|
+
* ```
|
|
3770
|
+
*
|
|
3771
|
+
* The repo passes `signal` to `db.query.<table>.findUnique({ signal })`;
|
|
3772
|
+
* if the client disconnects mid-flight, the in-flight query rejects
|
|
3773
|
+
* with `RelationalQueryCancelledError` instead of consuming the
|
|
3774
|
+
* connection until completion.
|
|
3775
|
+
*
|
|
3776
|
+
* Implementation note — both `req.on('close')` and `res.on('close')`
|
|
3777
|
+
* are wired so the signal aborts regardless of whether the close
|
|
3778
|
+
* event lands on the request stream or the response stream first.
|
|
3779
|
+
* Subsequent fires are no-ops (`AbortController.abort()` is
|
|
3780
|
+
* idempotent).
|
|
3781
|
+
*/
|
|
3782
|
+
get signal(): AbortSignal;
|
|
3783
|
+
/**
|
|
3784
|
+
* The request's session — set by the `session()` middleware, which must be
|
|
3785
|
+
* installed. Type your keys once by augmenting `SessionData`:
|
|
3786
|
+
*
|
|
3787
|
+
* ```ts
|
|
3788
|
+
* declare module '@forinda/kickjs' {
|
|
3789
|
+
* interface SessionData { userId?: string }
|
|
3790
|
+
* }
|
|
3791
|
+
* ```
|
|
3792
|
+
*/
|
|
3793
|
+
get session(): Session;
|
|
3794
|
+
/**
|
|
3795
|
+
* The authenticated user set by AuthAdapter.
|
|
3796
|
+
* Reads from the per-request metadata store first (`ctx.set('user', ...)`),
|
|
3797
|
+
* then falls back to `req.user` (set directly by AuthAdapter middleware).
|
|
3798
|
+
*
|
|
3799
|
+
* Extend the `AuthUser` interface via module augmentation in your own auth
|
|
3800
|
+
* module — see the BYO Auth recipe in the docs
|
|
3801
|
+
* to get full typing.
|
|
3802
|
+
*
|
|
3803
|
+
* @example
|
|
3804
|
+
* ```ts
|
|
3805
|
+
* @Get('/me')
|
|
3806
|
+
* @Authenticated()
|
|
3807
|
+
* getProfile(ctx: RequestContext) {
|
|
3808
|
+
* const user = ctx.user
|
|
3809
|
+
* if (!user) return ctx.notFound()
|
|
3810
|
+
* return ctx.json({ user })
|
|
3811
|
+
* }
|
|
3812
|
+
* ```
|
|
3813
|
+
*/
|
|
3814
|
+
get user(): MetaValue<'user', Record<string, any>> | undefined;
|
|
3815
|
+
/**
|
|
3816
|
+
* Tenant identifier for multi-tenant apps. Reads `user.tenantId` —
|
|
3817
|
+
* populated either by `AuthAdapter.testMode({ tenantId })`, a tenant
|
|
3818
|
+
* resolver middleware, or manually on the strategy's `mapPayload`.
|
|
3819
|
+
*
|
|
3820
|
+
* Augment `AuthUser` (or `ContextMeta['user']`) to widen the return
|
|
3821
|
+
* type if your user shape guarantees a non-`string | undefined` id.
|
|
3822
|
+
*/
|
|
3823
|
+
get tenantId(): string | undefined;
|
|
3824
|
+
/**
|
|
3825
|
+
* Effective role list for the current user. Prefers `user.tenantRoles`
|
|
3826
|
+
* (populated by `AuthAdapterOptions.roleResolver` under a tenant) and
|
|
3827
|
+
* falls back to `user.roles`. Returns an empty array when the user is
|
|
3828
|
+
* absent or the shape has neither field.
|
|
3829
|
+
*/
|
|
3830
|
+
get roles(): string[];
|
|
3831
|
+
/**
|
|
3832
|
+
* Parse the request query string into structured filters, sort, pagination, and search.
|
|
3833
|
+
* Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
|
|
3834
|
+
*
|
|
3835
|
+
* Generic over the field config: when passed an inline literal (or
|
|
3836
|
+
* `as const`), `filters[].field` and `sort[].field` are narrowed to
|
|
3837
|
+
* the exact whitelisted field names. Pass nothing or a non-literal
|
|
3838
|
+
* config and you get the loose `string` fallback.
|
|
3839
|
+
*
|
|
3840
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
|
|
3841
|
+
* @param options - Limits (`maxLimit`, `defaultLimit`, `maxSearchLength`) and an
|
|
3842
|
+
* `onReject` hook. By default a rejected/over-broad field is logged via
|
|
3843
|
+
* `console.warn` with the request id; pass an explicit `onReject` to override
|
|
3844
|
+
* (e.g. throw to return a 400), or `onReject: () => {}` to silence.
|
|
3845
|
+
*
|
|
3846
|
+
* @example
|
|
3847
|
+
* ```ts
|
|
3848
|
+
* @Get('/')
|
|
3849
|
+
* async list(ctx: RequestContext) {
|
|
3850
|
+
* const parsed = ctx.qs({
|
|
3851
|
+
* filterable: ['status', 'priority'],
|
|
3852
|
+
* sortable: ['createdAt', 'title'],
|
|
3853
|
+
* } as const)
|
|
3854
|
+
* parsed.filters[0].field // typed as 'status' | 'priority'
|
|
3855
|
+
* parsed.sort[0].field // typed as 'createdAt' | 'title'
|
|
3856
|
+
* }
|
|
3857
|
+
* ```
|
|
3858
|
+
*/
|
|
3859
|
+
qs<TConfig extends QueryFieldConfig | undefined = undefined>(fieldConfig?: TConfig, options?: ParseQueryOptions): TypedParsedQuery<TConfig>;
|
|
3860
|
+
/**
|
|
3861
|
+
* Single uploaded file (requires `@FileUpload({ mode: 'single' })`).
|
|
3862
|
+
* Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.
|
|
3863
|
+
* File metadata is set by the upload middleware and shouldn't be
|
|
3864
|
+
* mutated downstream.
|
|
3865
|
+
*/
|
|
3866
|
+
get file(): Express.Multer.File | undefined;
|
|
3867
|
+
/**
|
|
3868
|
+
* Array of uploaded files (requires `@FileUpload({ mode: 'array' })`).
|
|
3869
|
+
* The array (and each entry in dev) is wrapped in a read-only Proxy
|
|
3870
|
+
* that warns on `push`/`pop` and per-file mutation. Use
|
|
3871
|
+
* `ctx.req.files` if you genuinely need the mutable Express handle.
|
|
3872
|
+
*/
|
|
3873
|
+
get files(): Express.Multer.File[] | undefined;
|
|
3874
|
+
/**
|
|
3875
|
+
* Read a value from the per-request metadata store.
|
|
3876
|
+
*
|
|
3877
|
+
* The key is constrained to {@link ContextMetaKey} — the keys registered in
|
|
3878
|
+
* `ContextMeta` / `ContextKeys` — so a typo is a compile error rather than a
|
|
3879
|
+
* permanent `undefined`. Projects that have augmented neither registry get
|
|
3880
|
+
* `string`, exactly as before.
|
|
3881
|
+
*
|
|
3882
|
+
* Constrained by `ContextMetaKey` and deliberately NOT by `TKeys`: "does this
|
|
3883
|
+
* key exist in the app" is a different question from "does this route carry
|
|
3884
|
+
* it", and narrowing by the latter would turn an incomplete typegen view into
|
|
3885
|
+
* false errors for keys written by middleware. Presence is `require`'s job;
|
|
3886
|
+
* this always returns `| undefined`.
|
|
3887
|
+
*
|
|
3888
|
+
* When `ContextMeta` has a matching key the return type is inferred
|
|
3889
|
+
* automatically. For ad-hoc keys, pass a generic: `ctx.get<MyType>('custom')`.
|
|
3890
|
+
*/
|
|
3891
|
+
get<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined;
|
|
3892
|
+
/**
|
|
3893
|
+
* Read a value that a contributor is expected to have produced, and
|
|
3894
|
+
* throw {@link MissingContextValueError} when it hasn't.
|
|
3895
|
+
*
|
|
3896
|
+
* Use this instead of `ctx.get(key)!` anywhere the value is a
|
|
3897
|
+
* precondition rather than an optional extra — permissions, tenants,
|
|
3898
|
+
* the resolved subject of the route. The non-null assertion compiles
|
|
3899
|
+
* whether or not the producing contributor is actually applied to the
|
|
3900
|
+
* route, so a dropped `@LoadTenant` turns into `undefined` flowing
|
|
3901
|
+
* silently into an auth check. `require()` fails loudly at that point
|
|
3902
|
+
* instead, naming the key.
|
|
3903
|
+
*
|
|
3904
|
+
* ```ts
|
|
3905
|
+
* // before — compiles even if @OperatorPerm was never applied
|
|
3906
|
+
* const perm = ctx.get('operatorPerm')!
|
|
3907
|
+
*
|
|
3908
|
+
* // after — throws MissingContextValueError naming the key + route
|
|
3909
|
+
* const perm = ctx.require('operatorPerm')
|
|
3910
|
+
* ```
|
|
3911
|
+
*
|
|
3912
|
+
* When `TKeys` is narrowed — which it is for a handler typed as
|
|
3913
|
+
* `Ctx<KickRoutes…>`, from typegen's per-route `contextKeys` — asking
|
|
3914
|
+
* for a key the route doesn't carry is a compile error, so a dropped
|
|
3915
|
+
* decorator fails the build. `TKeys` stays `string` (no narrowing) for
|
|
3916
|
+
* a plain `RequestContext` and for any route typegen couldn't prove
|
|
3917
|
+
* complete; there this is a runtime guarantee only.
|
|
3918
|
+
* See `architecture.md` §20.14.
|
|
3919
|
+
*
|
|
3920
|
+
* `null` counts as present; only `undefined` (or a missing entry)
|
|
3921
|
+
* throws. A contributor that deliberately resolves to `null` is
|
|
3922
|
+
* expressing "looked, found nothing", which is a real value — which
|
|
3923
|
+
* is why the return type is `Exclude<…, undefined>` and NOT
|
|
3924
|
+
* `NonNullable<…>`. The latter would strip `null` from the type while
|
|
3925
|
+
* the runtime still hands it back, so a caller would be told a value
|
|
3926
|
+
* is non-null and then get `null`.
|
|
3927
|
+
*/
|
|
3928
|
+
require<K extends TKeys>(key: K): Exclude<MetaValue<K>, undefined>;
|
|
3929
|
+
/**
|
|
3930
|
+
* Best-effort `"GET /path"` label for error messages. Runtime-agnostic:
|
|
3931
|
+
* express/fastify requests and web-standard `Request` all expose
|
|
3932
|
+
* `method` + `url`, but none of them are guaranteed here, so every
|
|
3933
|
+
* access is defensive and the whole thing is optional.
|
|
3934
|
+
*/
|
|
3935
|
+
private routeLabel;
|
|
3936
|
+
/**
|
|
3937
|
+
* Write a value to the per-request metadata store. Throws when no
|
|
3938
|
+
* AsyncLocalStorage frame is active — see {@link metadataForWrite}
|
|
3939
|
+
* for why a silent fallback is the wrong default.
|
|
3940
|
+
*/
|
|
3941
|
+
set<K extends ContextMetaKey>(key: K, value: MetaValue<K>): void;
|
|
3942
|
+
/**
|
|
3943
|
+
* Set a response header. Runtime-neutral — works on every engine and on
|
|
3944
|
+
* the web/edge entry. No-op guards are the runtime's job (headers set
|
|
3945
|
+
* after the response settles are ignored or throw per engine).
|
|
3946
|
+
*/
|
|
3947
|
+
setHeader(name: string, value: string | number | readonly string[]): this;
|
|
3948
|
+
json(data: any, status?: number): RuntimeResponse;
|
|
3949
|
+
created(data: any): RuntimeResponse;
|
|
3950
|
+
private sendJson;
|
|
3951
|
+
noContent(): unknown;
|
|
3952
|
+
/**
|
|
3953
|
+
* The URL of a route, by name — `'Controller.method'` — with its `:params`
|
|
3954
|
+
* filled (encoded) and an optional query string. Names and params are typed
|
|
3955
|
+
* once `kick typegen` has run; an unknown name or a missing param throws.
|
|
3956
|
+
*
|
|
3957
|
+
* ```ts
|
|
3958
|
+
* @Post('/')
|
|
3959
|
+
* async create(ctx: RequestContext) {
|
|
3960
|
+
* const user = await this.users.create(ctx.body)
|
|
3961
|
+
* ctx.setHeader('Location', ctx.urlFor('UsersController.show', { id: user.id }))
|
|
3962
|
+
* ctx.created(user)
|
|
3963
|
+
* }
|
|
3964
|
+
* ```
|
|
3965
|
+
*/
|
|
3966
|
+
urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
|
|
3967
|
+
/**
|
|
3968
|
+
* Answer a conditional request from the resource's validators, before doing
|
|
3969
|
+
* the expensive part. Sets `ETag` / `Last-Modified`, then — per RFC 9110 —
|
|
3970
|
+
* answers `304 Not Modified` when the client's copy is current, or `412`
|
|
3971
|
+
* when an `If-Match` / `If-Unmodified-Since` write is based on a stale one.
|
|
3972
|
+
* Returns `true` when it answered; respond as usual when it returns `false`.
|
|
3973
|
+
*
|
|
3974
|
+
* ```ts
|
|
3975
|
+
* @Get('/:id')
|
|
3976
|
+
* async show(ctx: RequestContext) {
|
|
3977
|
+
* const { version, updatedAt } = await posts.meta(ctx.params.id) // cheap
|
|
3978
|
+
* if (ctx.conditional({ etag: `v${version}`, lastModified: updatedAt })) return
|
|
3979
|
+
* ctx.json(await posts.full(ctx.params.id)) // only when it changed
|
|
3980
|
+
* }
|
|
3981
|
+
* ```
|
|
3982
|
+
*/
|
|
3983
|
+
conditional(validators: Validators): boolean;
|
|
3984
|
+
/**
|
|
3985
|
+
* @deprecated Prefer {@link ProblemSender.notFound | ctx.problem.notFound()},
|
|
3986
|
+
* which emits an RFC 9457 — Problem Details response. This helper stays
|
|
3987
|
+
* for backward compatibility and will not be removed.
|
|
3988
|
+
*/
|
|
3989
|
+
notFound(message?: string): RuntimeResponse;
|
|
3990
|
+
/**
|
|
3991
|
+
* @deprecated Prefer {@link ProblemSender.badRequest | ctx.problem.badRequest()},
|
|
3992
|
+
* which emits an RFC 9457 — Problem Details response. This helper stays
|
|
3993
|
+
* for backward compatibility and will not be removed.
|
|
3994
|
+
*/
|
|
3995
|
+
badRequest(message: string): RuntimeResponse;
|
|
3996
|
+
/**
|
|
3997
|
+
* RFC 9457 — Problem Details for HTTP APIs response helper.
|
|
3998
|
+
* https://datatracker.ietf.org/doc/html/rfc9457
|
|
3999
|
+
*
|
|
4000
|
+
* `ctx.problem(...)` sends a canonical problem-detail response with
|
|
4001
|
+
* `Content-Type: application/problem+json`. The convenience methods
|
|
4002
|
+
* (`ctx.problem.notFound`, `.badRequest`, etc.) pre-fill `status` +
|
|
4003
|
+
* `title` for the common codes.
|
|
4004
|
+
*
|
|
4005
|
+
* `type` defaults to `about:blank` (§3.1.1); `title` defaults to the
|
|
4006
|
+
* IANA reason phrase for `status` (§3.1.4). Extension members per §3.2
|
|
4007
|
+
* pass through unchanged.
|
|
4008
|
+
*
|
|
4009
|
+
* @example
|
|
4010
|
+
* ```ts
|
|
4011
|
+
* ctx.problem({
|
|
4012
|
+
* type: 'https://api.example.com/problems/out-of-credit',
|
|
4013
|
+
* status: 403,
|
|
4014
|
+
* detail: 'Your balance is 30, but that costs 50.',
|
|
4015
|
+
* instance: `/account/${ctx.user.id}/messages/${ctx.params.id}`,
|
|
4016
|
+
* balance: 30,
|
|
4017
|
+
* })
|
|
4018
|
+
*
|
|
4019
|
+
* ctx.problem.notFound({ detail: 'User abc not found' })
|
|
4020
|
+
* ctx.problem.validation(zodResult.error.issues)
|
|
4021
|
+
* ```
|
|
4022
|
+
*
|
|
4023
|
+
* @see {@link ProblemException} for the exception-throwing equivalent
|
|
4024
|
+
* (use it from services where `ctx` isn't in scope).
|
|
4025
|
+
*/
|
|
4026
|
+
get problem(): ProblemSender;
|
|
4027
|
+
private sendProblem;
|
|
4028
|
+
/**
|
|
4029
|
+
* Send an HTML response.
|
|
4030
|
+
*
|
|
4031
|
+
* Passes the full MIME type rather than the `'html'` shorthand. The
|
|
4032
|
+
* shorthand is an Express affordance — `res.type()` runs it through a MIME
|
|
4033
|
+
* lookup — but the Fastify and h3 drivers forward the string to their own
|
|
4034
|
+
* `type()` / `setHeader()` verbatim, so `'html'` reached the wire as a
|
|
4035
|
+
* malformed `Content-Type: html` on those engines. Fastify 5.10 started
|
|
4036
|
+
* normalising that invalid value to `text/plain`, which is what surfaced it.
|
|
4037
|
+
*
|
|
4038
|
+
* Express produces `text/html; charset=utf-8` for `.type('html')`, so
|
|
4039
|
+
* spelling it out here is byte-identical there and correct everywhere else.
|
|
4040
|
+
*/
|
|
4041
|
+
/**
|
|
4042
|
+
* The client's IP address, or `undefined` when it cannot be determined.
|
|
4043
|
+
*
|
|
4044
|
+
* Prefers the value the runtime computed (Express derives `req.ip` from the
|
|
4045
|
+
* app's `trust proxy` setting; Fastify from `trustProxy`), because raw
|
|
4046
|
+
* forwarded headers are client-SPOOFABLE on deployments that do not
|
|
4047
|
+
* normalize them. The header fallbacks exist for runtimes with no `ip`
|
|
4048
|
+
* field at all — notably the web/edge entry.
|
|
4049
|
+
*
|
|
4050
|
+
* `ctx.req.ip` is Express-only, so reaching for it directly broke on
|
|
4051
|
+
* Fastify and h3.
|
|
4052
|
+
*/
|
|
4053
|
+
get ip(): string | undefined;
|
|
4054
|
+
/**
|
|
4055
|
+
* Redirect the client. Works on every runtime.
|
|
4056
|
+
*
|
|
4057
|
+
* Every engine spells this differently — Express and Fastify have
|
|
4058
|
+
* `res.redirect()`, h3 has `sendRedirect(event, location, code)` — and none
|
|
4059
|
+
* of them is shared, so this writes the status and `Location` header through
|
|
4060
|
+
* the runtime response surface, which all four expose.
|
|
4061
|
+
*
|
|
4062
|
+
* The response carries no body. Express sends a short text line and h3 an
|
|
4063
|
+
* HTML meta-refresh fallback; a bare `Location` with a 3xx is sufficient per
|
|
4064
|
+
* RFC 9110, and interpolating the URL into an HTML body would add an
|
|
4065
|
+
* injection surface to a value this method already warns is dangerous.
|
|
4066
|
+
*
|
|
4067
|
+
* ::: warning
|
|
4068
|
+
* Never pass an unvalidated user-supplied `url`. An attacker-controlled
|
|
4069
|
+
* destination turns this into an open redirect, which is a common phishing
|
|
4070
|
+
* primitive. Allow-list the target or keep it relative.
|
|
4071
|
+
* :::
|
|
4072
|
+
*/
|
|
4073
|
+
redirect(url: string, status?: number): unknown;
|
|
4074
|
+
html(content: string, status?: number): RuntimeResponse;
|
|
4075
|
+
/**
|
|
4076
|
+
* Send a body with its content type — XML, plain text, CSV, an image.
|
|
4077
|
+
* Runtime-neutral, like `json()` and `html()`. `type` defaults to
|
|
4078
|
+
* `text/plain; charset=utf-8`.
|
|
4079
|
+
*
|
|
4080
|
+
* @example
|
|
4081
|
+
* ```ts
|
|
4082
|
+
* ctx.send(sitemapXml, { type: 'application/xml' })
|
|
4083
|
+
* ctx.send(csv, { type: 'text/csv; charset=utf-8', status: 200 })
|
|
4084
|
+
* ```
|
|
4085
|
+
*/
|
|
4086
|
+
send(body: string | Uint8Array, options?: {
|
|
4087
|
+
type?: string;
|
|
4088
|
+
status?: number;
|
|
4089
|
+
}): RuntimeResponse;
|
|
4090
|
+
/**
|
|
4091
|
+
* Send `buffer` as a file download named `filename`. The name is written
|
|
4092
|
+
* per RFC 6266 — an ASCII fallback plus `filename*` in UTF-8 — so a name
|
|
4093
|
+
* from an upload (quotes, line breaks, non-Latin text) can't break the header.
|
|
4094
|
+
*/
|
|
4095
|
+
download(buffer: Buffer, filename: string, contentType?: string): RuntimeResponse;
|
|
4096
|
+
/**
|
|
4097
|
+
* Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
|
|
4098
|
+
* Requires a ViewAdapter to be configured in bootstrap().
|
|
4099
|
+
*
|
|
4100
|
+
* @param template - Template name (without extension, relative to viewsDir)
|
|
4101
|
+
* @param data - Data to pass to the template
|
|
4102
|
+
*
|
|
4103
|
+
* @example
|
|
4104
|
+
* ```ts
|
|
4105
|
+
* ctx.render('dashboard', { user, title: 'Dashboard' })
|
|
4106
|
+
* ctx.render('emails/welcome', { name: 'Alice' })
|
|
4107
|
+
* ```
|
|
4108
|
+
*/
|
|
4109
|
+
render(template: string, data?: Record<string, any>): unknown;
|
|
4110
|
+
/**
|
|
4111
|
+
* Parse query params and return a standardized paginated response.
|
|
4112
|
+
* Calls `ctx.qs()` internally, then wraps your data with pagination meta.
|
|
4113
|
+
*
|
|
4114
|
+
* @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
|
|
4115
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
|
|
4116
|
+
*
|
|
4117
|
+
* @example
|
|
4118
|
+
* ```ts
|
|
4119
|
+
* @Get('/')
|
|
4120
|
+
* async list(ctx: RequestContext) {
|
|
4121
|
+
* return ctx.paginate(
|
|
4122
|
+
* async (parsed) => {
|
|
4123
|
+
* const data = await db.select().from(users)
|
|
4124
|
+
* .where(query.where).limit(parsed.pagination.limit)
|
|
4125
|
+
* .offset(parsed.pagination.offset).all()
|
|
4126
|
+
* const total = await db.select({ count: count() }).from(users).get()
|
|
4127
|
+
* return { data, total: total?.count ?? 0 }
|
|
4128
|
+
* },
|
|
4129
|
+
* { filterable: ['name', 'role'], sortable: ['createdAt'] },
|
|
4130
|
+
* )
|
|
4131
|
+
* }
|
|
4132
|
+
* ```
|
|
4133
|
+
*/
|
|
4134
|
+
paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{
|
|
4135
|
+
data: T[];
|
|
4136
|
+
total: number;
|
|
4137
|
+
}>, fieldConfig?: TConfig): Promise<PaginatedResponse<T>>;
|
|
4138
|
+
/**
|
|
4139
|
+
* Start an SSE (Server-Sent Events) stream.
|
|
4140
|
+
* Sets the correct headers and returns helpers to send events.
|
|
4141
|
+
*
|
|
4142
|
+
* Pass a payload type to get typed sends — and `return sse` from the
|
|
4143
|
+
* handler so `kick typegen` carries the event type into
|
|
4144
|
+
* `KickRoutes.Api`, where `@forinda/kickjs-client`'s `api.stream()`
|
|
4145
|
+
* picks it up (the returned handler is ignored at runtime — the
|
|
4146
|
+
* response is already streaming).
|
|
4147
|
+
*
|
|
4148
|
+
* @example
|
|
4149
|
+
* ```ts
|
|
4150
|
+
* interface Tick { time: string }
|
|
4151
|
+
*
|
|
4152
|
+
* @Get('/events')
|
|
4153
|
+
* async stream(ctx: RequestContext) {
|
|
4154
|
+
* const sse = ctx.sse<Tick>()
|
|
4155
|
+
*
|
|
4156
|
+
* const interval = setInterval(() => {
|
|
4157
|
+
* sse.send({ time: new Date().toISOString() }, 'tick')
|
|
4158
|
+
* }, 1000)
|
|
4159
|
+
*
|
|
4160
|
+
* sse.onClose(() => clearInterval(interval))
|
|
4161
|
+
* return sse // typed as SseHandler<Tick> → response inference
|
|
4162
|
+
* }
|
|
4163
|
+
* ```
|
|
4164
|
+
*/
|
|
4165
|
+
/**
|
|
4166
|
+
* Send a web-standard `Response` — status, headers (every `Set-Cookie`
|
|
4167
|
+
* kept) and body, streamed chunk by chunk — on any runtime. For handing off
|
|
4168
|
+
* to libraries that speak `Request`/`Response`, such as the MCP SDK's
|
|
4169
|
+
* web-standard transport.
|
|
4170
|
+
*
|
|
4171
|
+
* Resolves once the body is fully written. Stops reading the body when the
|
|
4172
|
+
* client disconnects.
|
|
4173
|
+
*
|
|
4174
|
+
* @example
|
|
4175
|
+
* ```ts
|
|
4176
|
+
* @Post('/mcp')
|
|
4177
|
+
* async mcp(ctx: RequestContext) {
|
|
4178
|
+
* await ctx.sendResponse(await transport.handleRequest(webRequest))
|
|
4179
|
+
* }
|
|
4180
|
+
* ```
|
|
4181
|
+
*/
|
|
4182
|
+
sendResponse(response: Response): Promise<void>;
|
|
4183
|
+
/**
|
|
4184
|
+
* Keep `promise` running after the response is sent — an audit log, an
|
|
4185
|
+
* email, an analytics call. The Node server's `shutdown()` waits for it;
|
|
4186
|
+
* `createHandler()` and the web entry hand it to the platform's
|
|
4187
|
+
* `waitUntil` when you pass the platform context in. A rejection is
|
|
4188
|
+
* logged, never unhandled. Same as the standalone `waitUntil()` export.
|
|
4189
|
+
*/
|
|
4190
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
4191
|
+
sse<T = unknown>(): SseHandler<T>;
|
|
4192
|
+
}
|
|
4193
|
+
/**
|
|
4194
|
+
* The handle {@link RequestContext.sse} returns. The optional phantom
|
|
4195
|
+
* `__sse` property carries the event payload type STRUCTURALLY — never set
|
|
4196
|
+
* at runtime — so `kick typegen`'s response inference (handler `return sse`)
|
|
4197
|
+
* flows it into `KickRoutes.Api`, and `@forinda/kickjs-client` detects SSE
|
|
4198
|
+
* routes without importing any server types.
|
|
4199
|
+
*/
|
|
4200
|
+
interface SseHandler<T = unknown> {
|
|
4201
|
+
/** Phantom event-payload type marker — never assigned at runtime. */
|
|
4202
|
+
readonly __sse?: T;
|
|
4203
|
+
/** Send an SSE event with optional event name and id. */
|
|
4204
|
+
send(data: T, event?: string, id?: string): void;
|
|
4205
|
+
/** Send a comment line (keeps the connection alive through proxies). */
|
|
4206
|
+
comment(text: string): void;
|
|
4207
|
+
/** Register a callback for client disconnect. */
|
|
4208
|
+
onClose(fn: () => void): void;
|
|
4209
|
+
/** End the SSE stream. */
|
|
4210
|
+
close(): void;
|
|
4211
|
+
}
|
|
4212
|
+
/**
|
|
4213
|
+
* Short alias for `RequestContext` parameterised by a route shape.
|
|
4214
|
+
*
|
|
4215
|
+
* Use with `kick typegen`'s generated `KickRoutes` namespace for
|
|
4216
|
+
* fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata
|
|
4217
|
+
* typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from
|
|
4218
|
+
* `ContextMeta` augmentation and works on all `RequestContext` instances.
|
|
4219
|
+
*
|
|
4220
|
+
* @example
|
|
4221
|
+
* ```ts
|
|
4222
|
+
* @Get('/:id')
|
|
4223
|
+
* getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {
|
|
4224
|
+
* ctx.params.id // typed from RouteShape
|
|
4225
|
+
* ctx.body // typed from RouteShape
|
|
4226
|
+
* ctx.user // typed from ContextMeta
|
|
4227
|
+
* ctx.get('tenant') // typed from ContextMeta
|
|
4228
|
+
* }
|
|
4229
|
+
* ```
|
|
4230
|
+
*/
|
|
4231
|
+
type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<TRoute extends {
|
|
4232
|
+
body: infer B;
|
|
4233
|
+
} ? B : any, TRoute extends {
|
|
4234
|
+
params: infer P;
|
|
4235
|
+
} ? P : any, TRoute extends {
|
|
4236
|
+
query: infer Q;
|
|
4237
|
+
} ? Q : any, TRoute extends {
|
|
4238
|
+
contextKeys: infer K;
|
|
4239
|
+
} ? K extends ContextMetaKey ? K : ContextMetaKey : ContextMetaKey>;
|
|
4240
|
+
/**
|
|
4241
|
+
* Global ambient registry of typed routes, populated by `kick typegen`.
|
|
4242
|
+
*
|
|
4243
|
+
* Interfaces inside `KickRoutes` correspond to controller classes (each
|
|
4244
|
+
* property one route method, conforming to `RouteShape`) — plus the
|
|
4245
|
+
* reserved `KickRoutes.Api`: a flat `'METHOD /mounted/path'` map over the
|
|
4246
|
+
* same shapes, consumed by `@forinda/kickjs-client`. Don't name a
|
|
4247
|
+
* controller class `Api` — it would declaration-merge into that map.
|
|
4248
|
+
*
|
|
4249
|
+
* Empty by default — declarations come from `.kickjs/types/kick__routes.ts`
|
|
4250
|
+
* generated alongside the rest of the typegen output.
|
|
4251
|
+
*/
|
|
4252
|
+
declare global {
|
|
4253
|
+
namespace KickRoutes {}
|
|
4254
|
+
}
|
|
4255
|
+
/** `attachment; filename="…"; filename*=UTF-8''…` for any file name (RFC 6266 / RFC 8187). */
|
|
4256
|
+
declare function contentDisposition(filename: string): string;
|
|
4257
|
+
//#endregion
|
|
4258
|
+
//#region src/http/runtime.d.ts
|
|
4259
|
+
/** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */
|
|
4260
|
+
type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
4261
|
+
/**
|
|
4262
|
+
* A context-based handler: the runtime-neutral unit of the request pipeline.
|
|
4263
|
+
* Contributors, route middleware (via {@link MiddlewareHandler}), and the
|
|
4264
|
+
* terminal controller call all reduce to this shape. The runtime owns how a
|
|
4265
|
+
* `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,
|
|
4266
|
+
* next)`; Fastify in its own handler).
|
|
4267
|
+
*/
|
|
4268
|
+
type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>;
|
|
4269
|
+
/**
|
|
4270
|
+
* Connect-style middleware — the portable middleware format. Built-in
|
|
4271
|
+
* middleware and adopter-supplied Express middleware are this shape. The
|
|
4272
|
+
* Express runtime hands them straight to `app.use`; later runtimes bridge
|
|
4273
|
+
* them (Fastify via `@fastify/middie`, h3 via its node adapter).
|
|
4274
|
+
*
|
|
4275
|
+
* Typed as the Express handler union for M1 (Express is the only runtime);
|
|
4276
|
+
* a future milestone narrows this to bare node `(req, res, next)` primitives
|
|
4277
|
+
* once the driver layer lands.
|
|
4278
|
+
*/
|
|
4279
|
+
type ConnectMiddleware = RequestHandler | ErrorRequestHandler;
|
|
4280
|
+
/**
|
|
4281
|
+
* One materialized route, as plain data. Produced by {@link buildRouteTable}
|
|
4282
|
+
* from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.
|
|
4283
|
+
*
|
|
4284
|
+
* The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`
|
|
4285
|
+
* keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),
|
|
4286
|
+
* `contributorRunner` is a closure over the pre-built pipeline + container (the
|
|
4287
|
+
* pipeline is built — and any cycle / missing-dep error thrown — at table-build
|
|
4288
|
+
* time, i.e. boot), and `validation` / `upload` stay as metadata the runtime
|
|
4289
|
+
* materializes its own way. Faithfully reproducing the legacy Express chain —
|
|
4290
|
+
* not collapsing it — is what keeps M1 behavior-neutral.
|
|
4291
|
+
*/
|
|
4292
|
+
interface RouteEntry {
|
|
4293
|
+
method: RouteMethod;
|
|
4294
|
+
/** Path with `:param` segments — the portable subset all engines accept. */
|
|
4295
|
+
path: string;
|
|
4296
|
+
/** Class + method middleware, in execution order; each receives `(ctx, next)`. */
|
|
4297
|
+
middlewares: MiddlewareHandler[];
|
|
4298
|
+
/**
|
|
4299
|
+
* Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),
|
|
4300
|
+
* or `null` when no contributors apply. Closes over the built pipeline and
|
|
4301
|
+
* the DI container so it stays engine-neutral; the runtime advances the
|
|
4302
|
+
* chain (Express: call `next()`) once it resolves.
|
|
4303
|
+
*/
|
|
4304
|
+
contributorRunner: CtxHandler | null;
|
|
4305
|
+
/**
|
|
4306
|
+
* Contributors registered with `beforeValidation: true`. Runtimes run this
|
|
4307
|
+
* right after publishing the matched route — before validation, upload and
|
|
4308
|
+
* middleware — so a rejection (401) lands before a malformed body's 422.
|
|
4309
|
+
* Absent or `null` when no contributor asks for it.
|
|
4310
|
+
*/
|
|
4311
|
+
earlyContributorRunner?: CtxHandler | null;
|
|
4312
|
+
/** The app's `validationError` — what this route's validation failure throws. */
|
|
4313
|
+
validationError?: ValidationErrorFactory;
|
|
4314
|
+
/** The app's route names → paths, for `ctx.urlFor()`. */
|
|
4315
|
+
urls?: RouteUrls;
|
|
4316
|
+
/** Terminal handler: resolves the controller per-request and invokes it. */
|
|
4317
|
+
handler: CtxHandler;
|
|
4318
|
+
/** Introspection + runtime-materialized concerns (swagger/typegen read this). */
|
|
4319
|
+
meta: RouteMeta;
|
|
4320
|
+
}
|
|
4321
|
+
/** Per-route metadata: introspection refs plus runtime-materialized concerns. */
|
|
4322
|
+
/**
|
|
4323
|
+
* One context contributor on a route, as introspection sees it: the
|
|
4324
|
+
* contributors a request runs, in execution order. Built with the route.
|
|
4325
|
+
*/
|
|
4326
|
+
interface RouteContributor {
|
|
4327
|
+
/** The key it sets with `ctx.set(...)`. */
|
|
4328
|
+
key: string;
|
|
4329
|
+
/** Where it was registered — `method` / `class` decorators, or a module, adapter or global list. */
|
|
4330
|
+
source: ContributorSource;
|
|
4331
|
+
/** The registering site, e.g. `UsersController.show#0(tenant)` or a module name. */
|
|
4332
|
+
label?: string;
|
|
4333
|
+
dependsOn: readonly string[];
|
|
4334
|
+
/** Runs before validation (`beforeValidation: true`). */
|
|
4335
|
+
beforeValidation: boolean;
|
|
4336
|
+
/** Lower-precedence registrations of the same key this one replaced. */
|
|
4337
|
+
overrides: ReadonlyArray<{
|
|
4338
|
+
source: ContributorSource;
|
|
4339
|
+
label?: string;
|
|
4340
|
+
}>;
|
|
4341
|
+
}
|
|
4342
|
+
interface RouteMeta {
|
|
4343
|
+
/**
|
|
4344
|
+
* Owning controller class — for DI resolution and adapter introspection.
|
|
4345
|
+
* Absent for ad-hoc routes registered through {@link AdapterHttp.route},
|
|
4346
|
+
* which have no controller class behind them.
|
|
4347
|
+
*/
|
|
4348
|
+
controller?: Constructor;
|
|
4349
|
+
/** Handler method name on the controller, when there is one. */
|
|
4350
|
+
handlerName?: string;
|
|
4351
|
+
/** The route's context contributors, in execution order — for devtools / introspection. */
|
|
4352
|
+
contributors?: readonly RouteContributor[];
|
|
4353
|
+
/** Zod/JSON-schema validation config from the route decorator, if any. */
|
|
4354
|
+
validation?: RouteDefinition['validation'];
|
|
4355
|
+
/** `@FileUpload` config, if present — the runtime supplies the backend. */
|
|
4356
|
+
upload?: FileUploadConfig;
|
|
4357
|
+
/**
|
|
4358
|
+
* Route flags in force here, resolved at build time (method over class).
|
|
4359
|
+
* Enabled flags only: a flag declared `false` at a higher-precedence site is
|
|
4360
|
+
* absent rather than present-and-false, so `has()` is always the right
|
|
4361
|
+
* question. See `core/route-flag.ts`.
|
|
4362
|
+
*/
|
|
4363
|
+
flags?: RouteFlags;
|
|
4364
|
+
/**
|
|
4365
|
+
* The full mounted pattern (`/api/v1/users/:id`) — set by the Application
|
|
4366
|
+
* for controller routes. `path` is relative to the module mount.
|
|
4367
|
+
*/
|
|
4368
|
+
pattern?: string;
|
|
4369
|
+
}
|
|
4370
|
+
interface MatchedRoute {
|
|
4371
|
+
readonly method: RouteMethod;
|
|
4372
|
+
/** Path as declared on the handler, e.g. `/:id`. */
|
|
4373
|
+
readonly path: string;
|
|
4374
|
+
/**
|
|
4375
|
+
* The full route pattern including the mount prefix and version, e.g.
|
|
4376
|
+
* `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls
|
|
4377
|
+
* back to `path` for routes registered without a mount.
|
|
4378
|
+
*/
|
|
4379
|
+
readonly pattern: string;
|
|
4380
|
+
readonly controller?: Constructor;
|
|
4381
|
+
readonly handlerName?: string;
|
|
4382
|
+
/** Enabled flags only — see {@link RouteMeta.flags}. */
|
|
4383
|
+
readonly flags: RouteFlags;
|
|
4384
|
+
/** @internal The app's route names, for `ctx.urlFor()`. */
|
|
4385
|
+
readonly urls?: RouteUrls;
|
|
4386
|
+
}
|
|
4387
|
+
/** A controller's routes grouped under the module mount prefix. */
|
|
4388
|
+
type RouteTable = {
|
|
4389
|
+
mountPath: string;
|
|
4390
|
+
routes: RouteEntry[];
|
|
4391
|
+
}[];
|
|
4392
|
+
interface RuntimeResponse {
|
|
4393
|
+
status(code: number): RuntimeResponse;
|
|
4394
|
+
json(data: unknown): RuntimeResponse;
|
|
4395
|
+
send(data: unknown): RuntimeResponse;
|
|
4396
|
+
type(contentType: string): RuntimeResponse;
|
|
4397
|
+
setHeader(name: string, value: string | number | readonly string[]): unknown;
|
|
4398
|
+
render(view: string, data?: Record<string, unknown>): unknown;
|
|
4399
|
+
writeHead(statusCode: number, headers?: Record<string, string>): unknown;
|
|
4400
|
+
flushHeaders(): unknown;
|
|
4401
|
+
write(chunk: string | Buffer): boolean;
|
|
4402
|
+
end(data?: unknown): unknown;
|
|
4403
|
+
once(event: 'close' | 'drain', listener: () => void): unknown;
|
|
4404
|
+
readonly headersSent: boolean;
|
|
4405
|
+
}
|
|
4406
|
+
/**
|
|
4407
|
+
* Per-runtime type map: the engine-native request / response / app types an
|
|
4408
|
+
* `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.
|
|
4409
|
+
*/
|
|
4410
|
+
interface RuntimeTypeMap {
|
|
4411
|
+
request: unknown;
|
|
4412
|
+
response: unknown;
|
|
4413
|
+
app: unknown;
|
|
4414
|
+
}
|
|
4415
|
+
/** The Express runtime's native types — the default when nothing is augmented. */
|
|
4416
|
+
interface ExpressRuntimeTypes {
|
|
4417
|
+
request: Request$1;
|
|
4418
|
+
response: Response$1;
|
|
4419
|
+
app: Express$1;
|
|
4420
|
+
}
|
|
4421
|
+
/**
|
|
4422
|
+
* Augmentable runtime registry. Empty by default; the `kick/runtime` typegen
|
|
4423
|
+
* plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured
|
|
4424
|
+
* runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,
|
|
4425
|
+
* `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`
|
|
4426
|
+
* — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is
|
|
4427
|
+
* uniform with `kick/db` and env typing.
|
|
4428
|
+
*
|
|
4429
|
+
* @example
|
|
4430
|
+
* ```ts
|
|
4431
|
+
* // .kickjs/types/kick__runtime.d.ts — generated by typegen
|
|
4432
|
+
* declare module '@forinda/kickjs' {
|
|
4433
|
+
* interface KickRuntimeRegister {
|
|
4434
|
+
* runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes
|
|
4435
|
+
* }
|
|
4436
|
+
* }
|
|
4437
|
+
* ```
|
|
4438
|
+
*/
|
|
4439
|
+
interface KickRuntimeRegister {}
|
|
4440
|
+
/** The active runtime's type map — the augmented one, or Express by default. */
|
|
4441
|
+
type ActiveRuntime = KickRuntimeRegister extends {
|
|
4442
|
+
runtime: infer R extends RuntimeTypeMap;
|
|
4443
|
+
} ? R : ExpressRuntimeTypes;
|
|
4444
|
+
/** Options passed to {@link HttpRuntime.createApp}. */
|
|
4445
|
+
interface RuntimeAppOptions {
|
|
4446
|
+
/**
|
|
4447
|
+
* Express `trust proxy` setting (and the equivalent on other engines). The
|
|
4448
|
+
* function form is Express-specific; other runtimes interpret the simpler
|
|
4449
|
+
* shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).
|
|
4450
|
+
*/
|
|
4451
|
+
trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean);
|
|
4452
|
+
/**
|
|
4453
|
+
* When the app is mounted inside another handler (`kick dev`'s Vite server,
|
|
4454
|
+
* `app.handle(req, res, next)` in a host server), hand requests no route
|
|
4455
|
+
* matched back to it — `true`, the default — or answer them here with the
|
|
4456
|
+
* app's not-found handling — `false`. Express always answers.
|
|
4457
|
+
*/
|
|
4458
|
+
notFoundFallthrough?: boolean;
|
|
4459
|
+
/** Largest request body the engine parses, in bytes — `jsonLimit`, resolved. */
|
|
4460
|
+
bodyLimit?: number;
|
|
4461
|
+
}
|
|
4462
|
+
/** Where a connect middleware sits and what it scopes to. */
|
|
4463
|
+
interface UseConnectOptions {
|
|
4464
|
+
path?: string | RegExp | ReadonlyArray<string | RegExp>;
|
|
4465
|
+
}
|
|
4466
|
+
/**
|
|
4467
|
+
* Optional engine capabilities. Absence means the corresponding `ctx` feature
|
|
4468
|
+
* raises a clear error on that runtime rather than failing obscurely.
|
|
4469
|
+
*/
|
|
4470
|
+
interface RuntimeCapabilities {
|
|
4471
|
+
/** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */
|
|
4472
|
+
render: boolean;
|
|
4473
|
+
/** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */
|
|
4474
|
+
uploads: boolean;
|
|
4475
|
+
/** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */
|
|
4476
|
+
connectMiddleware: boolean;
|
|
4477
|
+
/**
|
|
4478
|
+
* The engine parses request bodies itself (Fastify, h3). When true, the
|
|
4479
|
+
* Application skips its default `express.json()` so the body stream isn't
|
|
4480
|
+
* consumed twice (which would deadlock the engine's own parser). Express:
|
|
4481
|
+
* false — it relies on the `express.json()` connect middleware.
|
|
4482
|
+
*/
|
|
4483
|
+
nativeBodyParsing: boolean;
|
|
4484
|
+
/**
|
|
4485
|
+
* The engine's `nodeHandler` works behind `node:http2` (the HTTP/2
|
|
4486
|
+
* compatibility API), so `server: { http2: true }` may use it. Fastify/h3:
|
|
4487
|
+
* true. Express: false — it does not run on that layer. Absent = false, so
|
|
4488
|
+
* custom runtimes opt in explicitly.
|
|
4489
|
+
*/
|
|
4490
|
+
http2?: boolean;
|
|
4491
|
+
}
|
|
4492
|
+
/**
|
|
4493
|
+
* The engine driver. KickJS owns decorators → {@link RouteTable}, the
|
|
4494
|
+
* contributor pipeline, the `RequestContext` surface, and error mapping. The
|
|
4495
|
+
* runtime owns app/server creation, route materialization, connect-middleware
|
|
4496
|
+
* registration, static serving, and the terminal not-found / error handlers.
|
|
4497
|
+
*
|
|
4498
|
+
* `expressRuntime()` is the default and the M1 reference implementation.
|
|
4499
|
+
*/
|
|
4500
|
+
interface HttpRuntime<TApp = unknown> {
|
|
4501
|
+
readonly name: 'express' | 'fastify' | 'h3' | (string & {});
|
|
4502
|
+
/** Create the engine app. Called once per Application (and per HMR rebuild). */
|
|
4503
|
+
createApp(options?: RuntimeAppOptions): TApp;
|
|
4504
|
+
/**
|
|
4505
|
+
* Node-compatible request listener — the transport contract.
|
|
4506
|
+
* `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST
|
|
4507
|
+
* invoke `next` (when given) instead of 404-ing if no route matched — the
|
|
4508
|
+
* Vite dev chain depends on fall-through.
|
|
4509
|
+
*/
|
|
4510
|
+
nodeHandler(app: TApp): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void;
|
|
4511
|
+
/** Materialize the framework-built route table onto the engine. */
|
|
4512
|
+
mountRoutes(app: TApp, table: RouteTable): void;
|
|
4513
|
+
/** Register a connect-style middleware (built-ins + adopter middleware). */
|
|
4514
|
+
useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void;
|
|
4515
|
+
/** Serve a static directory (swagger-ui assets, devtools SPA). */
|
|
4516
|
+
serveStatic(app: TApp, prefix: string, dir: string): void;
|
|
4517
|
+
/** Terminal not-found handler. */
|
|
4518
|
+
setNotFound(app: TApp, mw: ConnectMiddleware): void;
|
|
4519
|
+
/** Terminal error handler. */
|
|
4520
|
+
setErrorHandler(app: TApp, mw: ConnectMiddleware): void;
|
|
4521
|
+
/** Release the engine app on shutdown (Fastify runs its `onClose` hooks). */
|
|
4522
|
+
close?(app: TApp): void | Promise<void>;
|
|
4523
|
+
readonly capabilities: RuntimeCapabilities;
|
|
4524
|
+
}
|
|
4525
|
+
/**
|
|
4526
|
+
* The supported surface adapters use to add HTTP routes, mounts, static dirs,
|
|
4527
|
+
* and middleware — engine-agnostic, in place of reaching for the raw Express
|
|
4528
|
+
* `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the
|
|
4529
|
+
* Application over the active {@link HttpRuntime}, so an adapter written against
|
|
4530
|
+
* this works under any runtime; the raw `app` escape hatch stays available for
|
|
4531
|
+
* the rare engine-specific need.
|
|
4532
|
+
*/
|
|
4533
|
+
interface AdapterHttp {
|
|
4534
|
+
/** Register a single context-handler route (e.g. a docs or transport endpoint). */
|
|
4535
|
+
route(method: RouteMethod, path: string, handler: CtxHandler): void;
|
|
4536
|
+
/** Mount a pre-built route table under a path prefix. */
|
|
4537
|
+
mount(prefix: string, routes: RouteEntry[]): void;
|
|
4538
|
+
/** Serve a static directory under a path prefix. */
|
|
4539
|
+
serveStatic(prefix: string, dir: string): void;
|
|
4540
|
+
/** Register a connect-style middleware (optionally path-scoped). */
|
|
4541
|
+
use(mw: ConnectMiddleware, opts?: UseConnectOptions): void;
|
|
4542
|
+
}
|
|
4543
|
+
//#endregion
|
|
4544
|
+
//#region src/core/adapter.d.ts
|
|
4545
|
+
/**
|
|
4546
|
+
* Where in the middleware pipeline an adapter's middleware should be inserted.
|
|
4547
|
+
*
|
|
4548
|
+
* - `beforeGlobal` — runs **before** any user-defined global middleware.
|
|
4549
|
+
* Suitable for transport-level concerns (request tagging, low-level
|
|
4550
|
+
* request rewriting). Fires on every request.
|
|
4551
|
+
* - `afterGlobal` — runs **after** global middleware, **before** module
|
|
4552
|
+
* routes are matched. Default for most adapter middleware (auth pre-checks,
|
|
4553
|
+
* tenant resolution, body shaping). Fires on every request.
|
|
4554
|
+
* - `beforeRoutes` — runs just before module routes are mounted. Functionally
|
|
4555
|
+
* equivalent to `afterGlobal` for most cases; the explicit phase exists so
|
|
4556
|
+
* adapters that *must* sit at the very end of the pre-route stack can
|
|
4557
|
+
* declare intent. Fires on every request.
|
|
4558
|
+
* - `afterRoutes` — sits **after** module routes but **before** error
|
|
4559
|
+
* handlers. **Fires only on fall-through** — when no route matched (404
|
|
4560
|
+
* path) or a route handler called `next()` without ending the response.
|
|
4561
|
+
* Controllers that respond with `ctx.json(...)` end the chain and skip
|
|
4562
|
+
* this phase, so it is *not* a "post-response" hook. For per-response
|
|
4563
|
+
* work (logging, metrics) use `res.on('finish', ...)` from inside an
|
|
4564
|
+
* earlier-phase middleware instead.
|
|
4565
|
+
*/
|
|
4566
|
+
type MiddlewarePhase = 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes';
|
|
4567
|
+
/**
|
|
4568
|
+
* Path scope for an {@link AdapterMiddleware} entry. Mirrors what
|
|
4569
|
+
* Express's `app.use(path, handler)` accepts so adapters get the full
|
|
4570
|
+
* range without learning a new mini-language:
|
|
4571
|
+
*
|
|
4572
|
+
* - A `string` prefix — `'/api'` matches `/api`, `/api/v1`, `/api/v1/x`.
|
|
4573
|
+
* - A `RegExp` — `/^\/api\/v\d+/` matches `/api/v1`, `/api/v42`.
|
|
4574
|
+
* - An array of either — `['/api', '/admin']` matches either prefix;
|
|
4575
|
+
* `['/api', /^\/internal\//]` mixes shapes.
|
|
4576
|
+
*
|
|
4577
|
+
* Omit to apply the middleware unconditionally (Express `app.use(handler)`).
|
|
4578
|
+
*/
|
|
4579
|
+
type MiddlewarePath = string | RegExp | ReadonlyArray<string | RegExp>;
|
|
4580
|
+
/** A middleware entry contributed by an adapter */
|
|
4581
|
+
interface AdapterMiddleware {
|
|
4582
|
+
/**
|
|
4583
|
+
* Express handler: either a `RequestHandler` (`(req, res, next) => …`)
|
|
4584
|
+
* or an `ErrorRequestHandler` (`(err, req, res, next) => …`).
|
|
4585
|
+
* Express dispatches based on arity, so the same field accepts both
|
|
4586
|
+
* without a discriminant.
|
|
4587
|
+
*/
|
|
4588
|
+
handler: RequestHandler | ErrorRequestHandler;
|
|
4589
|
+
/** Which phase to insert into (default: 'afterGlobal') */
|
|
4590
|
+
phase?: MiddlewarePhase;
|
|
4591
|
+
/**
|
|
4592
|
+
* Optional path scope. See {@link MiddlewarePath} for the accepted
|
|
4593
|
+
* shapes (string prefix, RegExp, or an array mixing both). Omit to
|
|
4594
|
+
* apply the middleware to every request that reaches this phase.
|
|
4595
|
+
*/
|
|
4596
|
+
path?: MiddlewarePath;
|
|
4597
|
+
}
|
|
4598
|
+
/**
|
|
4599
|
+
* Context passed to adapter lifecycle hooks.
|
|
4600
|
+
* Populated by the Application — provides the engine-agnostic HTTP surface,
|
|
4601
|
+
* the engine-native app instance, the DI container, the http.Server, and
|
|
4602
|
+
* environment info without requiring external type imports.
|
|
4603
|
+
*
|
|
4604
|
+
* Prefer `http` over `app`: `http` is the same on every runtime, while `app`
|
|
4605
|
+
* is whatever the active engine's instance happens to be (Express, Fastify,
|
|
4606
|
+
* h3), so an adapter that reaches for it only runs on that engine.
|
|
4607
|
+
*
|
|
4608
|
+
* @example
|
|
4609
|
+
* ```ts
|
|
4610
|
+
* beforeMount({ http, container }: AdapterContext) {
|
|
4611
|
+
* http.use(myConnectMiddleware())
|
|
4612
|
+
* http.route('GET', '/status', (ctx) => ctx.json({ ok: true }))
|
|
4613
|
+
* }
|
|
4614
|
+
* ```
|
|
4615
|
+
*/
|
|
4616
|
+
/** The Node server behind the app — see `ApplicationOptions.server`. */
|
|
4617
|
+
type KickServer = http.Server | https.Server | http2.Http2SecureServer;
|
|
4618
|
+
interface AdapterContext {
|
|
4619
|
+
/**
|
|
4620
|
+
* Engine-agnostic HTTP surface — the supported way to add routes, mounts,
|
|
4621
|
+
* static dirs, and middleware (spec §4.4). Prefer this over {@link app}:
|
|
4622
|
+
* an adapter written against `http` works under any runtime.
|
|
4623
|
+
*/
|
|
4624
|
+
http: AdapterHttp;
|
|
4625
|
+
/**
|
|
4626
|
+
* Engine-native application instance — Express under the default runtime,
|
|
4627
|
+
* typed from the active runtime via {@link ActiveRuntime} (spec §4.3b).
|
|
4628
|
+
* Escape hatch for genuinely engine-specific needs; for everything else use
|
|
4629
|
+
* {@link http}.
|
|
4630
|
+
*/
|
|
4631
|
+
app: ActiveRuntime['app'];
|
|
4632
|
+
/**
|
|
4633
|
+
* Run a web `Request` through this app's pipeline and return the
|
|
4634
|
+
* `Response` — routing, middleware, validation, contributors, errors —
|
|
4635
|
+
* without a listening server (`createHandler()`, tests), so an adapter that
|
|
4636
|
+
* calls the app's own routes (MCP and AI tool dispatch) never needs the
|
|
4637
|
+
* server address. See `Application.fetch`.
|
|
4638
|
+
*
|
|
4639
|
+
* The full pipeline exists once setup completes: from `beforeStart` on,
|
|
4640
|
+
* and in request handlers after that. In `beforeMount` module routes and
|
|
4641
|
+
* error handlers are not mounted yet.
|
|
4642
|
+
*/
|
|
4643
|
+
fetch(request: Request): Promise<Response>;
|
|
4644
|
+
/** DI container */
|
|
4645
|
+
container: Container;
|
|
4646
|
+
/**
|
|
4647
|
+
* The Node server the app listens on — only available in afterStart. An
|
|
4648
|
+
* `http.Server` by default; an `https.Server` or `Http2SecureServer` when
|
|
4649
|
+
* `bootstrap({ server })` sets `tls` / `http2`. All three emit `upgrade`
|
|
4650
|
+
* for HTTP/1.1 clients, which is what WebSocket libraries attach to.
|
|
4651
|
+
*/
|
|
4652
|
+
server?: KickServer;
|
|
4653
|
+
/** Current NODE_ENV value (default: 'development') */
|
|
4654
|
+
env: string;
|
|
4655
|
+
/** true when NODE_ENV === 'production' */
|
|
4656
|
+
isProduction: boolean;
|
|
4657
|
+
}
|
|
4658
|
+
/**
|
|
4659
|
+
* Adapters plug into the Application lifecycle.
|
|
4660
|
+
* Implement this to add WebSocket, database, rate limiting, docs, etc.
|
|
4661
|
+
*
|
|
4662
|
+
* All hooks receive an `AdapterContext` populated by the framework.
|
|
4663
|
+
* No external type imports needed — the context is fully typed from KickJS internals.
|
|
4664
|
+
*
|
|
4665
|
+
* @example
|
|
4666
|
+
* ```ts
|
|
4667
|
+
* import type { AppAdapter, AdapterContext } from '@forinda/kickjs/adapter'
|
|
4668
|
+
*
|
|
4669
|
+
* class SentryAdapter implements AppAdapter {
|
|
4670
|
+
* name = 'SentryAdapter'
|
|
4671
|
+
*
|
|
4672
|
+
* beforeMount({ http, container }: AdapterContext) {
|
|
4673
|
+
* // `http.use` takes any connect-style middleware and mounts it on
|
|
4674
|
+
* // whichever engine is active. Reach for `app` only when the thing you
|
|
4675
|
+
* // are wiring is engine-specific — and accept the engine lock-in.
|
|
4676
|
+
* http.use(Sentry.expressRequestHandler())
|
|
4677
|
+
* }
|
|
4678
|
+
*
|
|
4679
|
+
* afterStart({ server }: AdapterContext) {
|
|
4680
|
+
* // server is the http.Server — available after listen()
|
|
4681
|
+
* }
|
|
4682
|
+
*
|
|
4683
|
+
* async shutdown() {
|
|
4684
|
+
* await Sentry.close(2000)
|
|
4685
|
+
* }
|
|
4686
|
+
* }
|
|
4687
|
+
* ```
|
|
4688
|
+
*/
|
|
4689
|
+
interface AppAdapter {
|
|
4690
|
+
/**
|
|
4691
|
+
* Human-readable name for logging and `dependsOn` resolution.
|
|
4692
|
+
* Required when the adapter (or any other in the same set) declares
|
|
4693
|
+
* `dependsOn` — sort errors will reference adapters by name.
|
|
4694
|
+
*/
|
|
4695
|
+
name?: string;
|
|
4696
|
+
/**
|
|
4697
|
+
* Other adapter names that must mount before this one. The framework
|
|
4698
|
+
* topologically sorts adapters at boot — cycles or unknown names throw
|
|
4699
|
+
* via `MountCycleError` / `MissingMountDepError` so bad configurations
|
|
4700
|
+
* fail boot rather than corrupt live traffic.
|
|
4701
|
+
*
|
|
4702
|
+
* Common pattern: `TenantAdapter` populates `req.tenant` and
|
|
4703
|
+
* `AuthAdapter` reads it for tenant-scoped RBAC, so AuthAdapter
|
|
4704
|
+
* declares `dependsOn = ['TenantAdapter']`. Adapters without
|
|
4705
|
+
* `dependsOn` retain their declaration order.
|
|
4706
|
+
*
|
|
4707
|
+
* @example
|
|
4708
|
+
* ```ts
|
|
4709
|
+
* class AuthAdapter implements AppAdapter {
|
|
4710
|
+
* name = 'AuthAdapter'
|
|
4711
|
+
* dependsOn = ['TenantAdapter']
|
|
4712
|
+
* }
|
|
4713
|
+
* ```
|
|
4714
|
+
*/
|
|
4715
|
+
dependsOn?: readonly KickJsPluginName[];
|
|
4716
|
+
/**
|
|
4717
|
+
* Whether this adapter runs at all, decided once at startup. Return `true`
|
|
4718
|
+
* to keep it, or `false` / a reason to leave it out — the outcome is in
|
|
4719
|
+
* `app.getConditionReport()` and DevTools' `/_debug/conditions`. An adapter
|
|
4720
|
+
* that `dependsOn` one left out is left out too.
|
|
4721
|
+
*
|
|
4722
|
+
* ```ts
|
|
4723
|
+
* const cache: AppAdapter = { name: 'Cache', when: onEnv('REDIS_URL'), … }
|
|
4724
|
+
* defineAdapter({ name: 'Queue', build: () => ({ when: allOf(onEnv('QUEUE'), onPackage('bullmq')), … }) })
|
|
4725
|
+
* ```
|
|
4726
|
+
*/
|
|
4727
|
+
when?: AdapterCondition;
|
|
4728
|
+
/**
|
|
4729
|
+
* Explain one of this adapter's startup failures. When a setup hook throws,
|
|
4730
|
+
* the app asks the adapter first, then its own analyzers (connection
|
|
4731
|
+
* refused, unknown host, bad credentials, …), and logs the advice before
|
|
4732
|
+
* the error itself. Return `undefined` for errors you don't recognise.
|
|
4733
|
+
*
|
|
4734
|
+
* ```ts
|
|
4735
|
+
* analyzeFailure: (err) =>
|
|
4736
|
+
* err instanceof MissingExtensionError
|
|
4737
|
+
* ? { summary: 'pgvector is not installed', fix: 'CREATE EXTENSION vector;' }
|
|
4738
|
+
* : undefined
|
|
4739
|
+
* ```
|
|
4740
|
+
*/
|
|
4741
|
+
analyzeFailure?(err: unknown): FailureAdvice | undefined;
|
|
4742
|
+
/**
|
|
4743
|
+
* Return middleware entries to be inserted into the pipeline.
|
|
4744
|
+
* The `phase` controls ordering relative to global middleware and routes.
|
|
4745
|
+
*/
|
|
4746
|
+
middleware?(): AdapterMiddleware[];
|
|
4747
|
+
/**
|
|
4748
|
+
* Return Context Contributors (#107) that apply to every route in the
|
|
4749
|
+
* application. Adapter-level contributors merge into the per-route
|
|
4750
|
+
* pipeline at the `'adapter'` precedence level — they win over global
|
|
4751
|
+
* contributors but lose to module, class, and method decorators.
|
|
4752
|
+
*
|
|
4753
|
+
* Useful for cross-cutting concerns: an auth adapter contributing
|
|
4754
|
+
* `user`, a multi-tenant adapter contributing `tenant`, etc. Optional.
|
|
4755
|
+
*/
|
|
4756
|
+
contributors?(): ContributorRegistrations;
|
|
4757
|
+
/**
|
|
4758
|
+
* Settings sections this adapter needs — validated at startup and bound
|
|
4759
|
+
* before any hook runs, only when the adapter is enabled (see `when`).
|
|
4760
|
+
*/
|
|
4761
|
+
settings?(): readonly SettingsDeclaration[];
|
|
4762
|
+
/**
|
|
4763
|
+
* Called before global middleware — register early routes (docs UI, health).
|
|
4764
|
+
* May return a Promise — async rejections are caught and logged.
|
|
4765
|
+
*/
|
|
4766
|
+
beforeMount?(ctx: AdapterContext): void | Promise<void>;
|
|
4767
|
+
/**
|
|
4768
|
+
* Called for each module route that gets mounted.
|
|
4769
|
+
* Use this to collect route metadata (e.g. for OpenAPI spec generation).
|
|
4770
|
+
*/
|
|
4771
|
+
onRouteMount?(controllerClass: Constructor, mountPath: string): void;
|
|
4772
|
+
/**
|
|
4773
|
+
* Called after modules are registered and the DI container is bootstrapped,
|
|
4774
|
+
* before the HTTP server starts listening. **This is the correct hook for
|
|
4775
|
+
* adapters that register DI bindings, resolve services, or otherwise prepare
|
|
4776
|
+
* container-side state** (e.g. `container.registerInstance(MAILER, ...)`).
|
|
4777
|
+
*
|
|
4778
|
+
* `beforeStart` runs inside `app.setup()`, which means it also fires under
|
|
4779
|
+
* `createTestApp` — adapters using this hook work in unit tests without
|
|
4780
|
+
* needing a live HTTP server. See {@link afterStart} for the contrast.
|
|
4781
|
+
*
|
|
4782
|
+
* May return a Promise — async rejections are caught and logged.
|
|
4783
|
+
*/
|
|
4784
|
+
beforeStart?(ctx: AdapterContext): void | Promise<void>;
|
|
4785
|
+
/**
|
|
4786
|
+
* Called after the HTTP server is listening — `ctx.server` is the live
|
|
4787
|
+
* `http.Server`. **Use this hook only for work that genuinely needs a
|
|
4788
|
+
* listening server**: attaching Socket.IO / WS upgrades, reading the bound
|
|
4789
|
+
* port via `server.address()`, dispatching to the local server over HTTP,
|
|
4790
|
+
* etc.
|
|
4791
|
+
*
|
|
4792
|
+
* `afterStart` does NOT fire under `createTestApp`, since tests call
|
|
4793
|
+
* `app.setup()` and never `app.start()`. If your adapter only registers DI
|
|
4794
|
+
* bindings or resolves services, use {@link beforeStart} — that hook runs
|
|
4795
|
+
* in both production (`start()`) and tests (`setup()`).
|
|
4796
|
+
*
|
|
4797
|
+
* May return a Promise — async rejections are caught and logged.
|
|
4798
|
+
*/
|
|
4799
|
+
afterStart?(ctx: AdapterContext): void | Promise<void>;
|
|
4800
|
+
/**
|
|
4801
|
+
* Called by the /health/ready endpoint. Return the health status of your adapter's
|
|
4802
|
+
* backing service (database, Redis, queue, etc.).
|
|
4803
|
+
*/
|
|
4804
|
+
onHealthCheck?(): Promise<{
|
|
4805
|
+
name: string;
|
|
4806
|
+
status: 'up' | 'down';
|
|
4807
|
+
}>;
|
|
4808
|
+
/**
|
|
4809
|
+
* Observe every error the app reports — request errors (any status; filter
|
|
4810
|
+
* on `info.status`), uncaught exceptions, unhandled rejections, failed
|
|
4811
|
+
* `waitUntil` work, failed queue jobs, and anything passed to
|
|
4812
|
+
* `reportError()`. Observe-only: the response is not yours to change, and a
|
|
4813
|
+
* throw here is logged and skipped. The place to wire Sentry & co.
|
|
4814
|
+
*/
|
|
4815
|
+
onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
|
|
4816
|
+
/**
|
|
4817
|
+
* Observe every finished response — method, path, the matched route
|
|
4818
|
+
* pattern, status, duration. Only timed while something listens.
|
|
4819
|
+
*/
|
|
4820
|
+
onResponse?(info: ResponseInfo): void | Promise<void>;
|
|
4821
|
+
/**
|
|
4822
|
+
* Called on shutdown — release what this adapter owns.
|
|
4823
|
+
*
|
|
4824
|
+
* Runs on a real shutdown AND on **every HMR reload**, so treat it as a hot
|
|
4825
|
+
* path in dev, not an exit-only courtesy.
|
|
4826
|
+
*
|
|
4827
|
+
* Close only what you own. The `server` from {@link AdapterContext} is
|
|
4828
|
+
* SHARED — in dev it is Vite's listener — and closing it takes the dev
|
|
4829
|
+
* server down with no way to rebind. `io.close()` on a socket.io server
|
|
4830
|
+
* does exactly that; detach with `io.engine.close()` instead. The framework
|
|
4831
|
+
* closes the shared server itself on a real shutdown.
|
|
4832
|
+
*
|
|
4833
|
+
* Time-boxed: `shutdownTimeout` on a real shutdown, `min(shutdownTimeout,
|
|
4834
|
+
* 5s)` on a reload. Overruns are logged by name and skipped.
|
|
4835
|
+
*/
|
|
4836
|
+
shutdown?(): MaybePromise;
|
|
4837
|
+
/**
|
|
4838
|
+
* Optional DevTools introspection hook (architecture.md §23). Returns
|
|
4839
|
+
* a snapshot describing this adapter's current state, metrics, and DI
|
|
4840
|
+
* tokens. DevTools awaits the result, so async work is fine — but keep
|
|
4841
|
+
* the implementation cheap (counters + flags, no DB round trips) since
|
|
4842
|
+
* the topology endpoint polls on a short interval.
|
|
4843
|
+
*
|
|
4844
|
+
* The return type lives in `@forinda/kickjs` itself ({@link IntrospectionSnapshot})
|
|
4845
|
+
* so adopters can author `introspect()` without importing the kit just
|
|
4846
|
+
* to satisfy the contract. The kit's own `IntrospectionSnapshot` type
|
|
4847
|
+
* stays structurally identical; either import works.
|
|
4848
|
+
*/
|
|
4849
|
+
introspect?(): IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
|
|
4850
|
+
/**
|
|
4851
|
+
* Optional DevTools tabs this adapter contributes (architecture.md §23).
|
|
4852
|
+
* Returns an array of `DevtoolsTabDescriptor` shapes — typically one
|
|
4853
|
+
* entry per adapter-owned panel (iframe / launch / html view).
|
|
4854
|
+
*
|
|
4855
|
+
* Same untyped-at-this-layer convention as {@link introspect}: adapter
|
|
4856
|
+
* authors import `defineDevtoolsTab` (or the bare type) from
|
|
4857
|
+
* `@forinda/kickjs-devtools-kit` so `@forinda/kickjs` doesn't take on
|
|
4858
|
+
* a runtime dep on the kit.
|
|
4859
|
+
*/
|
|
4860
|
+
devtoolsTabs?(): readonly unknown[];
|
|
4861
|
+
}
|
|
4862
|
+
/** Constructor type for AppAdapter classes */
|
|
4863
|
+
type AppAdapterClass = new () => AppAdapter;
|
|
4864
|
+
//#endregion
|
|
4865
|
+
export { applyUploadConfig as $, ContributorPipeline as $n, BuildContext as $r, ConditionalOutcome as $t, SseHandler as A, StartupTimelineSnapshot as An, disposeAll as Ar, PasswordHashOptions as At, ViewAdapter as B, AdapterAsyncOptions as Bn, NoJobHandlerError as Br, HANDLER_CHANNEL as Bt, RuntimeResponse as C, reply as Cn, setInMetaRecord as Cr, buildRouteTable as Ct, DeepReadonly as D, StartupCheckError as Dn, KickErrorInit as Dr, VerifyOptions as Dt, Ctx as E, StartupCheck as En, KickError as Er, SignerOptions as Et, UrlForArgs as F, AssetKeyStrategy as Fn, Job as Fr, isClusterPrimary as Ft, parseTraceparent as G, MissingMountDepError as Gn, registerJobContext as Gr, KickCronAdapter as Gt, TRACEPARENT_HEADER as H, DefineAdapterOptions as Hn, ProcessDefinition as Hr, RESPONSE_CHANNEL as Ht, UrlQuery as I, GroupAssetKeysOptions as In, JobContextCarrier as Ir, KickHandler as It, buildUploadMiddleware as J, MountSortItem as Jn, ModuleList as Jr, settleBackgroundWork as Jt, traceContext as K, MountCycleError as Kn, runJob as Kr, RAW_BODY as Kt, SpaAdapter as L, GroupAssetKeysResult as Ln, JobDispatcher as Lr, createHandler as Lt, ROUTE_URLS as M, bindRoutePolicy as Mn, JOB_CONTEXT_FIELD as Mr, verifyPassword as Mt, RouteName as N, offerRoutePolicy as Nn, JOB_DISPATCHER as Nr, defineHttpContextDecorator as Nt, RequestContext as O, defineCheck as On, formatKickError as Or, createSigner as Ot, UrlBuilder as P, AssetKeyPair as Pn, JOB_META as Pr, ClusterOptions as Pt, UploadedFileLike as Q, BuildPipelineOptions as Qn, defineModule as Qr, metricsAdapter as Qt, SpaAdapterOptions as R, groupAssetKeys as Rn, JobHandler as Rr, bootstrap as Rt, RuntimeCapabilities as S, onPackage as Si, isRespondable as Sn, setInMetaMap as Sr, assertRouteUnique as St, UseConnectOptions as T, CheckMessage as Tn, FormatKickErrorOptions as Tr, Signer as Tt, TraceContext as U, defineAdapter as Un, listJobHandlers as Ur, CRON_WORKER_ENV as Ut, ViewAdapterOptions as V, AdapterFactory as Vn, Process as Vr, HandlerTraceContext as Vt, TraceContextOptions as W, DuplicateMountNameError as Wn, listJobQueues as Wr, CronAdapterOptions as Wt, upload as X, RunContributorsOptions as Xn, DefineModuleOptions as Xr, MetricsOptions as Xt, cleanupFiles as Y, mountSort as Yn, defineModules as Yr, waitUntil as Yt, RawUploadPart as Z, runContributors as Zn, ModuleFactory as Zr, RequestHistogram as Zt, RouteEntry as _, FailureAdvice as _i, RESPOND as _n, getMethodMetaOrUndefined as _r, buildRoutes as _t, KickServer as a, ModuleRegistry as ai, ConfigOrigins as an, MissingContextValueError as ar, KvSessionStore as at, RouteTable as b, allOf as bi, applyHandlerResult as bn, pushMethodMeta as br, BuildRoutesOptions as bt, ActiveRuntime as c, KickJsPluginRegistry as ci, ServerOptions as cn, CircuitBreakerOptions as cr, rateLimitGuard as ct, CtxHandler as d, IntrospectionSnapshot as di, HealthCheckResult as dn, CircuitOpenError as dr, notFoundHandler as dt, DefinePluginOptions as ei, Validators as en, ContributorSource as er, buildFileTypeFilter as et, ExpressRuntimeTypes as f, ErrorInfo as fi, HealthController as fn, getClassMeta as fr, requestScopeMiddleware as ft, RouteContributor as g, reportResponse as gi, InferHandlerResponse as gn, getMethodMeta as gr, requestStore as gt, MatchedRoute as h, reportError as hi, healthModule as hn, getMetaRecord as hr, getRequestValue as ht, AppAdapterClass as i, KickPlugin as ii, ConfigDescription as in, DuplicateContributorError as ir, KvRateLimitStoreOptions as it, contentDisposition as j, RoutePolicyTable as jn, registerDisposable as jr, hashPassword as jt, RouteShape as k, StartupStep as kn, Disposable as kr, PasswordCheck as kt, AdapterHttp as l, IntrospectFn as li, ShutdownOptions as ln, CircuitBreakerState as lr, MountedRoute as lt, KickRuntimeRegister as m, ResponseInfo as mi, HealthProbe as mn, getMetaMap as mr, getRequestStore as mt, AdapterMiddleware as n, PluginFactory as ni, Application as nn, buildPipeline as nr, KvLike as nt, MiddlewarePath as o, MutableModuleRegistry as oi, MiddlewareEntry as on, MissingContributorError as or, KvSessionStoreOptions as ot, HttpRuntime as p, ErrorSource as pi, HealthModuleConfig as pn, getClassMetaOrUndefined as pr, RequestStore as pt, UploadOptions as q, MountKind as qn, stampJobContext as qr, PlatformContext as qt, AppAdapter as r, definePlugin as ri, ApplicationOptions as rn, ContributorCycleError as rr, KvRateLimitStore as rt, MiddlewarePhase as s, KickJsPluginName as si, MountedRouteInfo as sn, CircuitBreaker as sr, RateLimitGuardOptions as st, AdapterContext as t, PluginAsyncOptions as ti, evaluatePreconditions as tn, SourcedRegistration as tr, resolveMimeTypes as tt, ConnectMiddleware as u, IntrospectionKind as ui, HEALTH_PROBE as un, CircuitBreakerStats as ur, errorHandler as ut, RouteMeta as v, AdapterCondition as vi, Reply as vn, hasClassMeta as vr, expressRuntime as vt, RuntimeTypeMap as w, CheckContext as wn, setMethodMeta as wr, SignedCheck as wt, RuntimeAppOptions as x, onEnv as xi, isReply as xn, setClassMeta as xr, _setExternalContributorSources as xt, RouteMethod as y, ConditionOutcome as yi, Respondable as yn, pushClassMeta as yr, materializeRouter as yt, resolveClientDir as z, stripExt as zn, JobLike as zr, ERROR_CHANNEL as zt };
|
|
4866
|
+
//# sourceMappingURL=adapter-C5I5e_-i.d.mts.map
|