@forinda/kickjs 10.3.0 → 10.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/dist/adapter-6fjmVVc2.d.mts +2324 -0
  2. package/dist/adapter-6fjmVVc2.d.mts.map +1 -0
  3. package/dist/{app-module-Ftz6m7SO.d.mts → app-module-Cuu-Ma_E.d.mts} +5 -4
  4. package/dist/app-module-Cuu-Ma_E.d.mts.map +1 -0
  5. package/dist/application-BuUWvaqp.d.mts +1985 -0
  6. package/dist/application-BuUWvaqp.d.mts.map +1 -0
  7. package/dist/{application-B2e5XYHm.mjs → application-CYCvctQx.mjs} +3 -3
  8. package/dist/{application-B2e5XYHm.mjs.map → application-CYCvctQx.mjs.map} +1 -1
  9. package/dist/bootstrap-CfaYHbmd.mjs +12 -0
  10. package/dist/{bootstrap-BmALF-1Y.mjs.map → bootstrap-CfaYHbmd.mjs.map} +1 -1
  11. package/dist/{bounded-counters-aA3iI_Ei.mjs → bounded-counters-BcA0f0bV.mjs} +2 -2
  12. package/dist/{bounded-counters-aA3iI_Ei.mjs.map → bounded-counters-BcA0f0bV.mjs.map} +1 -1
  13. package/dist/{client-ip-D2dsx8RG.mjs → client-ip-BpauuVN_.mjs} +2 -2
  14. package/dist/{client-ip-D2dsx8RG.mjs.map → client-ip-BpauuVN_.mjs.map} +1 -1
  15. package/dist/config/index.d.mts +1 -1
  16. package/dist/config/index.mjs +2 -2
  17. package/dist/{config-B77LTW_E.mjs → config-DgMxtfcW.mjs} +3 -3
  18. package/dist/{config-B77LTW_E.mjs.map → config-DgMxtfcW.mjs.map} +1 -1
  19. package/dist/container-4iJdDkRH.d.mts +3 -0
  20. package/dist/{context-GbQnJB-L.mjs → context-DJvuLfrx.mjs} +3 -3
  21. package/dist/{context-GbQnJB-L.mjs.map → context-DJvuLfrx.mjs.map} +1 -1
  22. package/dist/{context-errors-CPqYYhl0.mjs → context-errors-BGIOYMV5.mjs} +2 -2
  23. package/dist/{context-errors-CPqYYhl0.mjs.map → context-errors-BGIOYMV5.mjs.map} +1 -1
  24. package/dist/{contributor-runner-Cl5yZZy1.mjs → contributor-runner-CJn1gZ8h.mjs} +3 -3
  25. package/dist/{contributor-runner-Cl5yZZy1.mjs.map → contributor-runner-CJn1gZ8h.mjs.map} +1 -1
  26. package/dist/core/adapter.d.mts +1 -1
  27. package/dist/core/adapter.mjs +1 -1
  28. package/dist/core/app-module.d.mts +1 -1
  29. package/dist/core/app-module.mjs +1 -1
  30. package/dist/core/cache.mjs +1 -1
  31. package/dist/core/container.d.mts +2 -2
  32. package/dist/core/container.mjs +2 -2
  33. package/dist/core/cron.mjs +2 -2
  34. package/dist/core/decorators.d.mts +2 -2
  35. package/dist/core/decorators.mjs +2 -2
  36. package/dist/core/decorators.mjs.map +1 -1
  37. package/dist/core/errors.mjs +1 -1
  38. package/dist/core/interfaces.d.mts +2 -2
  39. package/dist/core/interfaces.mjs +2 -2
  40. package/dist/core/interfaces.mjs.map +1 -1
  41. package/dist/core/logger.mjs +1 -1
  42. package/dist/core/path.mjs +1 -1
  43. package/dist/core/plugin.d.mts +1 -1
  44. package/dist/core/plugin.mjs +1 -1
  45. package/dist/core/reactivity.mjs +1 -1
  46. package/dist/core-YE-k8IrU.mjs +12 -0
  47. package/dist/{core-D1AV-Tvd.mjs.map → core-YE-k8IrU.mjs.map} +1 -1
  48. package/dist/{csrf-D3prC4FK.mjs → csrf-C6Em76kH.mjs} +3 -3
  49. package/dist/{csrf-D3prC4FK.mjs.map → csrf-C6Em76kH.mjs.map} +1 -1
  50. package/dist/{csrf-Cy1meSpf.d.mts → csrf-ahBjt1ay.d.mts} +2 -2
  51. package/dist/{csrf-Cy1meSpf.d.mts.map → csrf-ahBjt1ay.d.mts.map} +1 -1
  52. package/dist/decorate-CaEYam5J.mjs +13 -0
  53. package/dist/{decorate-BiXL-9e9.mjs.map → decorate-CaEYam5J.mjs.map} +1 -1
  54. package/dist/{decorators-DaQUNXOn.d.mts → decorators-deGmthGc.d.mts} +3 -199
  55. package/dist/decorators-deGmthGc.d.mts.map +1 -0
  56. package/dist/{define-adapter-D22SDe0U.mjs → define-adapter-C6H-I1og.mjs} +2 -2
  57. package/dist/{define-adapter-D22SDe0U.mjs.map → define-adapter-C6H-I1og.mjs.map} +1 -1
  58. package/dist/di-hooks-BE0IOQk-.mjs +132 -0
  59. package/dist/di-hooks-BE0IOQk-.mjs.map +1 -0
  60. package/dist/disposables-Cste73oY.mjs +11 -0
  61. package/dist/error-handler-C6JJJct_.d.mts +63 -0
  62. package/dist/error-handler-C6JJJct_.d.mts.map +1 -0
  63. package/dist/{handler-gW_h2miq.mjs → handler-DUyRCpPw.mjs} +3 -3
  64. package/dist/{handler-gW_h2miq.mjs.map → handler-DUyRCpPw.mjs.map} +1 -1
  65. package/dist/{host-D__uZPyz.mjs → host-fc-YQZnN.mjs} +2 -2
  66. package/dist/{host-D__uZPyz.mjs.map → host-fc-YQZnN.mjs.map} +1 -1
  67. package/dist/http/application.d.mts +1 -1
  68. package/dist/http/application.mjs +2 -2
  69. package/dist/http/bootstrap.d.mts +1 -1
  70. package/dist/http/bootstrap.mjs +2 -2
  71. package/dist/http/context.d.mts +2 -2
  72. package/dist/http/context.mjs +2 -2
  73. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  74. package/dist/http/middleware/breach-padding.mjs +1 -1
  75. package/dist/http/middleware/cors.mjs +1 -1
  76. package/dist/http/middleware/csrf.d.mts +1 -1
  77. package/dist/http/middleware/csrf.mjs +2 -2
  78. package/dist/http/middleware/error-handler.d.mts +1 -1
  79. package/dist/http/middleware/error-handler.mjs +2 -2
  80. package/dist/http/middleware/helmet.mjs +1 -1
  81. package/dist/http/middleware/rate-limit.mjs +2 -2
  82. package/dist/http/middleware/request-id.mjs +1 -1
  83. package/dist/http/middleware/request-logger.mjs +2 -2
  84. package/dist/http/middleware/session.mjs +2 -2
  85. package/dist/http/middleware/spa.d.mts +1 -1
  86. package/dist/http/middleware/spa.mjs +2 -2
  87. package/dist/http/middleware/upload.d.mts +1 -1
  88. package/dist/http/middleware/upload.mjs +2 -2
  89. package/dist/http/middleware/validate.mjs +1 -1
  90. package/dist/http/middleware/views.d.mts +1 -1
  91. package/dist/http/middleware/views.mjs +2 -2
  92. package/dist/http/query/index.mjs +2 -2
  93. package/dist/http/router-builder.d.mts +1 -1
  94. package/dist/http/router-builder.mjs +2 -2
  95. package/dist/http/runtimes/fastify.d.mts +1 -1
  96. package/dist/http/runtimes/fastify.mjs +2 -2
  97. package/dist/http/runtimes/h3-web.mjs +1 -1
  98. package/dist/http/runtimes/h3.d.mts +1 -1
  99. package/dist/http/runtimes/h3.mjs +2 -2
  100. package/dist/{index-CuiWSnZL.d.mts → index-Dms8LzHG.d.mts} +3 -3
  101. package/dist/{index-CuiWSnZL.d.mts.map → index-Dms8LzHG.d.mts.map} +1 -1
  102. package/dist/index.d.mts +16 -10
  103. package/dist/index.mjs +2 -2
  104. package/dist/index.mjs.map +1 -1
  105. package/dist/interfaces-C6LHcYsg.d.mts +34 -0
  106. package/dist/interfaces-C6LHcYsg.d.mts.map +1 -0
  107. package/dist/{is-production-Dbm13WNL.mjs → is-production-0lB5MU1j.mjs} +2 -2
  108. package/dist/{is-production-Dbm13WNL.mjs.map → is-production-0lB5MU1j.mjs.map} +1 -1
  109. package/dist/jobs-DWi_Lwbe.mjs +12 -0
  110. package/dist/{jobs-s4__kZLr.mjs.map → jobs-DWi_Lwbe.mjs.map} +1 -1
  111. package/dist/kv-stores-BGXPKv15.d.mts +366 -0
  112. package/dist/kv-stores-BGXPKv15.d.mts.map +1 -0
  113. package/dist/{kv-stores-Cjel_Dkc.mjs → kv-stores-BGXeNEDK.mjs} +3 -3
  114. package/dist/{kv-stores-Cjel_Dkc.mjs.map → kv-stores-BGXeNEDK.mjs.map} +1 -1
  115. package/dist/{lazy-serve-static-w94Xs3wQ.mjs → lazy-serve-static-Barg3__1.mjs} +2 -2
  116. package/dist/{lazy-serve-static-w94Xs3wQ.mjs.map → lazy-serve-static-Barg3__1.mjs.map} +1 -1
  117. package/dist/metadata-CnL9sQFa.mjs +11 -0
  118. package/dist/{observers-boPE9XGi.mjs → observers-BNMQ7VLb.mjs} +2 -2
  119. package/dist/{observers-boPE9XGi.mjs.map → observers-BNMQ7VLb.mjs.map} +1 -1
  120. package/dist/{query-DjTeF1d4.mjs → query-mXPZYtQw.mjs} +2 -2
  121. package/dist/{query-DjTeF1d4.mjs.map → query-mXPZYtQw.mjs.map} +1 -1
  122. package/dist/{reply-CYY_CzRf.mjs → reply-CMRk-Jp3.mjs} +3 -3
  123. package/dist/{reply-CYY_CzRf.mjs.map → reply-CMRk-Jp3.mjs.map} +1 -1
  124. package/dist/{respond-Dc18G0X7.mjs → respond-gPELdOSi.mjs} +2 -2
  125. package/dist/{respond-Dc18G0X7.mjs.map → respond-gPELdOSi.mjs.map} +1 -1
  126. package/dist/{route-flag-BOQZs2Wn.mjs → route-flag-8Pi83-uw.mjs} +3 -3
  127. package/dist/{route-flag-BOQZs2Wn.mjs.map → route-flag-8Pi83-uw.mjs.map} +1 -1
  128. package/dist/{route-policy-B8c6QfiU.mjs → route-policy-0LAfSzo-.mjs} +2 -2
  129. package/dist/{route-policy-B8c6QfiU.mjs.map → route-policy-0LAfSzo-.mjs.map} +1 -1
  130. package/dist/router-builder-D0SDqFTr.mjs +12 -0
  131. package/dist/{router-builder-DoWOIGmG.mjs.map → router-builder-D0SDqFTr.mjs.map} +1 -1
  132. package/dist/router-builder-obSpg-Ub.d.mts +56 -0
  133. package/dist/router-builder-obSpg-Ub.d.mts.map +1 -0
  134. package/dist/settings-BW5gVm6c.mjs +14 -0
  135. package/dist/{settings-DcytOCC6.mjs.map → settings-BW5gVm6c.mjs.map} +1 -1
  136. package/dist/{settings-C8VKewNS.d.mts → settings-BnE75hnr.d.mts} +2 -2
  137. package/dist/{settings-C8VKewNS.d.mts.map → settings-BnE75hnr.d.mts.map} +1 -1
  138. package/dist/token-D6jfTQLA.d.mts +3 -0
  139. package/dist/token-Q2c8xwJE.mjs +11 -0
  140. package/dist/upload-CyBSlnH_.d.mts +104 -0
  141. package/dist/upload-CyBSlnH_.d.mts.map +1 -0
  142. package/dist/{upload-config-CzxbJALL.mjs → upload-config-D22qKth8.mjs} +2 -2
  143. package/dist/{upload-config-CzxbJALL.mjs.map → upload-config-D22qKth8.mjs.map} +1 -1
  144. package/dist/url-for-UZ5kJjsG.mjs +12 -0
  145. package/dist/{url-for-DGSrVfdD.mjs.map → url-for-UZ5kJjsG.mjs.map} +1 -1
  146. package/dist/web.d.mts +5 -4
  147. package/dist/web.d.mts.map +1 -1
  148. package/dist/web.mjs +2 -2
  149. package/dist/web.mjs.map +1 -1
  150. package/package.json +2 -1
  151. package/dist/adapter-BYdxuKiM.d.mts +0 -4916
  152. package/dist/adapter-BYdxuKiM.d.mts.map +0 -1
  153. package/dist/app-module-Ftz6m7SO.d.mts.map +0 -1
  154. package/dist/bootstrap-BmALF-1Y.mjs +0 -12
  155. package/dist/container-Dpvd66Yt.d.mts +0 -298
  156. package/dist/container-Dpvd66Yt.d.mts.map +0 -1
  157. package/dist/container-mvaAYThX.mjs +0 -132
  158. package/dist/container-mvaAYThX.mjs.map +0 -1
  159. package/dist/core-D1AV-Tvd.mjs +0 -12
  160. package/dist/decorate-BiXL-9e9.mjs +0 -13
  161. package/dist/decorators-DaQUNXOn.d.mts.map +0 -1
  162. package/dist/disposables-CJD_gWlA.mjs +0 -12
  163. package/dist/disposables-CJD_gWlA.mjs.map +0 -1
  164. package/dist/interfaces-C1hCSoLD.d.mts +0 -75
  165. package/dist/interfaces-C1hCSoLD.d.mts.map +0 -1
  166. package/dist/jobs-s4__kZLr.mjs +0 -12
  167. package/dist/metadata-C2GK_17k.mjs +0 -12
  168. package/dist/metadata-C2GK_17k.mjs.map +0 -1
  169. package/dist/router-builder-DoWOIGmG.mjs +0 -12
  170. package/dist/settings-DcytOCC6.mjs +0 -14
  171. package/dist/url-for-DGSrVfdD.mjs +0 -12
@@ -0,0 +1,2324 @@
1
+
2
+ import "./token-D6jfTQLA.mjs";
3
+ import { i as SettingsDeclaration } from "./settings-BnE75hnr.mjs";
4
+ import { g as FileUploadConfig, k as RouteDefinition, x as MiddlewareHandler } from "./decorators-deGmthGc.mjs";
5
+ import { t as Container$1 } from "./container-4iJdDkRH.mjs";
6
+ import { p as RouteFlags } from "./route-flag-B1lQht6v.mjs";
7
+ import { i as Constructor, s as MaybePromise } from "./interfaces-C6LHcYsg.mjs";
8
+ import { C as MetaValue, S as ExecutionContext, m as ContributorRegistrations, o as AnyContributorRegistration, r as AppModuleEntry, t as AppModule, x as ContextMetaKey } from "./app-module-Cuu-Ma_E.mjs";
9
+ import "./cache-C0qL0NSD.mjs";
10
+ import { i as ProblemDetails } from "./errors-By6UueCm.mjs";
11
+ import { n as Session } from "./session-ChXx7jG5.mjs";
12
+ import { S as QueryFieldConfig, T as TypedParsedQuery, t as ParseQueryOptions, v as PaginatedResponse } from "./index-BfT5KZ-M.mjs";
13
+ import { t as ValidationErrorFactory } from "./validate-CzjCbRUn.mjs";
14
+ import "reflect-metadata";
15
+ import { Disposable, disposeAll, getClassMeta, getClassMetaOrUndefined, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, hasClassMeta, pushClassMeta, pushMethodMeta, registerDisposable, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta } from "@forinda/kickjs-di";
16
+ import http, { IncomingMessage, ServerResponse } from "node:http";
17
+ import https from "node:https";
18
+ import http2 from "node:http2";
19
+ import { ErrorRequestHandler, Express as Express$1, NextFunction, Request as Request$1, RequestHandler, Response as Response$1 } from "express";
20
+ //#region src/core/adapter-conditions.d.ts
21
+ /**
22
+ * `true` keeps the adapter; `false` or a string (the reason) leaves it out.
23
+ * Runs once at startup — keep it synchronous and free of side effects.
24
+ */
25
+ type AdapterCondition = () => boolean | string;
26
+ /** One adapter's outcome, as `app.getConditionReport()` lists it. */
27
+ interface ConditionOutcome {
28
+ adapter: string;
29
+ enabled: boolean;
30
+ /** Why it was left out; absent when enabled. */
31
+ reason?: string;
32
+ }
33
+ /**
34
+ * On when the env variable is set (non-empty) — or equals `value`.
35
+ *
36
+ * when: onEnv('REDIS_URL')
37
+ * when: onEnv('QUEUE_DRIVER', 'redis')
38
+ */
39
+ declare function onEnv(name: string, value?: string): AdapterCondition;
40
+ /**
41
+ * On when the app can import `name` — for an adapter that needs an optional
42
+ * dependency.
43
+ *
44
+ * when: onPackage('ioredis')
45
+ */
46
+ declare function onPackage(name: string): AdapterCondition;
47
+ /** On only when every condition is — the first that fails gives the reason. */
48
+ declare function allOf(...conditions: AdapterCondition[]): AdapterCondition;
49
+ //#endregion
50
+ //#region src/core/failure-analysis.d.ts
51
+ /**
52
+ * Turn a startup failure into advice: what went wrong in words, and what to
53
+ * change — instead of a driver's stack trace that names a socket.
54
+ *
55
+ * @module @forinda/kickjs/core/failure-analysis
56
+ */
57
+ /** What an analyzer says about an error it recognises. */
58
+ interface FailureAdvice {
59
+ summary: string;
60
+ cause?: string;
61
+ fix: string;
62
+ }
63
+ //#endregion
64
+ //#region src/core/observers.d.ts
65
+ /** Where an error came from. Integrations may report their own sources. */
66
+ type ErrorSource = 'request' | 'uncaught' | 'unhandled-rejection' | 'background' | 'job' | (string & {});
67
+ interface ErrorInfo {
68
+ source: ErrorSource;
69
+ requestId?: string;
70
+ method?: string;
71
+ /** The request URL path, as received. */
72
+ path?: string;
73
+ /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */
74
+ route?: string;
75
+ /** The status the error was answered with, for request errors. */
76
+ status?: number;
77
+ /** Anything else the reporter knows — a queue and job name, a cron schedule. */
78
+ context?: Record<string, unknown>;
79
+ }
80
+ interface ResponseInfo {
81
+ method: string;
82
+ path: string;
83
+ /** The matched route pattern, or undefined when no route matched (404s). */
84
+ route?: string;
85
+ status: number;
86
+ durationMs: number;
87
+ requestId?: string;
88
+ }
89
+ /**
90
+ * Report an error to every observer. The framework calls this for request
91
+ * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and
92
+ * queue job failures; call it from your own integrations too (a cron runner,
93
+ * a message consumer). Never throws.
94
+ */
95
+ declare function reportError(error: unknown, info: ErrorInfo): void;
96
+ /** Report a finished response to every observer. Never throws. */
97
+ declare function reportResponse(info: ResponseInfo): void;
98
+ //#endregion
99
+ //#region src/core/introspect.d.ts
100
+ /**
101
+ * Per-primitive introspection snapshot — the JSON shape an adapter or
102
+ * plugin's optional `introspect()` hook returns for DevTools.
103
+ *
104
+ * Lives in `@forinda/kickjs` (not `@forinda/kickjs-devtools-kit`) so
105
+ * adopters can type their `introspect()` return without taking on a
106
+ * dep on the kit just to satisfy the contract. The kit's own
107
+ * `IntrospectionSnapshot` type is structurally identical and continues
108
+ * to be the canonical doc location for DevTools-side consumers; the
109
+ * two stay in lockstep — if a field is added on one side it MUST be
110
+ * added on the other (covered by the type-equivalence test in the
111
+ * devtools-kit package).
112
+ *
113
+ * Cheap-by-default principle: `state` and `metrics` should be O(1) to
114
+ * compute (counters, flags, recent samples). Anything that requires a
115
+ * DB round trip or a full DI graph walk belongs behind a separate
116
+ * explicit RPC — DevTools polls topology aggressively.
117
+ */
118
+ interface IntrospectionSnapshot {
119
+ /**
120
+ * Wire-protocol version this snapshot conforms to. The kit ships a
121
+ * `PROTOCOL_VERSION` constant typed as the literal `1`; we mirror
122
+ * that literal here so structural parity is enforced both ways —
123
+ * an adopter who writes `protocolVersion: 1` satisfies both this
124
+ * type and the kit's `IntrospectionSnapshot`. Bumping is a
125
+ * coordinated kit + framework release; widen this literal in
126
+ * lockstep.
127
+ */
128
+ protocolVersion: 1;
129
+ /** Stable identity matching the `name` from `definePlugin` / `defineAdapter`. */
130
+ name: string;
131
+ /** Discriminator for what kind of primitive this is. */
132
+ kind: IntrospectionKind;
133
+ /** Optional version string from the plugin / adapter metadata. */
134
+ version?: string;
135
+ /**
136
+ * Reactive state surface — JSON-serialisable snapshot. Keep small
137
+ * (under a few KB) so polling stays cheap.
138
+ */
139
+ state?: Record<string, unknown>;
140
+ /** DI tokens this primitive registers (`provides`) or consumes (`requires`). */
141
+ tokens?: {
142
+ provides: readonly string[];
143
+ requires: readonly string[];
144
+ };
145
+ /**
146
+ * Per-instance counters — active connections, in-flight jobs, cached
147
+ * items, etc. Numbers only so the DevTools panel can chart trends.
148
+ */
149
+ metrics?: Record<string, number>;
150
+ /** Self-reported memory footprint estimate, in bytes. Optional. */
151
+ memoryBytes?: number;
152
+ }
153
+ /**
154
+ * What kind of primitive an introspection snapshot describes. Matches
155
+ * the kit's `IntrospectionKind` and the routing the topology aggregator
156
+ * does when bucketing adapters vs plugins vs middleware vs contributor
157
+ * primitives.
158
+ */
159
+ type IntrospectionKind = 'plugin' | 'adapter' | 'middleware' | 'contributor';
160
+ /**
161
+ * Convenience function signature for adopter-side helpers that return
162
+ * a complete snapshot. Used by the optional `introspect?()` hook on
163
+ * `AppAdapter` and `KickPlugin`.
164
+ */
165
+ type IntrospectFn = () => IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
166
+ //#endregion
167
+ //#region src/core/augmentation.d.ts
168
+ /**
169
+ * The canonical `KickJsPluginRegistry` interface that `kick typegen`
170
+ * augments, for typed `dependsOn` between plugins and adapters.
171
+ *
172
+ * See `architecture.md` §21.2.1 (typegen for `dependsOn`) and §21.3.3
173
+ * (standardized augmentation registry) for the design rationale.
174
+ *
175
+ * @module @forinda/kickjs/core/augmentation
176
+ */
177
+ /**
178
+ * Marker interface that lists every plugin/adapter in the project. The
179
+ * keys are the literal `name` field passed to `defineAdapter` /
180
+ * `definePlugin` (or declared on a `class implements AppAdapter`); the
181
+ * values are the kind tag (`'plugin' | 'adapter'`).
182
+ *
183
+ * The framework ships this empty. `kick typegen` augments it from
184
+ * source so `keyof KickJsPluginRegistry` resolves to a string-literal
185
+ * union of every name in scope — and therefore so do `dependsOn`
186
+ * declarations on plugins/adapters.
187
+ */
188
+ interface KickJsPluginRegistry {}
189
+ /**
190
+ * Resolves to a string-literal union of every registered plugin/adapter
191
+ * name when the project's typegen has populated `KickJsPluginRegistry`,
192
+ * or to `string` when the registry is empty (no typegen pass yet).
193
+ *
194
+ * Falling back to `string` keeps fresh projects compiling — the typegen
195
+ * narrowing is a progressive enhancement, not a hard prerequisite.
196
+ */
197
+ type KickJsPluginName = keyof KickJsPluginRegistry extends never ? string : keyof KickJsPluginRegistry & string;
198
+ //#endregion
199
+ //#region src/core/module-registry.d.ts
200
+ /**
201
+ * Imperative receiver passed to {@link KickPlugin.setup} and the
202
+ * top-level `bootstrap({ setup })` callback so adopters can register
203
+ * modules conditionally — based on env flags, runtime config,
204
+ * tenant lists, etc. — instead of being limited to the static
205
+ * `modules: [...]` array.
206
+ *
207
+ * @example
208
+ * ```ts
209
+ * bootstrap({
210
+ * modules: [HelloModule()], // static — always mounted
211
+ * setup(registry) {
212
+ * if (env.ENABLE_ADMIN) registry.mount(AdminModule())
213
+ * for (const tenant of env.TENANTS) {
214
+ * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))
215
+ * }
216
+ * },
217
+ * })
218
+ * ```
219
+ *
220
+ * **Currently exposes only `.mount(module)` — the HTTP-feature path.**
221
+ * A future `.use(module)` for non-HTTP modules (queues, cron, workers,
222
+ * DI-only seeds) is planned but not yet implemented; existing non-HTTP
223
+ * modules continue returning `null` from `routes()` and registering
224
+ * via `.mount()`.
225
+ *
226
+ * Same dispatch rules as the static `modules: [...]` array — class
227
+ * entries get `new`-ed at boot, `defineModule` factory output is used
228
+ * directly. The registry doesn't validate the entry shape itself; the
229
+ * Application loader does the typeof discrimination at mount time.
230
+ */
231
+ interface ModuleRegistry {
232
+ /**
233
+ * Register a module for the full HTTP lifecycle: `register()` runs,
234
+ * `import.meta.glob` decorator side-effects fire, `routes()` is
235
+ * called and its result mounted, `contributors()` are merged at
236
+ * `'module'` precedence and applied to the mounted routes.
237
+ *
238
+ * Modules are mounted in registration order (first call → first
239
+ * mount). Order across sources is: plugin static modules → plugin
240
+ * `setup()` calls → user static modules → user `setup()` callback.
241
+ */
242
+ mount(module: AppModuleEntry): void;
243
+ }
244
+ /**
245
+ * Internal collector implementing {@link ModuleRegistry}. Application
246
+ * passes one of these to every `setup()` callback during bootstrap;
247
+ * the collected `entries` array is then run through the same
248
+ * class-vs-instance dispatch as the static `modules: [...]` array.
249
+ *
250
+ * Not exported from the public surface — adopters interact only
251
+ * through the {@link ModuleRegistry} interface.
252
+ */
253
+ declare class MutableModuleRegistry implements ModuleRegistry {
254
+ readonly entries: AppModuleEntry[];
255
+ mount(module: AppModuleEntry): void;
256
+ }
257
+ //#endregion
258
+ //#region src/core/plugin.d.ts
259
+ /**
260
+ * Plugin interface for extending KickJS applications.
261
+ *
262
+ * Plugins bundle modules, adapters, middleware, and DI bindings into a single
263
+ * reusable unit. They run before the application bootstraps, so they can
264
+ * register services and configure the app before any module loads.
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * import type { KickPlugin } from '@forinda/kickjs'
269
+ *
270
+ * export class CorsPlugin implements KickPlugin {
271
+ * name = 'CorsPlugin'
272
+ *
273
+ * middleware() {
274
+ * return [cors({ origin: '*' })]
275
+ * }
276
+ * }
277
+ *
278
+ * // Usage:
279
+ * bootstrap({
280
+ * modules,
281
+ * plugins: [new CorsPlugin()],
282
+ * })
283
+ * ```
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * // A more complex plugin that bundles modules and adapters
288
+ * export class AuthPlugin implements KickPlugin {
289
+ * name = 'AuthPlugin'
290
+ *
291
+ * constructor(private config: AuthConfig) {}
292
+ *
293
+ * register(container: Container) {
294
+ * container.registerFactory(AUTH_SERVICE, () => new JwtAuthService(this.config))
295
+ * }
296
+ *
297
+ * modules() {
298
+ * return [AuthModule]
299
+ * }
300
+ *
301
+ * adapters() {
302
+ * return [new AuthGuardAdapter(this.config)]
303
+ * }
304
+ *
305
+ * middleware() {
306
+ * return [passport.initialize()]
307
+ * }
308
+ * }
309
+ * ```
310
+ */
311
+ interface KickPlugin {
312
+ /** Human-readable name for logging, debugging, and `dependsOn` resolution. */
313
+ name: string;
314
+ /**
315
+ * Other plugin names that must mount before this one. The framework
316
+ * topologically sorts plugins at boot — cycles or unknown names throw
317
+ * via {@link MountCycleError} / {@link MissingMountDepError} so bad
318
+ * configurations fail boot rather than corrupt live traffic.
319
+ *
320
+ * Plugins with no `dependsOn` retain their declaration order, so
321
+ * existing apps that don't use this field see no behaviour change.
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * class MonitoringPlugin implements KickPlugin {
326
+ * name = 'MonitoringPlugin'
327
+ * // OTel must initialize traces before request logger reads them
328
+ * dependsOn = ['OtelPlugin']
329
+ * }
330
+ * ```
331
+ */
332
+ dependsOn?: readonly KickJsPluginName[];
333
+ /**
334
+ * Register DI bindings before modules load.
335
+ * Use this to provide services that modules depend on.
336
+ */
337
+ register?(container: Container$1): void;
338
+ /**
339
+ * Return modules to be loaded alongside user modules. Plugin
340
+ * modules are loaded before user modules.
341
+ *
342
+ * Accepts both class form (`SomeModule extends AppModule`) and
343
+ * instance form (output of {@link defineModule}'s factory call,
344
+ * e.g. `TasksModule({ scope: 'admin' })`) — the bootstrap loader
345
+ * discriminates and either `new`-s the class or uses the instance
346
+ * directly.
347
+ *
348
+ * Static path — for conditional / dynamic registration, use
349
+ * {@link KickPlugin.setup} instead.
350
+ */
351
+ modules?(): AppModuleEntry[];
352
+ /**
353
+ * Imperative module registration hook. Receives a {@link ModuleRegistry}
354
+ * the plugin can call `.mount(module)` on to register modules
355
+ * conditionally — e.g. based on injected config, env flags, or a
356
+ * tenant list resolved at boot.
357
+ *
358
+ * Runs after the static {@link KickPlugin.modules} array is collected
359
+ * but before user modules and the user-level `setup()` callback. The
360
+ * plugin sees the same dispatch rules as everything else: class
361
+ * entries get `new`-ed, factory output is used directly.
362
+ *
363
+ * @example
364
+ * ```ts
365
+ * definePlugin<{ tenants: string[] }>({
366
+ * name: 'MultiTenantPlugin',
367
+ * build: (config) => ({
368
+ * setup(registry) {
369
+ * for (const tenant of config.tenants) {
370
+ * registry.mount(TenantModule.scoped(tenant, { id: tenant }))
371
+ * }
372
+ * },
373
+ * }),
374
+ * })
375
+ * ```
376
+ */
377
+ setup?(registry: ModuleRegistry): void;
378
+ /**
379
+ * Return adapter instances to be added to the application.
380
+ * Plugin adapters are added before user adapters.
381
+ */
382
+ adapters?(): AppAdapter[];
383
+ /**
384
+ * Return connect-style handlers — `(req, res, next)` — for the global
385
+ * pipeline. Each is mounted through the runtime's `useConnect` seam, so
386
+ * these work on Express, Fastify and h3 alike; only the `req` / `res`
387
+ * shapes differ per engine. Plugin middleware runs before user-defined
388
+ * middleware, and carries no `phase` / `path` — use an adapter's
389
+ * {@link AppAdapter.middleware} for scoped or phased entries.
390
+ */
391
+ middleware?(): any[];
392
+ /**
393
+ * Return Context Contributors (#107) the plugin ships. Contributors
394
+ * returned here merge into the per-route pipeline at the **`'adapter'`
395
+ * precedence level** — same as those returned by adapters the plugin
396
+ * ships via {@link KickPlugin.adapters}, and for the same reason: a
397
+ * plugin is a cross-cutting bundle, narrower than the global default
398
+ * but broader than a per-module hook.
399
+ *
400
+ * Use when a plugin wants to ship a typed contributor without standing
401
+ * up an accompanying adapter. For full coverage of the precedence
402
+ * matrix (method > class > module > adapter > global) see
403
+ * `docs/guide/context-decorators.md`.
404
+ *
405
+ * @example
406
+ * ```ts
407
+ * import { defineContextDecorator, type KickPlugin } from '@forinda/kickjs'
408
+ *
409
+ * const LoadFlags = defineContextDecorator({
410
+ * key: 'flags',
411
+ * resolve: (ctx) => fetchFlags(ctx.requestId!),
412
+ * })
413
+ *
414
+ * export class FlagsPlugin implements KickPlugin {
415
+ * name = 'FlagsPlugin'
416
+ * contributors() {
417
+ * return [LoadFlags.registration]
418
+ * }
419
+ * }
420
+ * ```
421
+ */
422
+ contributors?(): ContributorRegistrations;
423
+ /** Settings sections this plugin needs — validated at startup, bound before any hook runs. */
424
+ settings?(): readonly SettingsDeclaration[];
425
+ /**
426
+ * Called after the application has fully bootstrapped.
427
+ * Use for post-startup logic like logging, health registration, etc.
428
+ */
429
+ onReady?(container: Container$1): void | Promise<void>;
430
+ /**
431
+ * Observe every error the app reports — request errors (any status; filter
432
+ * on `info.status`), uncaught exceptions, unhandled rejections, failed
433
+ * `waitUntil` work, failed queue jobs, and anything passed to
434
+ * `reportError()`. Observe-only: the response is not yours to change, and a
435
+ * throw here is logged and skipped. The place to wire Sentry & co.
436
+ */
437
+ onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
438
+ /**
439
+ * Observe every finished response — method, path, the matched route
440
+ * pattern, status, duration. Only timed while something listens.
441
+ */
442
+ onResponse?(info: ResponseInfo): void | Promise<void>;
443
+ /**
444
+ * Called during application shutdown — release what this plugin owns
445
+ * (connections, intervals, subscriptions).
446
+ *
447
+ * Runs on a real shutdown AND on **every HMR reload**, so it is a hot path
448
+ * in dev, not an exit-only courtesy.
449
+ *
450
+ * Close only what you own. Never close the shared HTTP server: in dev it is
451
+ * Vite's listener, and closing it leaves the port dead with no rebind. The
452
+ * framework closes it itself on a real shutdown.
453
+ *
454
+ * Time-boxed: `shutdownTimeout` on a real shutdown, `min(shutdownTimeout,
455
+ * 5s)` on a reload. Overruns are logged by name and skipped.
456
+ */
457
+ shutdown?(): void | Promise<void>;
458
+ /**
459
+ * Optional DevTools introspection hook (architecture.md §23). Returns
460
+ * a snapshot describing this plugin's current state, metrics, and DI
461
+ * tokens. DevTools awaits the result, so async work is fine — but keep
462
+ * the implementation cheap (counters + flags, no DB round trips) since
463
+ * the topology endpoint polls on a short interval.
464
+ *
465
+ * The return type lives in `@forinda/kickjs` itself
466
+ * ({@link IntrospectionSnapshot}) so adopters can author `introspect()`
467
+ * without importing the kit just to satisfy the contract. The kit's
468
+ * own `IntrospectionSnapshot` type stays structurally identical;
469
+ * either import works.
470
+ */
471
+ introspect?(): IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
472
+ /**
473
+ * Optional DevTools tabs this plugin contributes (architecture.md §23).
474
+ * Same shape as {@link AppAdapter.devtoolsTabs}; the kit's
475
+ * `DevtoolsTabDescriptor` types it for plugin authors.
476
+ */
477
+ devtoolsTabs?(): readonly unknown[];
478
+ }
479
+ //#endregion
480
+ //#region src/core/define-plugin.d.ts
481
+ /**
482
+ * Options passed to {@link definePlugin}. Mirrors the spec in
483
+ * `architecture.md` §21.3.1 + §21.2.2 (Phase A "lite").
484
+ */
485
+ interface DefinePluginOptions<TConfig> {
486
+ /** Stable identity used for logging, `dependsOn` lookups, and `.scoped()` namespacing. */
487
+ name: string;
488
+ /** Optional plugin version — surfaced to DevTools and `kick add` compatibility checks (Phase B). */
489
+ version?: string;
490
+ /**
491
+ * Peer-version ranges this plugin needs from the framework or other
492
+ * plugins. Recorded as metadata; runtime enforcement lands in §21.4.4.
493
+ */
494
+ requires?: {
495
+ kickjs?: string;
496
+ };
497
+ /** Default config merged under any caller overrides. */
498
+ defaults?: Partial<TConfig>;
499
+ /** Builds the underlying {@link KickPlugin} from the resolved config. */
500
+ build(config: TConfig, ctx: BuildContext): Omit<KickPlugin, 'name'>;
501
+ }
502
+ /**
503
+ * Hook context handed to a plugin/adapter `build` function. `name` is the
504
+ * resolved instance name (the bare definition name for the bare call,
505
+ * or `${defName}:${scope}` for `.scoped()`). `scoped` is the discriminator
506
+ * authors use to namespace DI tokens or resource keys.
507
+ */
508
+ interface BuildContext {
509
+ name: string;
510
+ scoped: boolean;
511
+ }
512
+ /**
513
+ * Async-config form of a plugin or adapter — `inject` lists DI tokens to
514
+ * resolve from the container, then `useFactory` produces the config.
515
+ *
516
+ * Plugins resolve this lazily inside `onReady`, so any module/adapter/
517
+ * middleware/contributor a plugin contributes via `build` is **not
518
+ * available** when `.async()` is used. Use the bare/`.scoped()` form for
519
+ * plugins that need to register modules or middleware.
520
+ */
521
+ interface PluginAsyncOptions<TConfig> {
522
+ inject?: ReadonlyArray<unknown>;
523
+ useFactory(...deps: any[]): TConfig | Promise<TConfig>;
524
+ }
525
+ /**
526
+ * Factory returned by {@link definePlugin}. Callable form is the singleton
527
+ * (`AuthPlugin(config)`); `.scoped()` and `.async()` are the multi-instance
528
+ * and deferred-config forms.
529
+ */
530
+ interface PluginFactory<TConfig> {
531
+ (config?: Partial<TConfig>): KickPlugin;
532
+ scoped(scopeName: string, config?: Partial<TConfig>): KickPlugin;
533
+ async(opts: PluginAsyncOptions<TConfig>): KickPlugin;
534
+ /** Read-only access to the original definition — useful for DevTools introspection. */
535
+ readonly definition: Readonly<DefinePluginOptions<TConfig>>;
536
+ }
537
+ /**
538
+ * Build a {@link KickPlugin} factory from a typed definition. See
539
+ * `architecture.md` §21.2.2 for the design rationale.
540
+ *
541
+ * @example
542
+ * ```ts
543
+ * const FlagsPlugin = definePlugin<FlagsConfig>({
544
+ * name: 'FlagsPlugin',
545
+ * defaults: { defaultTtl: 60_000 },
546
+ * build(config) {
547
+ * return {
548
+ * register(container) {
549
+ * container.registerInstance(FLAGS, makeProvider(config))
550
+ * },
551
+ * }
552
+ * },
553
+ * })
554
+ *
555
+ * bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })
556
+ * ```
557
+ */
558
+ declare function definePlugin<TConfig = Record<string, unknown>>(options: DefinePluginOptions<TConfig>): PluginFactory<TConfig>;
559
+ //#endregion
560
+ //#region src/core/define-module.d.ts
561
+ /**
562
+ * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}
563
+ * and {@link DefinePluginOptions} so adopters learn one mental model
564
+ * across all three primitives.
565
+ *
566
+ * The optional `TExtra` generic lets a module ship public methods
567
+ * beyond the standard {@link AppModule} contract — they're preserved
568
+ * on the returned module instance so external callers (tests, sibling
569
+ * modules) can invoke them directly.
570
+ */
571
+ interface DefineModuleOptions<TConfig, TExtra = unknown> {
572
+ /**
573
+ * Stable identity surfaced in diagnostics, route logs, and
574
+ * `.scoped()` namespacing. Required because boot-time error
575
+ * messages reference modules by name — anonymous modules make
576
+ * cycles + missing-dep errors hard to localize.
577
+ */
578
+ name: string;
579
+ /** Optional version string surfaced in diagnostics. */
580
+ version?: string;
581
+ /**
582
+ * Optional kickjs version constraint. Enforced by the framework
583
+ * when implemented; today it lives on the definition for
584
+ * documentation and forward compatibility.
585
+ */
586
+ requires?: {
587
+ kickjs?: string;
588
+ };
589
+ /**
590
+ * Default config merged with overrides at instantiation time
591
+ * (`MyModule({ field: x })`). Call-site overrides win.
592
+ */
593
+ defaults?: Partial<TConfig>;
594
+ /**
595
+ * Build the AppModule shape from the resolved config and context.
596
+ * `ctx.name` is the resolved instance name (the bare definition
597
+ * name for the default call, or `${name}:${scope}` for
598
+ * `.scoped()`); `ctx.scoped` discriminates so the build function
599
+ * can branch on namespacing if needed.
600
+ *
601
+ * Return any extension methods alongside the standard
602
+ * {@link AppModule} surface — they're typed via `TExtra` and stay
603
+ * accessible on the resulting instance.
604
+ */
605
+ build(config: TConfig, ctx: BuildContext): AppModule & TExtra;
606
+ }
607
+ /**
608
+ * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}
609
+ * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),
610
+ * inspect (`MyModule.definition`).
611
+ *
612
+ * `.async()` is intentionally **not** part of the module factory
613
+ * surface. Module config has no async-resolution window: `register()`
614
+ * and `routes()` both run synchronously during bootstrap, before any
615
+ * adapter `beforeStart` hook fires. Adopters that need async-resolved
616
+ * config push it into an adapter (which has `beforeStart`), then
617
+ * inject the resolved value into the module via DI tokens.
618
+ */
619
+ interface ModuleFactory<TConfig, TExtra = unknown> {
620
+ (config?: Partial<TConfig>): AppModule & TExtra;
621
+ scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra;
622
+ readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>;
623
+ }
624
+ /**
625
+ * Build an {@link AppModule} factory from a typed definition. Pairs
626
+ * with {@link defineAdapter}, {@link definePlugin}, and
627
+ * {@link defineContextDecorator} as the fourth `define*` primitive
628
+ * — adopters write modules the same way they write adapters and
629
+ * plugins.
630
+ *
631
+ * The returned factory produces real {@link AppModule} instances
632
+ * that drop into `bootstrap({ modules })` directly. The legacy
633
+ * class form (`class TasksModule implements AppModule { ... }`) keeps
634
+ * working — `bootstrap` accepts either shape.
635
+ *
636
+ * @example
637
+ * ```ts
638
+ * interface TasksConfig {
639
+ * scope: 'public' | 'admin'
640
+ * }
641
+ *
642
+ * const TasksModule = defineModule<TasksConfig>({
643
+ * name: 'TasksModule',
644
+ * defaults: { scope: 'public' },
645
+ * build: (config, { name }) => ({
646
+ * register(container) {
647
+ * container.registerInstance(`tasks:scope:${name}`, config.scope)
648
+ * },
649
+ * routes() {
650
+ * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }
651
+ * },
652
+ * contributors() {
653
+ * return [LoadTenant.registration]
654
+ * },
655
+ * }),
656
+ * })
657
+ *
658
+ * bootstrap({
659
+ * modules: [
660
+ * TasksModule(), // public scope (defaults)
661
+ * TasksModule.scoped('admin', { scope: 'admin' }),
662
+ * ],
663
+ * })
664
+ * ```
665
+ */
666
+ declare function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(options: DefineModuleOptions<TConfig, TExtra>): ModuleFactory<TConfig, TExtra>;
667
+ //#endregion
668
+ //#region src/core/define-modules.d.ts
669
+ /**
670
+ * Chainable registry returned by {@link defineModules}. Extends
671
+ * `Array<AppModuleEntry>` so it drops into `bootstrap({ modules })`
672
+ * unchanged — the framework loader already iterates the array, so a
673
+ * `ModuleList` IS a valid `modules` value with no special handling.
674
+ *
675
+ * The added affordance is `.mount(module)` returning `this` so
676
+ * adopters can build the list fluently:
677
+ *
678
+ * ```ts
679
+ * const modules = defineModules()
680
+ * .mount(HelloModule())
681
+ * .mount(AdminModule())
682
+ *
683
+ * bootstrap({ modules })
684
+ * ```
685
+ *
686
+ * **Why not just use a plain array?** Two reasons. First, the
687
+ * fluent shape reads more naturally for module-list construction —
688
+ * adopters used to `definePlugin().scoped(...)` / `defineAdapter(...)`
689
+ * see the same call-then-call pattern. Second, the registry is the
690
+ * stable extension point: a future `.use(module)` for non-HTTP
691
+ * modules (queues, cron, workers) lands as a method on `ModuleList`
692
+ * without breaking the `Array<AppModuleEntry>` superclass contract.
693
+ */
694
+ declare class ModuleList extends Array<AppModuleEntry> {
695
+ /**
696
+ * Append a module to the list. Returns `this` for chaining.
697
+ *
698
+ * Accepts both class form (`SomeModule extends AppModule`) and
699
+ * `defineModule` factory output — same as the underlying
700
+ * `bootstrap({ modules })` array. The framework loader
701
+ * discriminates `typeof entry === 'function'` at boot.
702
+ */
703
+ mount(module: AppModuleEntry): this;
704
+ }
705
+ /**
706
+ * Build a {@link ModuleList} for the application. Optional vararg
707
+ * lets adopters seed the list inline; subsequent `.mount()` calls
708
+ * append.
709
+ *
710
+ * @example
711
+ * ```ts
712
+ * import { bootstrap, defineModules } from '@forinda/kickjs'
713
+ * import { HelloModule } from './modules/hello/hello.module'
714
+ * import { AdminModule } from './modules/admin/admin.module'
715
+ *
716
+ * // Fluent — most common
717
+ * const modules = defineModules()
718
+ * .mount(HelloModule())
719
+ * .mount(AdminModule())
720
+ *
721
+ * // Or seeded inline + chained
722
+ * const modules2 = defineModules(HelloModule()).mount(AdminModule())
723
+ *
724
+ * await bootstrap({ modules })
725
+ * ```
726
+ *
727
+ * The returned value is an `AppModuleEntry[]` subclass — `bootstrap`
728
+ * accepts it directly without any special-casing. For conditional /
729
+ * dynamic registration at bootstrap time (env flags, runtime config,
730
+ * tenant lists), use the `setup(registry)` callback on `bootstrap`
731
+ * instead — both surfaces compose.
732
+ */
733
+ declare function defineModules(...initial: AppModuleEntry[]): ModuleList;
734
+ //#endregion
735
+ //#region src/core/contributor-pipeline.d.ts
736
+ /**
737
+ * Where a contributor was registered, ordered by precedence
738
+ * (lower index wins). Mirrors `architecture.md` §20.4.
739
+ *
740
+ * Levels (highest → lowest precedence):
741
+ * - `'method'` — `@LoadX` on a controller method.
742
+ * - `'class'` — `@LoadX` on a controller class.
743
+ * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.
744
+ * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies
745
+ * to every module's routes.
746
+ * - `'global'` — `ApplicationOptions.contributors`. App-wide default.
747
+ */
748
+ type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global';
749
+ /**
750
+ * Input row to {@link buildPipeline}. Pairs a registration with its origin
751
+ * so dedup can apply the precedence rule and diagnostic errors can name
752
+ * the offending site.
753
+ *
754
+ * `registration` is the type-erased {@link AnyContributorRegistration}
755
+ * — the runner doesn't care about each registration's narrow `D` /
756
+ * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic
757
+ * contributors in the same `externalSources` / `contributors()`
758
+ * array. The narrow generics from `defineContextDecorator` survive
759
+ * at the *definition* site (where `resolve` is typed); they're erased
760
+ * here so collections compose without `as any` casts.
761
+ */
762
+ interface SourcedRegistration {
763
+ registration: AnyContributorRegistration;
764
+ source: ContributorSource;
765
+ /** Human label surfaced in DuplicateContributorError messages. */
766
+ label?: string;
767
+ }
768
+ /**
769
+ * Resolved, validated, topo-sorted pipeline ready for execution.
770
+ *
771
+ * `contributors` is in execution order — every entry's `dependsOn`
772
+ * keys appear earlier. `keys` is the set of all keys this pipeline
773
+ * produces; the runner uses it for fast existence checks and the
774
+ * builder uses it for missing-dep validation.
775
+ */
776
+ interface ContributorPipeline {
777
+ readonly contributors: readonly AnyContributorRegistration[];
778
+ readonly keys: ReadonlySet<string>;
779
+ }
780
+ interface BuildPipelineOptions {
781
+ /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */
782
+ route?: string;
783
+ }
784
+ /**
785
+ * Build, validate, and topo-sort a contributor pipeline.
786
+ *
787
+ * Pipeline:
788
+ *
789
+ * 1. Group sources by precedence (method > class > module > adapter > global).
790
+ * 2. Within each precedence level, two contributors with the same `key`
791
+ * raise {@link DuplicateContributorError}.
792
+ * 3. Across levels, the highest-precedence contributor wins each key
793
+ * (lower-precedence duplicates are silently dropped — that is the
794
+ * documented override mechanism, not an error).
795
+ * 4. Every key referenced by `dependsOn` must be produced by the
796
+ * surviving set, otherwise {@link MissingContributorError}.
797
+ * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after
798
+ * the queue drains form a cycle → {@link ContributorCycleError}
799
+ * with a reconstructed path.
800
+ *
801
+ * Pure function — no DI, no I/O. Safe to call once at startup per
802
+ * route and cache the result.
803
+ */
804
+ declare function buildPipeline(sources: readonly SourcedRegistration[], options?: BuildPipelineOptions): ContributorPipeline;
805
+ //#endregion
806
+ //#region src/core/contributor-runner.d.ts
807
+ interface RunContributorsOptions {
808
+ /** Pre-built, validated, topo-sorted pipeline. */
809
+ pipeline: ContributorPipeline;
810
+ /** The execution context contributors read from and write into. */
811
+ ctx: ExecutionContext;
812
+ /** DI container used to resolve declared `deps`. */
813
+ container: Container$1;
814
+ /**
815
+ * Route flags in force for the matched route, used to honour a
816
+ * registration's `skipWhen` / `onlyWhen`. Omitted outside a route (the
817
+ * pipeline then runs every contributor, as before).
818
+ */
819
+ flags?: RouteFlags;
820
+ }
821
+ /**
822
+ * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.
823
+ *
824
+ * Sequential — one contributor at a time, in the topo order chosen at
825
+ * pipeline-build time. Per `architecture.md` §20.10, V1 does not run
826
+ * contributors in parallel even within the same topo level; that is a
827
+ * V2 follow-up gated on profiling.
828
+ *
829
+ * ## Error matrix (architecture.md §20.9)
830
+ *
831
+ * | resolve outcome | optional | onError defined | runner behaviour |
832
+ * |-----------------|----------|-----------------|--------------------------------------------------|
833
+ * | throws | true | — | skip; `ctx.get(key)` remains undefined |
834
+ * | throws | false | yes | call hook; returned value (if any) stored |
835
+ * | throws | false | no | propagate the original error |
836
+ * | hook throws | — | yes | propagate the new error |
837
+ * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |
838
+ * | resolves | — | — | `ctx.set(key, value)` |
839
+ *
840
+ * Container.resolve() throwing while building `deps` is treated as a
841
+ * resolve-side throw and flows through the same matrix — adopters who
842
+ * need different behaviour for missing-DI vs. data-lookup failures can
843
+ * wrap the container access inside their own `resolve()`.
844
+ */
845
+ declare function runContributors(options: RunContributorsOptions): Promise<void>;
846
+ //#endregion
847
+ //#region src/core/define-adapter.d.ts
848
+ /**
849
+ * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}
850
+ * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter
851
+ * symmetry rationale.
852
+ *
853
+ * The optional `TExtra` generic lets an adapter ship public methods
854
+ * beyond the standard {@link AppAdapter} contract — they're preserved
855
+ * on the returned adapter instance so external callers (tests, peer
856
+ * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`
857
+ * for the canonical use case.
858
+ */
859
+ interface DefineAdapterOptions<TConfig, TExtra = unknown> {
860
+ /**
861
+ * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`
862
+ * namespacing. Required for adapters that participate in `dependsOn`
863
+ * sort — error messages reference adapters by name.
864
+ */
865
+ name: string;
866
+ version?: string;
867
+ requires?: {
868
+ kickjs?: string;
869
+ };
870
+ defaults?: Partial<TConfig>;
871
+ build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra;
872
+ }
873
+ /**
874
+ * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`
875
+ * but resolved during `beforeStart` (the earliest async hook in
876
+ * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner
877
+ * adapter are **not** picked up. Use the bare/`.scoped()` form when you need
878
+ * those.
879
+ */
880
+ interface AdapterAsyncOptions<TConfig> {
881
+ inject?: ReadonlyArray<unknown>;
882
+ useFactory(...deps: any[]): TConfig | Promise<TConfig>;
883
+ }
884
+ /**
885
+ * Factory returned by {@link defineAdapter}. Same surface as
886
+ * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn
887
+ * one mental model for both primitives. Returned instances carry both
888
+ * the standard {@link AppAdapter} contract and any `TExtra` extension
889
+ * methods the `build` function exposed.
890
+ */
891
+ interface AdapterFactory<TConfig, TExtra = unknown> {
892
+ (config?: Partial<TConfig>): AppAdapter & TExtra;
893
+ scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra;
894
+ async(opts: AdapterAsyncOptions<TConfig>): AppAdapter;
895
+ readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>;
896
+ }
897
+ /**
898
+ * Build an {@link AppAdapter} factory from a typed definition. See
899
+ * `architecture.md` §21.3.4 for migration guidance — most first-party
900
+ * adapter packages collapse to a single `defineAdapter()` call after this
901
+ * lands.
902
+ *
903
+ * @example
904
+ * ```ts
905
+ * const TenantAdapter = defineAdapter<TenantConfig>({
906
+ * name: 'TenantAdapter',
907
+ * defaults: { strategy: 'header', required: true },
908
+ * build: (config) => ({
909
+ * middleware: () => [tenantResolverMiddleware(config)],
910
+ * beforeStart: ({ container }) => registerTenantFactory(container, config),
911
+ * }),
912
+ * })
913
+ *
914
+ * bootstrap({
915
+ * adapters: [
916
+ * TenantAdapter({ strategy: 'subdomain' }),
917
+ * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),
918
+ * ],
919
+ * })
920
+ * ```
921
+ */
922
+ declare function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(options: DefineAdapterOptions<TConfig, TExtra>): AdapterFactory<TConfig, TExtra>;
923
+ //#endregion
924
+ //#region src/http/url-for.d.ts
925
+ /**
926
+ * Build a route's URL from its name — `'UsersController.show'` — instead of
927
+ * spelling the path where you link to it, so a moved route can't leave a
928
+ * redirect, a `Location` header or an email link pointing at the old one.
929
+ *
930
+ * @module @forinda/kickjs/http/url-for
931
+ */
932
+ /**
933
+ * Route names `kick typegen` knows: `'Controller.method'` → the route's
934
+ * shape. Falls back to `string` before typegen has run.
935
+ */
936
+ type RouteName = [keyof KickRoutes.Named] extends [never] ? string : Extract<keyof KickRoutes.Named, string>;
937
+ type ParamsOf<N> = N extends keyof KickRoutes.Named ? KickRoutes.Named[N] extends {
938
+ params: infer P;
939
+ } ? P : Record<string, string | number> : Record<string, string | number>;
940
+ /** `params` is optional when the route has none, required otherwise. */
941
+ type UrlForArgs<N> = Record<string, never> extends ParamsOf<N> ? [params?: ParamsOf<N>, query?: UrlQuery] : [params: ParamsOf<N>, query?: UrlQuery];
942
+ type UrlQuery = Record<string, string | number | boolean | Array<string | number>>;
943
+ /** Builds route URLs by name — what `ROUTE_URLS` resolves to. */
944
+ interface UrlBuilder {
945
+ /**
946
+ * The URL of a route, by name — `'Controller.method'` — with its `:params`
947
+ * filled (encoded) and an optional query string.
948
+ */
949
+ urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
950
+ }
951
+ /**
952
+ * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,
953
+ * a service building a link:
954
+ *
955
+ * ```ts
956
+ * @Service()
957
+ * class Mailer {
958
+ * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}
959
+ * resetLink(token: string) {
960
+ * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`
961
+ * }
962
+ * }
963
+ * ```
964
+ */
965
+ declare const ROUTE_URLS: import("@forinda/kickjs-di").InjectionToken<UrlBuilder>;
966
+ /** One app's route name → full path pattern (`/api/v1/users/:id`). */
967
+ declare class RouteUrls implements UrlBuilder {
968
+ private readonly paths;
969
+ /** First registration wins — a controller mounted twice keeps its first path. */
970
+ add(name: string, path: string): void;
971
+ urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
972
+ build(name: string, params?: Record<string, unknown>, query?: UrlQuery): string;
973
+ }
974
+ declare global {
975
+ namespace KickRoutes {
976
+ /** `'Controller.method'` → route shape, written by `kick typegen`. */
977
+ interface Named {}
978
+ }
979
+ }
980
+ //#endregion
981
+ //#region src/http/conditional.d.ts
982
+ /**
983
+ * Conditional requests (RFC 9110 §13): answer `304 Not Modified` when the
984
+ * client's copy is current, and `412 Precondition Failed` when a write was
985
+ * based on a stale one. Decided from validators the handler supplies — an
986
+ * ETag, a last-modified time — before it does the expensive part.
987
+ *
988
+ * @module @forinda/kickjs/http/conditional
989
+ */
990
+ /** What identifies the current version of a resource. */
991
+ interface Validators {
992
+ /**
993
+ * An entity tag. Quoted for you if bare: `'v42'` → `"v42"`. Prefix with
994
+ * `W/` for a weak tag (same meaning, not byte-identical).
995
+ */
996
+ etag?: string;
997
+ /** When the resource last changed. Compared to the second, as HTTP dates are. */
998
+ lastModified?: Date;
999
+ }
1000
+ /** 200: go on and respond. 304 / 412: answer with that status, no body. */
1001
+ type ConditionalOutcome = 200 | 304 | 412;
1002
+ type Headers = Record<string, string | string[] | undefined>;
1003
+ /**
1004
+ * The outcome of a request's preconditions against the current validators,
1005
+ * evaluated in RFC 9110 §13.2.2 order.
1006
+ */
1007
+ declare function evaluatePreconditions(method: string, headers: Headers, validators: Validators): ConditionalOutcome;
1008
+ //#endregion
1009
+ //#region src/http/context.d.ts
1010
+ /**
1011
+ * Input shape for the typed problem-detail convenience methods on
1012
+ * {@link ProblemSender} (`ctx.problem.notFound`, `.badRequest`, etc.) —
1013
+ * RFC 9457 details minus the `status`, which each method pre-fills.
1014
+ */
1015
+ type ProblemInput = Omit<ProblemDetails, 'status'>;
1016
+ /**
1017
+ * Callable response helper for RFC 9457 — Problem Details responses.
1018
+ * Returned by `ctx.problem`. Invoke directly for a fully-specified
1019
+ * payload, or use the named convenience methods to pre-fill `status` +
1020
+ * `title` for the common codes.
1021
+ *
1022
+ * Each call sets `Content-Type: application/problem+json` and serializes
1023
+ * the canonical shape (defaulting `type` to `about:blank` and `title` to
1024
+ * the IANA reason phrase per RFC 9457 §3.1.1 / §3.1.4).
1025
+ *
1026
+ * @example
1027
+ * ```ts
1028
+ * ctx.problem({
1029
+ * type: 'https://api.example.com/problems/out-of-credit',
1030
+ * status: 403,
1031
+ * detail: 'Your balance is 30, but that costs 50.',
1032
+ * balance: 30, // extension per §3.2
1033
+ * })
1034
+ *
1035
+ * ctx.problem.notFound({ detail: 'User abc not found' })
1036
+ * ctx.problem.validation(zodResult.error.issues)
1037
+ * ```
1038
+ */
1039
+ interface ProblemSender {
1040
+ (input: ProblemDetails): RuntimeResponse;
1041
+ /** 400 Bad Request — RFC 9457. */
1042
+ badRequest(input?: ProblemInput): RuntimeResponse;
1043
+ /** 401 Unauthorized — RFC 9457. */
1044
+ unauthorized(input?: ProblemInput): RuntimeResponse;
1045
+ /** 403 Forbidden — RFC 9457. */
1046
+ forbidden(input?: ProblemInput): RuntimeResponse;
1047
+ /** 404 Not Found — RFC 9457. */
1048
+ notFound(input?: ProblemInput): RuntimeResponse;
1049
+ /** 409 Conflict — RFC 9457. */
1050
+ conflict(input?: ProblemInput): RuntimeResponse;
1051
+ /** 422 Unprocessable Entity — RFC 9457. */
1052
+ unprocessable(input?: ProblemInput): RuntimeResponse;
1053
+ /** 429 Too Many Requests — RFC 9457. */
1054
+ tooManyRequests(input?: ProblemInput): RuntimeResponse;
1055
+ /** 500 Internal Server Error — RFC 9457. */
1056
+ internal(input?: ProblemInput): RuntimeResponse;
1057
+ /**
1058
+ * 422 with Zod issues serialized into the `errors` extension per
1059
+ * RFC 9457 §3.2's array convention. Pass `error.issues` from a Zod
1060
+ * `safeParse` failure or `error.issues` from a thrown ZodError.
1061
+ */
1062
+ validation(issues: any[], input?: ProblemInput): RuntimeResponse;
1063
+ }
1064
+ /**
1065
+ * Recursively marks every property of `T` as `readonly`. Preserves
1066
+ * `Function`, `Date`, and `RegExp` unchanged, and converts `Map` / `Set`
1067
+ * to `ReadonlyMap` / `ReadonlySet` so their mutating methods (`set`,
1068
+ * `delete`, `add`, `clear`) are removed from the public surface.
1069
+ * Tuples keep their positional element types — only their per-element
1070
+ * mutability is locked.
1071
+ *
1072
+ * Exposed as a utility for adopters who want to opt into compile-time
1073
+ * sealing of their own shapes. **No longer applied to
1074
+ * `RequestContext.{body,params,query,headers,file,files}`** — that
1075
+ * broke TS narrowing / discriminated-union drilldowns on typed request
1076
+ * payloads. Runtime read-only enforcement now lives in
1077
+ * {@link makeReadOnlyProxy} (dev-only Proxy that warns on writes,
1078
+ * no-op in production).
1079
+ *
1080
+ * Type-only. No runtime cost. `DeepReadonly<any>` is `any` (TS
1081
+ * distributes conditional types over `any`).
1082
+ */
1083
+ 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;
1084
+ /**
1085
+ * The shape of a single route entry in `KickRoutes`. Generated by
1086
+ * `kick typegen` and consumed via the `Ctx<T>` helper. Each field is
1087
+ * `unknown` by default and is filled in as the typegen learns more
1088
+ * about the route (URL params from the path, body/query from validation
1089
+ * schemas, etc.).
1090
+ */
1091
+ interface RouteShape {
1092
+ params?: unknown;
1093
+ body?: unknown;
1094
+ query?: unknown;
1095
+ response?: unknown;
1096
+ /**
1097
+ * Union of context keys `kick typegen` proved are populated for this
1098
+ * route — the keys of every context contributor applied at method or
1099
+ * class level. Drives {@link RequestContext.require} narrowing, so
1100
+ * calling `ctx.require()` for a key this route doesn't carry is a
1101
+ * compile error instead of a request-time throw.
1102
+ *
1103
+ * `string` (the default) means "not proven", not "no keys". Typegen
1104
+ * emits `string` whenever it cannot see the full picture — a
1105
+ * contributor registered at module / adapter / bootstrap level, or an
1106
+ * unrecognised decorator that might bundle contributors of its own.
1107
+ * Narrowing an unprovable route would produce compile errors for keys
1108
+ * that really are present.
1109
+ */
1110
+ contextKeys?: string;
1111
+ }
1112
+ /**
1113
+ * Unified request/response abstraction passed to every controller method.
1114
+ * Shields handlers from raw Express objects and provides convenience methods.
1115
+ *
1116
+ * Implements {@link ExecutionContext} so the transport-agnostic Context
1117
+ * Contributor pipeline (#107) can run against this concrete HTTP context
1118
+ * the same way it will run against future WS / queue / cron contexts.
1119
+ */
1120
+ declare class RequestContext<TBody = any, TParams = any, TQuery = any,
1121
+ /**
1122
+ * Context keys proven present for this route. Defaults to
1123
+ * {@link ContextMetaKey} — every key the project has registered — which
1124
+ * collapses to `string` when neither registry has been augmented, so a
1125
+ * handler typed as plain `RequestContext` keeps today's behaviour. That
1126
+ * default is also the deliberate escape hatch when typegen's view of a
1127
+ * route is incomplete.
1128
+ */
1129
+ TKeys extends ContextMetaKey = ContextMetaKey> implements ExecutionContext<TKeys> {
1130
+ readonly req: ActiveRuntime['request'];
1131
+ readonly res: ActiveRuntime['response'];
1132
+ readonly next: NextFunction;
1133
+ /**
1134
+ * Engine-agnostic response driver the response helpers write through. Under
1135
+ * the Express runtime it IS `res` (Express's Response satisfies
1136
+ * {@link RuntimeResponse} structurally); other runtimes pass a thin wrapper
1137
+ * over their native reply as the optional fourth argument.
1138
+ */
1139
+ private readonly _response;
1140
+ /**
1141
+ * The route this request matched: its method, path, controller, handler name
1142
+ * and resolved {@link MatchedRoute.flags}.
1143
+ *
1144
+ * Available to anything running inside the matched route — route middleware,
1145
+ * contributors, guards, the handler. Global middleware runs before route
1146
+ * matching, so it sees `undefined` there.
1147
+ *
1148
+ * ```ts
1149
+ * if (ctx.route?.flags.has('auth.public')) return next()
1150
+ * ```
1151
+ */
1152
+ get route(): MatchedRoute | undefined;
1153
+ constructor(req: ActiveRuntime['request'], res: ActiveRuntime['response'], next: NextFunction, responseDriver?: RuntimeResponse);
1154
+ /**
1155
+ * Memo of the most recent {@link qs} call this request. The query
1156
+ * object is immutable for a request's lifetime, so a repeat call with
1157
+ * the same `(fieldConfig, options)` references returns the cached
1158
+ * parse instead of re-walking the filter/sort strings.
1159
+ */
1160
+ private _qsMemo?;
1161
+ /** Memoized {@link problem} sender — built lazily on first access. */
1162
+ private _problem?;
1163
+ /**
1164
+ * Read-side accessor for the per-request metadata map.
1165
+ *
1166
+ * Returns the AsyncLocalStorage map (`requestStore.getStore().values`)
1167
+ * shared with the Context Contributor pipeline when an ALS frame is
1168
+ * active. Returns `null` outside any frame — read-side callers
1169
+ * (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as
1170
+ * "no metadata" and fall through to their `req.*` defaults. Reads
1171
+ * never throw because outside an ALS frame nobody could have written
1172
+ * via `ctx.set` anyway, so an empty answer is the truthful one.
1173
+ */
1174
+ private metadataReadOnly;
1175
+ /**
1176
+ * Write-side accessor for the per-request metadata map.
1177
+ *
1178
+ * Returns the same map as {@link metadataReadOnly} when an ALS frame
1179
+ * is active. Throws otherwise — writing to a fallback map outside
1180
+ * the ALS frame would silently lose data because other call sites
1181
+ * (downstream contributors, request-logger, etc.) read from the
1182
+ * canonical store and would never see it. Mount
1183
+ * `requestScopeMiddleware()` (Application does this for you in
1184
+ * `'auto'` mode) or wrap your test setup in
1185
+ * `requestStore.run({...}, () => …)` to fix.
1186
+ */
1187
+ private metadataForWrite;
1188
+ /**
1189
+ * Parsed request body. Wrapped in a dev-only Proxy that warns when
1190
+ * adopters try to mutate Zod-validated payloads in place — compute
1191
+ * new values and stash them via `ctx.set('key', value)` or a Context
1192
+ * Contributor instead. Reach for `ctx.req.body` if you genuinely
1193
+ * need the raw, mutable Express handle (rare).
1194
+ *
1195
+ * In production the Proxy is bypassed and `this.req.body` is
1196
+ * returned as-is — no runtime cost on the hot path.
1197
+ */
1198
+ get body(): TBody;
1199
+ /** Path parameters parsed from the route — read-only, see {@link body}. */
1200
+ get params(): TParams;
1201
+ /** Parsed query string — read-only, see {@link body}. */
1202
+ get query(): TQuery;
1203
+ /** Inbound HTTP headers — read-only, see {@link body}. */
1204
+ get headers(): Request$1['headers'];
1205
+ get requestId(): string | undefined;
1206
+ /**
1207
+ * `AbortSignal` that fires when the underlying HTTP request is
1208
+ * closed — either because the client disconnected before the
1209
+ * response was sent, or because Node's socket-close event ran
1210
+ * after a normal response. Multiple `RequestContext` wrappers for
1211
+ * the same request (router-builder constructs one per
1212
+ * middleware/contributor pipeline / main handler) share a single
1213
+ * `AbortController` cached on the underlying `req` object, so the
1214
+ * signal is stable across the request lifecycle.
1215
+ *
1216
+ * Thread it through anything that takes an `AbortSignal` so the
1217
+ * work cancels as soon as the client gives up — e.g. a kickjs-db
1218
+ * relational query:
1219
+ *
1220
+ * ```ts
1221
+ * @Get('/:id/full')
1222
+ * async show(ctx: RequestContext) {
1223
+ * const row = await this.repo.findFullById(ctx.params.id, ctx.signal)
1224
+ * if (!row) return ctx.notFound()
1225
+ * ctx.json(row)
1226
+ * }
1227
+ * ```
1228
+ *
1229
+ * The repo passes `signal` to `db.query.<table>.findUnique({ signal })`;
1230
+ * if the client disconnects mid-flight, the in-flight query rejects
1231
+ * with `RelationalQueryCancelledError` instead of consuming the
1232
+ * connection until completion.
1233
+ *
1234
+ * Implementation note — both `req.on('close')` and `res.on('close')`
1235
+ * are wired so the signal aborts regardless of whether the close
1236
+ * event lands on the request stream or the response stream first.
1237
+ * Subsequent fires are no-ops (`AbortController.abort()` is
1238
+ * idempotent).
1239
+ */
1240
+ get signal(): AbortSignal;
1241
+ /**
1242
+ * The request's session — set by the `session()` middleware, which must be
1243
+ * installed. Type your keys once by augmenting `SessionData`:
1244
+ *
1245
+ * ```ts
1246
+ * declare module '@forinda/kickjs' {
1247
+ * interface SessionData { userId?: string }
1248
+ * }
1249
+ * ```
1250
+ */
1251
+ get session(): Session;
1252
+ /**
1253
+ * The authenticated user set by AuthAdapter.
1254
+ * Reads from the per-request metadata store first (`ctx.set('user', ...)`),
1255
+ * then falls back to `req.user` (set directly by AuthAdapter middleware).
1256
+ *
1257
+ * Extend the `AuthUser` interface via module augmentation in your own auth
1258
+ * module — see the BYO Auth recipe in the docs
1259
+ * to get full typing.
1260
+ *
1261
+ * @example
1262
+ * ```ts
1263
+ * @Get('/me')
1264
+ * @Authenticated()
1265
+ * getProfile(ctx: RequestContext) {
1266
+ * const user = ctx.user
1267
+ * if (!user) return ctx.notFound()
1268
+ * return ctx.json({ user })
1269
+ * }
1270
+ * ```
1271
+ */
1272
+ get user(): MetaValue<'user', Record<string, any>> | undefined;
1273
+ /**
1274
+ * Tenant identifier for multi-tenant apps. Reads `user.tenantId` —
1275
+ * populated either by `AuthAdapter.testMode({ tenantId })`, a tenant
1276
+ * resolver middleware, or manually on the strategy's `mapPayload`.
1277
+ *
1278
+ * Augment `AuthUser` (or `ContextMeta['user']`) to widen the return
1279
+ * type if your user shape guarantees a non-`string | undefined` id.
1280
+ */
1281
+ get tenantId(): string | undefined;
1282
+ /**
1283
+ * Effective role list for the current user. Prefers `user.tenantRoles`
1284
+ * (populated by `AuthAdapterOptions.roleResolver` under a tenant) and
1285
+ * falls back to `user.roles`. Returns an empty array when the user is
1286
+ * absent or the shape has neither field.
1287
+ */
1288
+ get roles(): string[];
1289
+ /**
1290
+ * Parse the request query string into structured filters, sort, pagination, and search.
1291
+ * Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
1292
+ *
1293
+ * Generic over the field config: when passed an inline literal (or
1294
+ * `as const`), `filters[].field` and `sort[].field` are narrowed to
1295
+ * the exact whitelisted field names. Pass nothing or a non-literal
1296
+ * config and you get the loose `string` fallback.
1297
+ *
1298
+ * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
1299
+ * @param options - Limits (`maxLimit`, `defaultLimit`, `maxSearchLength`) and an
1300
+ * `onReject` hook. By default a rejected/over-broad field is logged via
1301
+ * `console.warn` with the request id; pass an explicit `onReject` to override
1302
+ * (e.g. throw to return a 400), or `onReject: () => {}` to silence.
1303
+ *
1304
+ * @example
1305
+ * ```ts
1306
+ * @Get('/')
1307
+ * async list(ctx: RequestContext) {
1308
+ * const parsed = ctx.qs({
1309
+ * filterable: ['status', 'priority'],
1310
+ * sortable: ['createdAt', 'title'],
1311
+ * } as const)
1312
+ * parsed.filters[0].field // typed as 'status' | 'priority'
1313
+ * parsed.sort[0].field // typed as 'createdAt' | 'title'
1314
+ * }
1315
+ * ```
1316
+ */
1317
+ qs<TConfig extends QueryFieldConfig | undefined = undefined>(fieldConfig?: TConfig, options?: ParseQueryOptions): TypedParsedQuery<TConfig>;
1318
+ /**
1319
+ * Single uploaded file (requires `@FileUpload({ mode: 'single' })`).
1320
+ * Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.
1321
+ * File metadata is set by the upload middleware and shouldn't be
1322
+ * mutated downstream.
1323
+ */
1324
+ get file(): Express.Multer.File | undefined;
1325
+ /**
1326
+ * Array of uploaded files (requires `@FileUpload({ mode: 'array' })`).
1327
+ * The array (and each entry in dev) is wrapped in a read-only Proxy
1328
+ * that warns on `push`/`pop` and per-file mutation. Use
1329
+ * `ctx.req.files` if you genuinely need the mutable Express handle.
1330
+ */
1331
+ get files(): Express.Multer.File[] | undefined;
1332
+ /**
1333
+ * Read a value from the per-request metadata store.
1334
+ *
1335
+ * The key is constrained to {@link ContextMetaKey} — the keys registered in
1336
+ * `ContextMeta` / `ContextKeys` — so a typo is a compile error rather than a
1337
+ * permanent `undefined`. Projects that have augmented neither registry get
1338
+ * `string`, exactly as before.
1339
+ *
1340
+ * Constrained by `ContextMetaKey` and deliberately NOT by `TKeys`: "does this
1341
+ * key exist in the app" is a different question from "does this route carry
1342
+ * it", and narrowing by the latter would turn an incomplete typegen view into
1343
+ * false errors for keys written by middleware. Presence is `require`'s job;
1344
+ * this always returns `| undefined`.
1345
+ *
1346
+ * When `ContextMeta` has a matching key the return type is inferred
1347
+ * automatically. For ad-hoc keys, pass a generic: `ctx.get<MyType>('custom')`.
1348
+ */
1349
+ get<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined;
1350
+ /**
1351
+ * Read a value that a contributor is expected to have produced, and
1352
+ * throw {@link MissingContextValueError} when it hasn't.
1353
+ *
1354
+ * Use this instead of `ctx.get(key)!` anywhere the value is a
1355
+ * precondition rather than an optional extra — permissions, tenants,
1356
+ * the resolved subject of the route. The non-null assertion compiles
1357
+ * whether or not the producing contributor is actually applied to the
1358
+ * route, so a dropped `@LoadTenant` turns into `undefined` flowing
1359
+ * silently into an auth check. `require()` fails loudly at that point
1360
+ * instead, naming the key.
1361
+ *
1362
+ * ```ts
1363
+ * // before — compiles even if @OperatorPerm was never applied
1364
+ * const perm = ctx.get('operatorPerm')!
1365
+ *
1366
+ * // after — throws MissingContextValueError naming the key + route
1367
+ * const perm = ctx.require('operatorPerm')
1368
+ * ```
1369
+ *
1370
+ * When `TKeys` is narrowed — which it is for a handler typed as
1371
+ * `Ctx<KickRoutes…>`, from typegen's per-route `contextKeys` — asking
1372
+ * for a key the route doesn't carry is a compile error, so a dropped
1373
+ * decorator fails the build. `TKeys` stays `string` (no narrowing) for
1374
+ * a plain `RequestContext` and for any route typegen couldn't prove
1375
+ * complete; there this is a runtime guarantee only.
1376
+ * See `architecture.md` §20.14.
1377
+ *
1378
+ * `null` counts as present; only `undefined` (or a missing entry)
1379
+ * throws. A contributor that deliberately resolves to `null` is
1380
+ * expressing "looked, found nothing", which is a real value — which
1381
+ * is why the return type is `Exclude<…, undefined>` and NOT
1382
+ * `NonNullable<…>`. The latter would strip `null` from the type while
1383
+ * the runtime still hands it back, so a caller would be told a value
1384
+ * is non-null and then get `null`.
1385
+ */
1386
+ require<K extends TKeys>(key: K): Exclude<MetaValue<K>, undefined>;
1387
+ /**
1388
+ * Best-effort `"GET /path"` label for error messages. Runtime-agnostic:
1389
+ * express/fastify requests and web-standard `Request` all expose
1390
+ * `method` + `url`, but none of them are guaranteed here, so every
1391
+ * access is defensive and the whole thing is optional.
1392
+ */
1393
+ private routeLabel;
1394
+ /**
1395
+ * Write a value to the per-request metadata store. Throws when no
1396
+ * AsyncLocalStorage frame is active — see {@link metadataForWrite}
1397
+ * for why a silent fallback is the wrong default.
1398
+ */
1399
+ set<K extends ContextMetaKey>(key: K, value: MetaValue<K>): void;
1400
+ /**
1401
+ * Set a response header. Runtime-neutral — works on every engine and on
1402
+ * the web/edge entry. No-op guards are the runtime's job (headers set
1403
+ * after the response settles are ignored or throw per engine).
1404
+ */
1405
+ setHeader(name: string, value: string | number | readonly string[]): this;
1406
+ json(data: any, status?: number): RuntimeResponse;
1407
+ created(data: any): RuntimeResponse;
1408
+ private sendJson;
1409
+ noContent(): unknown;
1410
+ /**
1411
+ * The URL of a route, by name — `'Controller.method'` — with its `:params`
1412
+ * filled (encoded) and an optional query string. Names and params are typed
1413
+ * once `kick typegen` has run; an unknown name or a missing param throws.
1414
+ *
1415
+ * ```ts
1416
+ * @Post('/')
1417
+ * async create(ctx: RequestContext) {
1418
+ * const user = await this.users.create(ctx.body)
1419
+ * ctx.setHeader('Location', ctx.urlFor('UsersController.show', { id: user.id }))
1420
+ * ctx.created(user)
1421
+ * }
1422
+ * ```
1423
+ */
1424
+ urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
1425
+ /**
1426
+ * Answer a conditional request from the resource's validators, before doing
1427
+ * the expensive part. Sets `ETag` / `Last-Modified`, then — per RFC 9110 —
1428
+ * answers `304 Not Modified` when the client's copy is current, or `412`
1429
+ * when an `If-Match` / `If-Unmodified-Since` write is based on a stale one.
1430
+ * Returns `true` when it answered; respond as usual when it returns `false`.
1431
+ *
1432
+ * ```ts
1433
+ * @Get('/:id')
1434
+ * async show(ctx: RequestContext) {
1435
+ * const { version, updatedAt } = await posts.meta(ctx.params.id) // cheap
1436
+ * if (ctx.conditional({ etag: `v${version}`, lastModified: updatedAt })) return
1437
+ * ctx.json(await posts.full(ctx.params.id)) // only when it changed
1438
+ * }
1439
+ * ```
1440
+ */
1441
+ conditional(validators: Validators): boolean;
1442
+ /**
1443
+ * @deprecated Prefer {@link ProblemSender.notFound | ctx.problem.notFound()},
1444
+ * which emits an RFC 9457 — Problem Details response. This helper stays
1445
+ * for backward compatibility and will not be removed.
1446
+ */
1447
+ notFound(message?: string): RuntimeResponse;
1448
+ /**
1449
+ * @deprecated Prefer {@link ProblemSender.badRequest | ctx.problem.badRequest()},
1450
+ * which emits an RFC 9457 — Problem Details response. This helper stays
1451
+ * for backward compatibility and will not be removed.
1452
+ */
1453
+ badRequest(message: string): RuntimeResponse;
1454
+ /**
1455
+ * RFC 9457 — Problem Details for HTTP APIs response helper.
1456
+ * https://datatracker.ietf.org/doc/html/rfc9457
1457
+ *
1458
+ * `ctx.problem(...)` sends a canonical problem-detail response with
1459
+ * `Content-Type: application/problem+json`. The convenience methods
1460
+ * (`ctx.problem.notFound`, `.badRequest`, etc.) pre-fill `status` +
1461
+ * `title` for the common codes.
1462
+ *
1463
+ * `type` defaults to `about:blank` (§3.1.1); `title` defaults to the
1464
+ * IANA reason phrase for `status` (§3.1.4). Extension members per §3.2
1465
+ * pass through unchanged.
1466
+ *
1467
+ * @example
1468
+ * ```ts
1469
+ * ctx.problem({
1470
+ * type: 'https://api.example.com/problems/out-of-credit',
1471
+ * status: 403,
1472
+ * detail: 'Your balance is 30, but that costs 50.',
1473
+ * instance: `/account/${ctx.user.id}/messages/${ctx.params.id}`,
1474
+ * balance: 30,
1475
+ * })
1476
+ *
1477
+ * ctx.problem.notFound({ detail: 'User abc not found' })
1478
+ * ctx.problem.validation(zodResult.error.issues)
1479
+ * ```
1480
+ *
1481
+ * @see {@link ProblemException} for the exception-throwing equivalent
1482
+ * (use it from services where `ctx` isn't in scope).
1483
+ */
1484
+ get problem(): ProblemSender;
1485
+ private sendProblem;
1486
+ /**
1487
+ * Send an HTML response.
1488
+ *
1489
+ * Passes the full MIME type rather than the `'html'` shorthand. The
1490
+ * shorthand is an Express affordance — `res.type()` runs it through a MIME
1491
+ * lookup — but the Fastify and h3 drivers forward the string to their own
1492
+ * `type()` / `setHeader()` verbatim, so `'html'` reached the wire as a
1493
+ * malformed `Content-Type: html` on those engines. Fastify 5.10 started
1494
+ * normalising that invalid value to `text/plain`, which is what surfaced it.
1495
+ *
1496
+ * Express produces `text/html; charset=utf-8` for `.type('html')`, so
1497
+ * spelling it out here is byte-identical there and correct everywhere else.
1498
+ */
1499
+ /**
1500
+ * The client's IP address, or `undefined` when it cannot be determined.
1501
+ *
1502
+ * Prefers the value the runtime computed (Express derives `req.ip` from the
1503
+ * app's `trust proxy` setting; Fastify from `trustProxy`), because raw
1504
+ * forwarded headers are client-SPOOFABLE on deployments that do not
1505
+ * normalize them. The header fallbacks exist for runtimes with no `ip`
1506
+ * field at all — notably the web/edge entry.
1507
+ *
1508
+ * `ctx.req.ip` is Express-only, so reaching for it directly broke on
1509
+ * Fastify and h3.
1510
+ */
1511
+ get ip(): string | undefined;
1512
+ /**
1513
+ * Redirect the client. Works on every runtime.
1514
+ *
1515
+ * Every engine spells this differently — Express and Fastify have
1516
+ * `res.redirect()`, h3 has `sendRedirect(event, location, code)` — and none
1517
+ * of them is shared, so this writes the status and `Location` header through
1518
+ * the runtime response surface, which all four expose.
1519
+ *
1520
+ * The response carries no body. Express sends a short text line and h3 an
1521
+ * HTML meta-refresh fallback; a bare `Location` with a 3xx is sufficient per
1522
+ * RFC 9110, and interpolating the URL into an HTML body would add an
1523
+ * injection surface to a value this method already warns is dangerous.
1524
+ *
1525
+ * ::: warning
1526
+ * Never pass an unvalidated user-supplied `url`. An attacker-controlled
1527
+ * destination turns this into an open redirect, which is a common phishing
1528
+ * primitive. Allow-list the target or keep it relative.
1529
+ * :::
1530
+ */
1531
+ redirect(url: string, status?: number): unknown;
1532
+ html(content: string, status?: number): RuntimeResponse;
1533
+ /**
1534
+ * Send a body with its content type — XML, plain text, CSV, an image.
1535
+ * Runtime-neutral, like `json()` and `html()`. `type` defaults to
1536
+ * `text/plain; charset=utf-8`.
1537
+ *
1538
+ * @example
1539
+ * ```ts
1540
+ * ctx.send(sitemapXml, { type: 'application/xml' })
1541
+ * ctx.send(csv, { type: 'text/csv; charset=utf-8', status: 200 })
1542
+ * ```
1543
+ */
1544
+ send(body: string | Uint8Array, options?: {
1545
+ type?: string;
1546
+ status?: number;
1547
+ }): RuntimeResponse;
1548
+ /**
1549
+ * Send `buffer` as a file download named `filename`. The name is written
1550
+ * per RFC 6266 — an ASCII fallback plus `filename*` in UTF-8 — so a name
1551
+ * from an upload (quotes, line breaks, non-Latin text) can't break the header.
1552
+ */
1553
+ download(buffer: Buffer, filename: string, contentType?: string): RuntimeResponse;
1554
+ /**
1555
+ * Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
1556
+ * Requires a ViewAdapter to be configured in bootstrap().
1557
+ *
1558
+ * @param template - Template name (without extension, relative to viewsDir)
1559
+ * @param data - Data to pass to the template
1560
+ *
1561
+ * @example
1562
+ * ```ts
1563
+ * ctx.render('dashboard', { user, title: 'Dashboard' })
1564
+ * ctx.render('emails/welcome', { name: 'Alice' })
1565
+ * ```
1566
+ */
1567
+ render(template: string, data?: Record<string, any>): unknown;
1568
+ /**
1569
+ * Parse query params and return a standardized paginated response.
1570
+ * Calls `ctx.qs()` internally, then wraps your data with pagination meta.
1571
+ *
1572
+ * @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
1573
+ * @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
1574
+ *
1575
+ * @example
1576
+ * ```ts
1577
+ * @Get('/')
1578
+ * async list(ctx: RequestContext) {
1579
+ * return ctx.paginate(
1580
+ * async (parsed) => {
1581
+ * const data = await db.select().from(users)
1582
+ * .where(query.where).limit(parsed.pagination.limit)
1583
+ * .offset(parsed.pagination.offset).all()
1584
+ * const total = await db.select({ count: count() }).from(users).get()
1585
+ * return { data, total: total?.count ?? 0 }
1586
+ * },
1587
+ * { filterable: ['name', 'role'], sortable: ['createdAt'] },
1588
+ * )
1589
+ * }
1590
+ * ```
1591
+ */
1592
+ paginate<T, TConfig extends QueryFieldConfig | undefined = undefined>(fetcher: (parsed: TypedParsedQuery<TConfig>) => Promise<{
1593
+ data: T[];
1594
+ total: number;
1595
+ }>, fieldConfig?: TConfig): Promise<PaginatedResponse<T>>;
1596
+ /**
1597
+ * Start an SSE (Server-Sent Events) stream.
1598
+ * Sets the correct headers and returns helpers to send events.
1599
+ *
1600
+ * Pass a payload type to get typed sends — and `return sse` from the
1601
+ * handler so `kick typegen` carries the event type into
1602
+ * `KickRoutes.Api`, where `@forinda/kickjs-client`'s `api.stream()`
1603
+ * picks it up (the returned handler is ignored at runtime — the
1604
+ * response is already streaming).
1605
+ *
1606
+ * @example
1607
+ * ```ts
1608
+ * interface Tick { time: string }
1609
+ *
1610
+ * @Get('/events')
1611
+ * async stream(ctx: RequestContext) {
1612
+ * const sse = ctx.sse<Tick>()
1613
+ *
1614
+ * const interval = setInterval(() => {
1615
+ * sse.send({ time: new Date().toISOString() }, 'tick')
1616
+ * }, 1000)
1617
+ *
1618
+ * sse.onClose(() => clearInterval(interval))
1619
+ * return sse // typed as SseHandler<Tick> → response inference
1620
+ * }
1621
+ * ```
1622
+ */
1623
+ /**
1624
+ * Send a web-standard `Response` — status, headers (every `Set-Cookie`
1625
+ * kept) and body, streamed chunk by chunk — on any runtime. For handing off
1626
+ * to libraries that speak `Request`/`Response`, such as the MCP SDK's
1627
+ * web-standard transport.
1628
+ *
1629
+ * Resolves once the body is fully written. Stops reading the body when the
1630
+ * client disconnects.
1631
+ *
1632
+ * @example
1633
+ * ```ts
1634
+ * @Post('/mcp')
1635
+ * async mcp(ctx: RequestContext) {
1636
+ * await ctx.sendResponse(await transport.handleRequest(webRequest))
1637
+ * }
1638
+ * ```
1639
+ */
1640
+ sendResponse(response: Response): Promise<void>;
1641
+ /**
1642
+ * Keep `promise` running after the response is sent — an audit log, an
1643
+ * email, an analytics call. The Node server's `shutdown()` waits for it;
1644
+ * `createHandler()` and the web entry hand it to the platform's
1645
+ * `waitUntil` when you pass the platform context in. A rejection is
1646
+ * logged, never unhandled. Same as the standalone `waitUntil()` export.
1647
+ */
1648
+ waitUntil(promise: Promise<unknown>): void;
1649
+ sse<T = unknown>(): SseHandler<T>;
1650
+ }
1651
+ /**
1652
+ * The handle {@link RequestContext.sse} returns. The optional phantom
1653
+ * `__sse` property carries the event payload type STRUCTURALLY — never set
1654
+ * at runtime — so `kick typegen`'s response inference (handler `return sse`)
1655
+ * flows it into `KickRoutes.Api`, and `@forinda/kickjs-client` detects SSE
1656
+ * routes without importing any server types.
1657
+ */
1658
+ interface SseHandler<T = unknown> {
1659
+ /** Phantom event-payload type marker — never assigned at runtime. */
1660
+ readonly __sse?: T;
1661
+ /** Send an SSE event with optional event name and id. */
1662
+ send(data: T, event?: string, id?: string): void;
1663
+ /** Send a comment line (keeps the connection alive through proxies). */
1664
+ comment(text: string): void;
1665
+ /** Register a callback for client disconnect. */
1666
+ onClose(fn: () => void): void;
1667
+ /** End the SSE stream. */
1668
+ close(): void;
1669
+ }
1670
+ /**
1671
+ * Short alias for `RequestContext` parameterised by a route shape.
1672
+ *
1673
+ * Use with `kick typegen`'s generated `KickRoutes` namespace for
1674
+ * fully-typed `ctx.params`, `ctx.body`, and `ctx.query`. Metadata
1675
+ * typing (`ctx.get()`, `ctx.set()`, `ctx.user`) comes from
1676
+ * `ContextMeta` augmentation and works on all `RequestContext` instances.
1677
+ *
1678
+ * @example
1679
+ * ```ts
1680
+ * @Get('/:id')
1681
+ * getUser(ctx: Ctx<KickRoutes.UserController['getUser']>) {
1682
+ * ctx.params.id // typed from RouteShape
1683
+ * ctx.body // typed from RouteShape
1684
+ * ctx.user // typed from ContextMeta
1685
+ * ctx.get('tenant') // typed from ContextMeta
1686
+ * }
1687
+ * ```
1688
+ */
1689
+ type Ctx<TRoute extends RouteShape = RouteShape> = RequestContext<TRoute extends {
1690
+ body: infer B;
1691
+ } ? B : any, TRoute extends {
1692
+ params: infer P;
1693
+ } ? P : any, TRoute extends {
1694
+ query: infer Q;
1695
+ } ? Q : any, TRoute extends {
1696
+ contextKeys: infer K;
1697
+ } ? K extends ContextMetaKey ? K : ContextMetaKey : ContextMetaKey>;
1698
+ /**
1699
+ * Global ambient registry of typed routes, populated by `kick typegen`.
1700
+ *
1701
+ * Interfaces inside `KickRoutes` correspond to controller classes (each
1702
+ * property one route method, conforming to `RouteShape`) — plus the
1703
+ * reserved `KickRoutes.Api`: a flat `'METHOD /mounted/path'` map over the
1704
+ * same shapes, consumed by `@forinda/kickjs-client`. Don't name a
1705
+ * controller class `Api` — it would declaration-merge into that map.
1706
+ *
1707
+ * Empty by default — declarations come from `.kickjs/types/kick__routes.ts`
1708
+ * generated alongside the rest of the typegen output.
1709
+ */
1710
+ declare global {
1711
+ namespace KickRoutes {}
1712
+ }
1713
+ /** `attachment; filename="…"; filename*=UTF-8''…` for any file name (RFC 6266 / RFC 8187). */
1714
+ declare function contentDisposition(filename: string): string;
1715
+ //#endregion
1716
+ //#region src/http/runtime.d.ts
1717
+ /** HTTP verbs the router emits. Mirrors the decorator surface (@Get/@Post/...). */
1718
+ type RouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
1719
+ /**
1720
+ * A context-based handler: the runtime-neutral unit of the request pipeline.
1721
+ * Contributors, route middleware (via {@link MiddlewareHandler}), and the
1722
+ * terminal controller call all reduce to this shape. The runtime owns how a
1723
+ * `CtxHandler` is wrapped onto its engine (Express wraps it in `(req, res,
1724
+ * next)`; Fastify in its own handler).
1725
+ */
1726
+ type CtxHandler = (ctx: RequestContext) => unknown | Promise<unknown>;
1727
+ /**
1728
+ * Connect-style middleware — the portable middleware format. Built-in
1729
+ * middleware and adopter-supplied Express middleware are this shape. The
1730
+ * Express runtime hands them straight to `app.use`; later runtimes bridge
1731
+ * them (Fastify via `@fastify/middie`, h3 via its node adapter).
1732
+ *
1733
+ * Typed as the Express handler union for M1 (Express is the only runtime);
1734
+ * a future milestone narrows this to bare node `(req, res, next)` primitives
1735
+ * once the driver layer lands.
1736
+ */
1737
+ type ConnectMiddleware = RequestHandler | ErrorRequestHandler;
1738
+ /**
1739
+ * One materialized route, as plain data. Produced by {@link buildRouteTable}
1740
+ * from decorator metadata; consumed by {@link HttpRuntime.mountRoutes}.
1741
+ *
1742
+ * The shape is deliberately richer than a flat `CtxHandler[]`: `middlewares`
1743
+ * keep the `(ctx, next)` signature (they may short-circuit or call `next(err)`),
1744
+ * `contributorRunner` is a closure over the pre-built pipeline + container (the
1745
+ * pipeline is built — and any cycle / missing-dep error thrown — at table-build
1746
+ * time, i.e. boot), and `validation` / `upload` stay as metadata the runtime
1747
+ * materializes its own way. Faithfully reproducing the legacy Express chain —
1748
+ * not collapsing it — is what keeps M1 behavior-neutral.
1749
+ */
1750
+ interface RouteEntry {
1751
+ method: RouteMethod;
1752
+ /** Path with `:param` segments — the portable subset all engines accept. */
1753
+ path: string;
1754
+ /** Class + method middleware, in execution order; each receives `(ctx, next)`. */
1755
+ middlewares: MiddlewareHandler[];
1756
+ /**
1757
+ * Runs the contributor pipeline against `ctx` (populates `ctx.set(...)`),
1758
+ * or `null` when no contributors apply. Closes over the built pipeline and
1759
+ * the DI container so it stays engine-neutral; the runtime advances the
1760
+ * chain (Express: call `next()`) once it resolves.
1761
+ */
1762
+ contributorRunner: CtxHandler | null;
1763
+ /**
1764
+ * Contributors registered with `beforeValidation: true`. Runtimes run this
1765
+ * right after publishing the matched route — before validation, upload and
1766
+ * middleware — so a rejection (401) lands before a malformed body's 422.
1767
+ * Absent or `null` when no contributor asks for it.
1768
+ */
1769
+ earlyContributorRunner?: CtxHandler | null;
1770
+ /** The app's `validationError` — what this route's validation failure throws. */
1771
+ validationError?: ValidationErrorFactory;
1772
+ /** The app's route names → paths, for `ctx.urlFor()`. */
1773
+ urls?: RouteUrls;
1774
+ /** Terminal handler: resolves the controller per-request and invokes it. */
1775
+ handler: CtxHandler;
1776
+ /** Introspection + runtime-materialized concerns (swagger/typegen read this). */
1777
+ meta: RouteMeta;
1778
+ }
1779
+ /** Per-route metadata: introspection refs plus runtime-materialized concerns. */
1780
+ /**
1781
+ * One context contributor on a route, as introspection sees it: the
1782
+ * contributors a request runs, in execution order. Built with the route.
1783
+ */
1784
+ interface RouteContributor {
1785
+ /** The key it sets with `ctx.set(...)`. */
1786
+ key: string;
1787
+ /** Where it was registered — `method` / `class` decorators, or a module, adapter or global list. */
1788
+ source: ContributorSource;
1789
+ /** The registering site, e.g. `UsersController.show#0(tenant)` or a module name. */
1790
+ label?: string;
1791
+ dependsOn: readonly string[];
1792
+ /** Runs before validation (`beforeValidation: true`). */
1793
+ beforeValidation: boolean;
1794
+ /** Lower-precedence registrations of the same key this one replaced. */
1795
+ overrides: ReadonlyArray<{
1796
+ source: ContributorSource;
1797
+ label?: string;
1798
+ }>;
1799
+ }
1800
+ interface RouteMeta {
1801
+ /**
1802
+ * Owning controller class — for DI resolution and adapter introspection.
1803
+ * Absent for ad-hoc routes registered through {@link AdapterHttp.route},
1804
+ * which have no controller class behind them.
1805
+ */
1806
+ controller?: Constructor;
1807
+ /** Handler method name on the controller, when there is one. */
1808
+ handlerName?: string;
1809
+ /** The route's context contributors, in execution order — for devtools / introspection. */
1810
+ contributors?: readonly RouteContributor[];
1811
+ /** Zod/JSON-schema validation config from the route decorator, if any. */
1812
+ validation?: RouteDefinition['validation'];
1813
+ /** `@FileUpload` config, if present — the runtime supplies the backend. */
1814
+ upload?: FileUploadConfig;
1815
+ /**
1816
+ * Route flags in force here, resolved at build time (method over class).
1817
+ * Enabled flags only: a flag declared `false` at a higher-precedence site is
1818
+ * absent rather than present-and-false, so `has()` is always the right
1819
+ * question. See `core/route-flag.ts`.
1820
+ */
1821
+ flags?: RouteFlags;
1822
+ /**
1823
+ * The full mounted pattern (`/api/v1/users/:id`) — set by the Application
1824
+ * for controller routes. `path` is relative to the module mount.
1825
+ */
1826
+ pattern?: string;
1827
+ }
1828
+ interface MatchedRoute {
1829
+ readonly method: RouteMethod;
1830
+ /** Path as declared on the handler, e.g. `/:id`. */
1831
+ readonly path: string;
1832
+ /**
1833
+ * The full route pattern including the mount prefix and version, e.g.
1834
+ * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls
1835
+ * back to `path` for routes registered without a mount.
1836
+ */
1837
+ readonly pattern: string;
1838
+ readonly controller?: Constructor;
1839
+ readonly handlerName?: string;
1840
+ /** Enabled flags only — see {@link RouteMeta.flags}. */
1841
+ readonly flags: RouteFlags;
1842
+ /** @internal The app's route names, for `ctx.urlFor()`. */
1843
+ readonly urls?: RouteUrls;
1844
+ }
1845
+ /** A controller's routes grouped under the module mount prefix. */
1846
+ type RouteTable = {
1847
+ mountPath: string;
1848
+ routes: RouteEntry[];
1849
+ }[];
1850
+ interface RuntimeResponse {
1851
+ status(code: number): RuntimeResponse;
1852
+ json(data: unknown): RuntimeResponse;
1853
+ send(data: unknown): RuntimeResponse;
1854
+ type(contentType: string): RuntimeResponse;
1855
+ setHeader(name: string, value: string | number | readonly string[]): unknown;
1856
+ render(view: string, data?: Record<string, unknown>): unknown;
1857
+ writeHead(statusCode: number, headers?: Record<string, string>): unknown;
1858
+ flushHeaders(): unknown;
1859
+ write(chunk: string | Buffer): boolean;
1860
+ end(data?: unknown): unknown;
1861
+ once(event: 'close' | 'drain', listener: () => void): unknown;
1862
+ readonly headersSent: boolean;
1863
+ }
1864
+ /**
1865
+ * Per-runtime type map: the engine-native request / response / app types an
1866
+ * `HttpRuntime` exposes through `ctx.req.raw` / `ctx.res.raw` / `AdapterContext.app`.
1867
+ */
1868
+ interface RuntimeTypeMap {
1869
+ request: unknown;
1870
+ response: unknown;
1871
+ app: unknown;
1872
+ }
1873
+ /** The Express runtime's native types — the default when nothing is augmented. */
1874
+ interface ExpressRuntimeTypes {
1875
+ request: Request$1;
1876
+ response: Response$1;
1877
+ app: Express$1;
1878
+ }
1879
+ /**
1880
+ * Augmentable runtime registry. Empty by default; the `kick/runtime` typegen
1881
+ * plugin emits a `{ runtime: <RuntimeTypeMap> }` augmentation from the configured
1882
+ * runtime, which flips the engine-native escape-hatch types — `AdapterContext.app`,
1883
+ * `getRuntimeApp()`, and (once the driver layer lands) `ctx.req.raw` / `ctx.res.raw`
1884
+ * — to that runtime. Mirrors `KickDbRegister` / `KickEnv`, so the type story is
1885
+ * uniform with `kick/db` and env typing.
1886
+ *
1887
+ * @example
1888
+ * ```ts
1889
+ * // .kickjs/types/kick__runtime.d.ts — generated by typegen
1890
+ * declare module '@forinda/kickjs' {
1891
+ * interface KickRuntimeRegister {
1892
+ * runtime: import('@forinda/kickjs/fastify').FastifyRuntimeTypes
1893
+ * }
1894
+ * }
1895
+ * ```
1896
+ */
1897
+ interface KickRuntimeRegister {}
1898
+ /** The active runtime's type map — the augmented one, or Express by default. */
1899
+ type ActiveRuntime = KickRuntimeRegister extends {
1900
+ runtime: infer R extends RuntimeTypeMap;
1901
+ } ? R : ExpressRuntimeTypes;
1902
+ /** Options passed to {@link HttpRuntime.createApp}. */
1903
+ interface RuntimeAppOptions {
1904
+ /**
1905
+ * Express `trust proxy` setting (and the equivalent on other engines). The
1906
+ * function form is Express-specific; other runtimes interpret the simpler
1907
+ * shapes (or normalize X-Forwarded-For themselves — see spec §10 Q1).
1908
+ */
1909
+ trustProxy?: boolean | string | number | string[] | ((ip: string, hopIndex: number) => boolean);
1910
+ /**
1911
+ * When the app is mounted inside another handler (`kick dev`'s Vite server,
1912
+ * `app.handle(req, res, next)` in a host server), hand requests no route
1913
+ * matched back to it — `true`, the default — or answer them here with the
1914
+ * app's not-found handling — `false`. Express always answers.
1915
+ */
1916
+ notFoundFallthrough?: boolean;
1917
+ /** Largest request body the engine parses, in bytes — `jsonLimit`, resolved. */
1918
+ bodyLimit?: number;
1919
+ }
1920
+ /** Where a connect middleware sits and what it scopes to. */
1921
+ interface UseConnectOptions {
1922
+ path?: string | RegExp | ReadonlyArray<string | RegExp>;
1923
+ }
1924
+ /**
1925
+ * Optional engine capabilities. Absence means the corresponding `ctx` feature
1926
+ * raises a clear error on that runtime rather than failing obscurely.
1927
+ */
1928
+ interface RuntimeCapabilities {
1929
+ /** View-engine rendering (`ctx.render`). Express: true; Fastify/h3: false initially. */
1930
+ render: boolean;
1931
+ /** File uploads (`ctx.file` / `@FileUpload`). All engines, different backends. */
1932
+ uploads: boolean;
1933
+ /** Connect-style middleware. Express/Fastify(middie): true; h3: best-effort. */
1934
+ connectMiddleware: boolean;
1935
+ /**
1936
+ * The engine parses request bodies itself (Fastify, h3). When true, the
1937
+ * Application skips its default `express.json()` so the body stream isn't
1938
+ * consumed twice (which would deadlock the engine's own parser). Express:
1939
+ * false — it relies on the `express.json()` connect middleware.
1940
+ */
1941
+ nativeBodyParsing: boolean;
1942
+ /**
1943
+ * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2
1944
+ * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:
1945
+ * true. Express: false — it does not run on that layer. Absent = false, so
1946
+ * custom runtimes opt in explicitly.
1947
+ */
1948
+ http2?: boolean;
1949
+ }
1950
+ /**
1951
+ * The engine driver. KickJS owns decorators → {@link RouteTable}, the
1952
+ * contributor pipeline, the `RequestContext` surface, and error mapping. The
1953
+ * runtime owns app/server creation, route materialization, connect-middleware
1954
+ * registration, static serving, and the terminal not-found / error handlers.
1955
+ *
1956
+ * `expressRuntime()` is the default and the M1 reference implementation.
1957
+ */
1958
+ interface HttpRuntime<TApp = unknown> {
1959
+ readonly name: 'express' | 'fastify' | 'h3' | (string & {});
1960
+ /** Create the engine app. Called once per Application (and per HMR rebuild). */
1961
+ createApp(options?: RuntimeAppOptions): TApp;
1962
+ /**
1963
+ * Node-compatible request listener — the transport contract.
1964
+ * `http.createServer(handler)` in prod, Vite post-middleware in dev. MUST
1965
+ * invoke `next` (when given) instead of 404-ing if no route matched — the
1966
+ * Vite dev chain depends on fall-through.
1967
+ */
1968
+ nodeHandler(app: TApp): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void;
1969
+ /** Materialize the framework-built route table onto the engine. */
1970
+ mountRoutes(app: TApp, table: RouteTable): void;
1971
+ /** Register a connect-style middleware (built-ins + adopter middleware). */
1972
+ useConnect(app: TApp, mw: ConnectMiddleware, opts?: UseConnectOptions): void;
1973
+ /** Serve a static directory (swagger-ui assets, devtools SPA). */
1974
+ serveStatic(app: TApp, prefix: string, dir: string): void;
1975
+ /** Terminal not-found handler. */
1976
+ setNotFound(app: TApp, mw: ConnectMiddleware): void;
1977
+ /** Terminal error handler. */
1978
+ setErrorHandler(app: TApp, mw: ConnectMiddleware): void;
1979
+ /** Release the engine app on shutdown (Fastify runs its `onClose` hooks). */
1980
+ close?(app: TApp): void | Promise<void>;
1981
+ readonly capabilities: RuntimeCapabilities;
1982
+ }
1983
+ /**
1984
+ * The supported surface adapters use to add HTTP routes, mounts, static dirs,
1985
+ * and middleware — engine-agnostic, in place of reaching for the raw Express
1986
+ * `app` (spec §4.4). Exposed as {@link AdapterContext.http}. Built by the
1987
+ * Application over the active {@link HttpRuntime}, so an adapter written against
1988
+ * this works under any runtime; the raw `app` escape hatch stays available for
1989
+ * the rare engine-specific need.
1990
+ */
1991
+ interface AdapterHttp {
1992
+ /** Register a single context-handler route (e.g. a docs or transport endpoint). */
1993
+ route(method: RouteMethod, path: string, handler: CtxHandler): void;
1994
+ /** Mount a pre-built route table under a path prefix. */
1995
+ mount(prefix: string, routes: RouteEntry[]): void;
1996
+ /** Serve a static directory under a path prefix. */
1997
+ serveStatic(prefix: string, dir: string): void;
1998
+ /** Register a connect-style middleware (optionally path-scoped). */
1999
+ use(mw: ConnectMiddleware, opts?: UseConnectOptions): void;
2000
+ }
2001
+ //#endregion
2002
+ //#region src/core/adapter.d.ts
2003
+ /**
2004
+ * Where in the middleware pipeline an adapter's middleware should be inserted.
2005
+ *
2006
+ * - `beforeGlobal` — runs **before** any user-defined global middleware.
2007
+ * Suitable for transport-level concerns (request tagging, low-level
2008
+ * request rewriting). Fires on every request.
2009
+ * - `afterGlobal` — runs **after** global middleware, **before** module
2010
+ * routes are matched. Default for most adapter middleware (auth pre-checks,
2011
+ * tenant resolution, body shaping). Fires on every request.
2012
+ * - `beforeRoutes` — runs just before module routes are mounted. Functionally
2013
+ * equivalent to `afterGlobal` for most cases; the explicit phase exists so
2014
+ * adapters that *must* sit at the very end of the pre-route stack can
2015
+ * declare intent. Fires on every request.
2016
+ * - `afterRoutes` — sits **after** module routes but **before** error
2017
+ * handlers. **Fires only on fall-through** — when no route matched (404
2018
+ * path) or a route handler called `next()` without ending the response.
2019
+ * Controllers that respond with `ctx.json(...)` end the chain and skip
2020
+ * this phase, so it is *not* a "post-response" hook. For per-response
2021
+ * work (logging, metrics) use `res.on('finish', ...)` from inside an
2022
+ * earlier-phase middleware instead.
2023
+ */
2024
+ type MiddlewarePhase = 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes';
2025
+ /**
2026
+ * Path scope for an {@link AdapterMiddleware} entry. Mirrors what
2027
+ * Express's `app.use(path, handler)` accepts so adapters get the full
2028
+ * range without learning a new mini-language:
2029
+ *
2030
+ * - A `string` prefix — `'/api'` matches `/api`, `/api/v1`, `/api/v1/x`.
2031
+ * - A `RegExp` — `/^\/api\/v\d+/` matches `/api/v1`, `/api/v42`.
2032
+ * - An array of either — `['/api', '/admin']` matches either prefix;
2033
+ * `['/api', /^\/internal\//]` mixes shapes.
2034
+ *
2035
+ * Omit to apply the middleware unconditionally (Express `app.use(handler)`).
2036
+ */
2037
+ type MiddlewarePath = string | RegExp | ReadonlyArray<string | RegExp>;
2038
+ /** A middleware entry contributed by an adapter */
2039
+ interface AdapterMiddleware {
2040
+ /**
2041
+ * Express handler: either a `RequestHandler` (`(req, res, next) => …`)
2042
+ * or an `ErrorRequestHandler` (`(err, req, res, next) => …`).
2043
+ * Express dispatches based on arity, so the same field accepts both
2044
+ * without a discriminant.
2045
+ */
2046
+ handler: RequestHandler | ErrorRequestHandler;
2047
+ /** Which phase to insert into (default: 'afterGlobal') */
2048
+ phase?: MiddlewarePhase;
2049
+ /**
2050
+ * Optional path scope. See {@link MiddlewarePath} for the accepted
2051
+ * shapes (string prefix, RegExp, or an array mixing both). Omit to
2052
+ * apply the middleware to every request that reaches this phase.
2053
+ */
2054
+ path?: MiddlewarePath;
2055
+ }
2056
+ /**
2057
+ * Context passed to adapter lifecycle hooks.
2058
+ * Populated by the Application — provides the engine-agnostic HTTP surface,
2059
+ * the engine-native app instance, the DI container, the http.Server, and
2060
+ * environment info without requiring external type imports.
2061
+ *
2062
+ * Prefer `http` over `app`: `http` is the same on every runtime, while `app`
2063
+ * is whatever the active engine's instance happens to be (Express, Fastify,
2064
+ * h3), so an adapter that reaches for it only runs on that engine.
2065
+ *
2066
+ * @example
2067
+ * ```ts
2068
+ * beforeMount({ http, container }: AdapterContext) {
2069
+ * http.use(myConnectMiddleware())
2070
+ * http.route('GET', '/status', (ctx) => ctx.json({ ok: true }))
2071
+ * }
2072
+ * ```
2073
+ */
2074
+ /** The Node server behind the app — see `ApplicationOptions.server`. */
2075
+ type KickServer = http.Server | https.Server | http2.Http2SecureServer;
2076
+ interface AdapterContext {
2077
+ /**
2078
+ * Engine-agnostic HTTP surface — the supported way to add routes, mounts,
2079
+ * static dirs, and middleware (spec §4.4). Prefer this over {@link app}:
2080
+ * an adapter written against `http` works under any runtime.
2081
+ */
2082
+ http: AdapterHttp;
2083
+ /**
2084
+ * Engine-native application instance — Express under the default runtime,
2085
+ * typed from the active runtime via {@link ActiveRuntime} (spec §4.3b).
2086
+ * Escape hatch for genuinely engine-specific needs; for everything else use
2087
+ * {@link http}.
2088
+ */
2089
+ app: ActiveRuntime['app'];
2090
+ /**
2091
+ * Run a web `Request` through this app's pipeline and return the
2092
+ * `Response` — routing, middleware, validation, contributors, errors —
2093
+ * without a listening server (`createHandler()`, tests), so an adapter that
2094
+ * calls the app's own routes (MCP and AI tool dispatch) never needs the
2095
+ * server address. See `Application.fetch`.
2096
+ *
2097
+ * The full pipeline exists once setup completes: from `beforeStart` on,
2098
+ * and in request handlers after that. In `beforeMount` module routes and
2099
+ * error handlers are not mounted yet.
2100
+ */
2101
+ fetch(request: Request): Promise<Response>;
2102
+ /** DI container */
2103
+ container: Container$1;
2104
+ /**
2105
+ * The Node server the app listens on — only available in afterStart. An
2106
+ * `http.Server` by default; an `https.Server` or `Http2SecureServer` when
2107
+ * `bootstrap({ server })` sets `tls` / `http2`. All three emit `upgrade`
2108
+ * for HTTP/1.1 clients, which is what WebSocket libraries attach to.
2109
+ */
2110
+ server?: KickServer;
2111
+ /** Current NODE_ENV value (default: 'development') */
2112
+ env: string;
2113
+ /** true when NODE_ENV === 'production' */
2114
+ isProduction: boolean;
2115
+ }
2116
+ /**
2117
+ * Adapters plug into the Application lifecycle.
2118
+ * Implement this to add WebSocket, database, rate limiting, docs, etc.
2119
+ *
2120
+ * All hooks receive an `AdapterContext` populated by the framework.
2121
+ * No external type imports needed — the context is fully typed from KickJS internals.
2122
+ *
2123
+ * @example
2124
+ * ```ts
2125
+ * import type { AppAdapter, AdapterContext } from '@forinda/kickjs/adapter'
2126
+ *
2127
+ * class SentryAdapter implements AppAdapter {
2128
+ * name = 'SentryAdapter'
2129
+ *
2130
+ * beforeMount({ http, container }: AdapterContext) {
2131
+ * // `http.use` takes any connect-style middleware and mounts it on
2132
+ * // whichever engine is active. Reach for `app` only when the thing you
2133
+ * // are wiring is engine-specific — and accept the engine lock-in.
2134
+ * http.use(Sentry.expressRequestHandler())
2135
+ * }
2136
+ *
2137
+ * afterStart({ server }: AdapterContext) {
2138
+ * // server is the http.Server — available after listen()
2139
+ * }
2140
+ *
2141
+ * async shutdown() {
2142
+ * await Sentry.close(2000)
2143
+ * }
2144
+ * }
2145
+ * ```
2146
+ */
2147
+ interface AppAdapter {
2148
+ /**
2149
+ * Human-readable name for logging and `dependsOn` resolution.
2150
+ * Required when the adapter (or any other in the same set) declares
2151
+ * `dependsOn` — sort errors will reference adapters by name.
2152
+ */
2153
+ name?: string;
2154
+ /**
2155
+ * Other adapter names that must mount before this one. The framework
2156
+ * topologically sorts adapters at boot — cycles or unknown names throw
2157
+ * via `MountCycleError` / `MissingMountDepError` so bad configurations
2158
+ * fail boot rather than corrupt live traffic.
2159
+ *
2160
+ * Common pattern: `TenantAdapter` populates `req.tenant` and
2161
+ * `AuthAdapter` reads it for tenant-scoped RBAC, so AuthAdapter
2162
+ * declares `dependsOn = ['TenantAdapter']`. Adapters without
2163
+ * `dependsOn` retain their declaration order.
2164
+ *
2165
+ * @example
2166
+ * ```ts
2167
+ * class AuthAdapter implements AppAdapter {
2168
+ * name = 'AuthAdapter'
2169
+ * dependsOn = ['TenantAdapter']
2170
+ * }
2171
+ * ```
2172
+ */
2173
+ dependsOn?: readonly KickJsPluginName[];
2174
+ /**
2175
+ * Whether this adapter runs at all, decided once at startup. Return `true`
2176
+ * to keep it, or `false` / a reason to leave it out — the outcome is in
2177
+ * `app.getConditionReport()` and DevTools' `/_debug/conditions`. An adapter
2178
+ * that `dependsOn` one left out is left out too.
2179
+ *
2180
+ * ```ts
2181
+ * const cache: AppAdapter = { name: 'Cache', when: onEnv('REDIS_URL'), … }
2182
+ * defineAdapter({ name: 'Queue', build: () => ({ when: allOf(onEnv('QUEUE'), onPackage('bullmq')), … }) })
2183
+ * ```
2184
+ */
2185
+ when?: AdapterCondition;
2186
+ /**
2187
+ * Explain one of this adapter's startup failures. When a setup hook throws,
2188
+ * the app asks the adapter first, then its own analyzers (connection
2189
+ * refused, unknown host, bad credentials, …), and logs the advice before
2190
+ * the error itself. Return `undefined` for errors you don't recognise.
2191
+ *
2192
+ * ```ts
2193
+ * analyzeFailure: (err) =>
2194
+ * err instanceof MissingExtensionError
2195
+ * ? { summary: 'pgvector is not installed', fix: 'CREATE EXTENSION vector;' }
2196
+ * : undefined
2197
+ * ```
2198
+ */
2199
+ analyzeFailure?(err: unknown): FailureAdvice | undefined;
2200
+ /**
2201
+ * Return middleware entries to be inserted into the pipeline.
2202
+ * The `phase` controls ordering relative to global middleware and routes.
2203
+ */
2204
+ middleware?(): AdapterMiddleware[];
2205
+ /**
2206
+ * Return Context Contributors (#107) that apply to every route in the
2207
+ * application. Adapter-level contributors merge into the per-route
2208
+ * pipeline at the `'adapter'` precedence level — they win over global
2209
+ * contributors but lose to module, class, and method decorators.
2210
+ *
2211
+ * Useful for cross-cutting concerns: an auth adapter contributing
2212
+ * `user`, a multi-tenant adapter contributing `tenant`, etc. Optional.
2213
+ */
2214
+ contributors?(): ContributorRegistrations;
2215
+ /**
2216
+ * Settings sections this adapter needs — validated at startup and bound
2217
+ * before any hook runs, only when the adapter is enabled (see `when`).
2218
+ */
2219
+ settings?(): readonly SettingsDeclaration[];
2220
+ /**
2221
+ * Called before global middleware — register early routes (docs UI, health).
2222
+ * May return a Promise — async rejections are caught and logged.
2223
+ */
2224
+ beforeMount?(ctx: AdapterContext): void | Promise<void>;
2225
+ /**
2226
+ * Called for each module route that gets mounted.
2227
+ * Use this to collect route metadata (e.g. for OpenAPI spec generation).
2228
+ */
2229
+ onRouteMount?(controllerClass: Constructor, mountPath: string): void;
2230
+ /**
2231
+ * Called after modules are registered and the DI container is bootstrapped,
2232
+ * before the HTTP server starts listening. **This is the correct hook for
2233
+ * adapters that register DI bindings, resolve services, or otherwise prepare
2234
+ * container-side state** (e.g. `container.registerInstance(MAILER, ...)`).
2235
+ *
2236
+ * `beforeStart` runs inside `app.setup()`, which means it also fires under
2237
+ * `createTestApp` — adapters using this hook work in unit tests without
2238
+ * needing a live HTTP server. See {@link afterStart} for the contrast.
2239
+ *
2240
+ * May return a Promise — async rejections are caught and logged.
2241
+ */
2242
+ beforeStart?(ctx: AdapterContext): void | Promise<void>;
2243
+ /**
2244
+ * Called after the HTTP server is listening — `ctx.server` is the live
2245
+ * `http.Server`. **Use this hook only for work that genuinely needs a
2246
+ * listening server**: attaching Socket.IO / WS upgrades, reading the bound
2247
+ * port via `server.address()`, dispatching to the local server over HTTP,
2248
+ * etc.
2249
+ *
2250
+ * `afterStart` does NOT fire under `createTestApp`, since tests call
2251
+ * `app.setup()` and never `app.start()`. If your adapter only registers DI
2252
+ * bindings or resolves services, use {@link beforeStart} — that hook runs
2253
+ * in both production (`start()`) and tests (`setup()`).
2254
+ *
2255
+ * May return a Promise — async rejections are caught and logged.
2256
+ */
2257
+ afterStart?(ctx: AdapterContext): void | Promise<void>;
2258
+ /**
2259
+ * Called by the /health/ready endpoint. Return the health status of your adapter's
2260
+ * backing service (database, Redis, queue, etc.).
2261
+ */
2262
+ onHealthCheck?(): Promise<{
2263
+ name: string;
2264
+ status: 'up' | 'down';
2265
+ }>;
2266
+ /**
2267
+ * Observe every error the app reports — request errors (any status; filter
2268
+ * on `info.status`), uncaught exceptions, unhandled rejections, failed
2269
+ * `waitUntil` work, failed queue jobs, and anything passed to
2270
+ * `reportError()`. Observe-only: the response is not yours to change, and a
2271
+ * throw here is logged and skipped. The place to wire Sentry & co.
2272
+ */
2273
+ onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
2274
+ /**
2275
+ * Observe every finished response — method, path, the matched route
2276
+ * pattern, status, duration. Only timed while something listens.
2277
+ */
2278
+ onResponse?(info: ResponseInfo): void | Promise<void>;
2279
+ /**
2280
+ * Called on shutdown — release what this adapter owns.
2281
+ *
2282
+ * Runs on a real shutdown AND on **every HMR reload**, so treat it as a hot
2283
+ * path in dev, not an exit-only courtesy.
2284
+ *
2285
+ * Close only what you own. The `server` from {@link AdapterContext} is
2286
+ * SHARED — in dev it is Vite's listener — and closing it takes the dev
2287
+ * server down with no way to rebind. `io.close()` on a socket.io server
2288
+ * does exactly that; detach with `io.engine.close()` instead. The framework
2289
+ * closes the shared server itself on a real shutdown.
2290
+ *
2291
+ * Time-boxed: `shutdownTimeout` on a real shutdown, `min(shutdownTimeout,
2292
+ * 5s)` on a reload. Overruns are logged by name and skipped.
2293
+ */
2294
+ shutdown?(): MaybePromise;
2295
+ /**
2296
+ * Optional DevTools introspection hook (architecture.md §23). Returns
2297
+ * a snapshot describing this adapter's current state, metrics, and DI
2298
+ * tokens. DevTools awaits the result, so async work is fine — but keep
2299
+ * the implementation cheap (counters + flags, no DB round trips) since
2300
+ * the topology endpoint polls on a short interval.
2301
+ *
2302
+ * The return type lives in `@forinda/kickjs` itself ({@link IntrospectionSnapshot})
2303
+ * so adopters can author `introspect()` without importing the kit just
2304
+ * to satisfy the contract. The kit's own `IntrospectionSnapshot` type
2305
+ * stays structurally identical; either import works.
2306
+ */
2307
+ introspect?(): IntrospectionSnapshot | Promise<IntrospectionSnapshot>;
2308
+ /**
2309
+ * Optional DevTools tabs this adapter contributes (architecture.md §23).
2310
+ * Returns an array of `DevtoolsTabDescriptor` shapes — typically one
2311
+ * entry per adapter-owned panel (iframe / launch / html view).
2312
+ *
2313
+ * Same untyped-at-this-layer convention as {@link introspect}: adapter
2314
+ * authors import `defineDevtoolsTab` (or the bare type) from
2315
+ * `@forinda/kickjs-devtools-kit` so `@forinda/kickjs` doesn't take on
2316
+ * a runtime dep on the kit.
2317
+ */
2318
+ devtoolsTabs?(): readonly unknown[];
2319
+ }
2320
+ /** Constructor type for AppAdapter classes */
2321
+ type AppAdapterClass = new () => AppAdapter;
2322
+ //#endregion
2323
+ export { getMetaMap as $, SseHandler as A, IntrospectionSnapshot as At, AdapterAsyncOptions as B, onEnv as Bt, RuntimeResponse as C, KickPlugin as Ct, DeepReadonly as D, KickJsPluginRegistry as Dt, Ctx as E, KickJsPluginName as Et, ROUTE_URLS as F, reportResponse as Ft, runContributors as G, DefineAdapterOptions as H, RouteName as I, FailureAdvice as It, ContributorSource as J, BuildPipelineOptions as K, UrlBuilder as L, AdapterCondition as Lt, ConditionalOutcome as M, ErrorSource as Mt, Validators as N, ResponseInfo as Nt, RequestContext as O, IntrospectFn as Ot, evaluatePreconditions as P, reportError as Pt, getClassMetaOrUndefined as Q, UrlForArgs as R, ConditionOutcome as Rt, RuntimeCapabilities as S, definePlugin as St, UseConnectOptions as T, MutableModuleRegistry as Tt, defineAdapter as U, AdapterFactory as V, onPackage as Vt, RunContributorsOptions as W, buildPipeline as X, SourcedRegistration as Y, getClassMeta as Z, RouteEntry as _, defineModule as _t, KickServer as a, pushMethodMeta as at, RouteTable as b, PluginAsyncOptions as bt, ActiveRuntime as c, setInMetaRecord as ct, CtxHandler as d, disposeAll as dt, getMetaRecord as et, ExpressRuntimeTypes as f, registerDisposable as ft, RouteContributor as g, ModuleFactory as gt, MatchedRoute as h, DefineModuleOptions as ht, AppAdapterClass as i, pushClassMeta as it, contentDisposition as j, ErrorInfo as jt, RouteShape as k, IntrospectionKind as kt, AdapterHttp as l, setMethodMeta as lt, KickRuntimeRegister as m, defineModules as mt, AdapterMiddleware as n, getMethodMetaOrUndefined as nt, MiddlewarePath as o, setClassMeta as ot, HttpRuntime as p, ModuleList as pt, ContributorPipeline as q, AppAdapter as r, hasClassMeta as rt, MiddlewarePhase as s, setInMetaMap as st, AdapterContext as t, getMethodMeta as tt, ConnectMiddleware as u, Disposable as ut, RouteMeta as v, BuildContext as vt, RuntimeTypeMap as w, ModuleRegistry as wt, RuntimeAppOptions as x, PluginFactory as xt, RouteMethod as y, DefinePluginOptions as yt, UrlQuery as z, allOf as zt };
2324
+ //# sourceMappingURL=adapter-6fjmVVc2.d.mts.map