@forinda/kickjs 10.2.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.
- package/dist/adapter-6fjmVVc2.d.mts +2324 -0
- package/dist/adapter-6fjmVVc2.d.mts.map +1 -0
- package/dist/{app-module-Ftz6m7SO.d.mts → app-module-Cuu-Ma_E.d.mts} +5 -4
- package/dist/app-module-Cuu-Ma_E.d.mts.map +1 -0
- package/dist/application-BuUWvaqp.d.mts +1985 -0
- package/dist/application-BuUWvaqp.d.mts.map +1 -0
- package/dist/{application-Ch5jT4fj.mjs → application-CYCvctQx.mjs} +3 -3
- package/dist/{application-Ch5jT4fj.mjs.map → application-CYCvctQx.mjs.map} +1 -1
- package/dist/bootstrap-CfaYHbmd.mjs +12 -0
- package/dist/{bootstrap-D56HIq1N.mjs.map → bootstrap-CfaYHbmd.mjs.map} +1 -1
- package/dist/{bounded-counters-B9dzk5o_.mjs → bounded-counters-BcA0f0bV.mjs} +2 -2
- package/dist/{bounded-counters-B9dzk5o_.mjs.map → bounded-counters-BcA0f0bV.mjs.map} +1 -1
- package/dist/{client-ip-lYnBU2PR.mjs → client-ip-BpauuVN_.mjs} +2 -2
- package/dist/{client-ip-lYnBU2PR.mjs.map → client-ip-BpauuVN_.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-BfImCyaG.mjs → config-DgMxtfcW.mjs} +3 -3
- package/dist/{config-BfImCyaG.mjs.map → config-DgMxtfcW.mjs.map} +1 -1
- package/dist/container-4iJdDkRH.d.mts +3 -0
- package/dist/{context-C6iKf9hN.mjs → context-DJvuLfrx.mjs} +3 -3
- package/dist/{context-C6iKf9hN.mjs.map → context-DJvuLfrx.mjs.map} +1 -1
- package/dist/{context-errors-6psUheqc.mjs → context-errors-BGIOYMV5.mjs} +2 -2
- package/dist/{context-errors-6psUheqc.mjs.map → context-errors-BGIOYMV5.mjs.map} +1 -1
- package/dist/{contributor-runner-Bn-ipSS5.mjs → contributor-runner-CJn1gZ8h.mjs} +3 -3
- package/dist/{contributor-runner-Bn-ipSS5.mjs.map → contributor-runner-CJn1gZ8h.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.d.mts +2 -2
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.d.mts +2 -2
- package/dist/core/interfaces.mjs +2 -2
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/core-YE-k8IrU.mjs +12 -0
- package/dist/{core-CFXpwc7m.mjs.map → core-YE-k8IrU.mjs.map} +1 -1
- package/dist/{csrf-C3RRSCMs.mjs → csrf-C6Em76kH.mjs} +3 -3
- package/dist/{csrf-C3RRSCMs.mjs.map → csrf-C6Em76kH.mjs.map} +1 -1
- package/dist/{csrf-Cy1meSpf.d.mts → csrf-ahBjt1ay.d.mts} +2 -2
- package/dist/{csrf-Cy1meSpf.d.mts.map → csrf-ahBjt1ay.d.mts.map} +1 -1
- package/dist/decorate-CaEYam5J.mjs +13 -0
- package/dist/{decorate-DkxaoRo5.mjs.map → decorate-CaEYam5J.mjs.map} +1 -1
- package/dist/{decorators-DaQUNXOn.d.mts → decorators-deGmthGc.d.mts} +3 -199
- package/dist/decorators-deGmthGc.d.mts.map +1 -0
- package/dist/{define-adapter-BRJ6lXkV.mjs → define-adapter-C6H-I1og.mjs} +2 -2
- package/dist/{define-adapter-BRJ6lXkV.mjs.map → define-adapter-C6H-I1og.mjs.map} +1 -1
- package/dist/di-hooks-BE0IOQk-.mjs +132 -0
- package/dist/di-hooks-BE0IOQk-.mjs.map +1 -0
- package/dist/disposables-Cste73oY.mjs +11 -0
- package/dist/error-handler-C6JJJct_.d.mts +63 -0
- package/dist/error-handler-C6JJJct_.d.mts.map +1 -0
- package/dist/{handler-Dl_1fGxE.mjs → handler-DUyRCpPw.mjs} +3 -3
- package/dist/{handler-Dl_1fGxE.mjs.map → handler-DUyRCpPw.mjs.map} +1 -1
- package/dist/{host-DTQ5pZgg.mjs → host-fc-YQZnN.mjs} +2 -2
- package/dist/{host-DTQ5pZgg.mjs.map → host-fc-YQZnN.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -3
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +2 -2
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.d.mts.map +1 -1
- package/dist/http/runtimes/fastify.mjs +3 -3
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +5 -4
- package/dist/http/runtimes/h3.d.mts.map +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-CuiWSnZL.d.mts → index-Dms8LzHG.d.mts} +3 -3
- package/dist/{index-CuiWSnZL.d.mts.map → index-Dms8LzHG.d.mts.map} +1 -1
- package/dist/index.d.mts +17 -11
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/interfaces-C6LHcYsg.d.mts +34 -0
- package/dist/interfaces-C6LHcYsg.d.mts.map +1 -0
- package/dist/{is-production-tnFh6NCj.mjs → is-production-0lB5MU1j.mjs} +2 -2
- package/dist/{is-production-tnFh6NCj.mjs.map → is-production-0lB5MU1j.mjs.map} +1 -1
- package/dist/jobs-DWi_Lwbe.mjs +12 -0
- package/dist/{jobs-lLcPhIqq.mjs.map → jobs-DWi_Lwbe.mjs.map} +1 -1
- package/dist/kv-stores-BGXPKv15.d.mts +366 -0
- package/dist/kv-stores-BGXPKv15.d.mts.map +1 -0
- package/dist/{kv-stores-_wz4DEiw.mjs → kv-stores-BGXeNEDK.mjs} +3 -3
- package/dist/{kv-stores-_wz4DEiw.mjs.map → kv-stores-BGXeNEDK.mjs.map} +1 -1
- package/dist/lazy-serve-static-Barg3__1.mjs +12 -0
- package/dist/lazy-serve-static-Barg3__1.mjs.map +1 -0
- package/dist/metadata-CnL9sQFa.mjs +11 -0
- package/dist/{observers-IGga6yut.mjs → observers-BNMQ7VLb.mjs} +2 -2
- package/dist/{observers-IGga6yut.mjs.map → observers-BNMQ7VLb.mjs.map} +1 -1
- package/dist/{query-AnbWMCd6.mjs → query-mXPZYtQw.mjs} +2 -2
- package/dist/{query-AnbWMCd6.mjs.map → query-mXPZYtQw.mjs.map} +1 -1
- package/dist/{reply-DjysdCPI.mjs → reply-CMRk-Jp3.mjs} +3 -3
- package/dist/{reply-DjysdCPI.mjs.map → reply-CMRk-Jp3.mjs.map} +1 -1
- package/dist/{respond-vPZlRnZR.mjs → respond-gPELdOSi.mjs} +2 -2
- package/dist/{respond-vPZlRnZR.mjs.map → respond-gPELdOSi.mjs.map} +1 -1
- package/dist/{route-flag-BjRpxryx.mjs → route-flag-8Pi83-uw.mjs} +3 -3
- package/dist/{route-flag-BjRpxryx.mjs.map → route-flag-8Pi83-uw.mjs.map} +1 -1
- package/dist/{route-policy-Pffte5M1.mjs → route-policy-0LAfSzo-.mjs} +2 -2
- package/dist/{route-policy-Pffte5M1.mjs.map → route-policy-0LAfSzo-.mjs.map} +1 -1
- package/dist/router-builder-D0SDqFTr.mjs +12 -0
- package/dist/{router-builder-CrWKq6O2.mjs.map → router-builder-D0SDqFTr.mjs.map} +1 -1
- package/dist/router-builder-obSpg-Ub.d.mts +56 -0
- package/dist/router-builder-obSpg-Ub.d.mts.map +1 -0
- package/dist/settings-BW5gVm6c.mjs +14 -0
- package/dist/{settings-CFtEAQUs.mjs.map → settings-BW5gVm6c.mjs.map} +1 -1
- package/dist/{settings-C8VKewNS.d.mts → settings-BnE75hnr.d.mts} +2 -2
- package/dist/{settings-C8VKewNS.d.mts.map → settings-BnE75hnr.d.mts.map} +1 -1
- package/dist/token-D6jfTQLA.d.mts +3 -0
- package/dist/token-Q2c8xwJE.mjs +11 -0
- package/dist/upload-CyBSlnH_.d.mts +104 -0
- package/dist/upload-CyBSlnH_.d.mts.map +1 -0
- package/dist/{upload-config-DLgt4l7F.mjs → upload-config-D22qKth8.mjs} +2 -2
- package/dist/{upload-config-DLgt4l7F.mjs.map → upload-config-D22qKth8.mjs.map} +1 -1
- package/dist/url-for-UZ5kJjsG.mjs +12 -0
- package/dist/{url-for-Cyh7pJCb.mjs.map → url-for-UZ5kJjsG.mjs.map} +1 -1
- package/dist/web.d.mts +5 -4
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +6 -1
- package/dist/adapter-C5I5e_-i.d.mts +0 -4866
- package/dist/adapter-C5I5e_-i.d.mts.map +0 -1
- package/dist/app-module-Ftz6m7SO.d.mts.map +0 -1
- package/dist/bootstrap-D56HIq1N.mjs +0 -12
- package/dist/container-C2aTj8Cb.mjs +0 -132
- package/dist/container-C2aTj8Cb.mjs.map +0 -1
- package/dist/container-Dpvd66Yt.d.mts +0 -298
- package/dist/container-Dpvd66Yt.d.mts.map +0 -1
- package/dist/core-CFXpwc7m.mjs +0 -12
- package/dist/decorate-DkxaoRo5.mjs +0 -13
- package/dist/decorators-DaQUNXOn.d.mts.map +0 -1
- package/dist/disposables-5nFqc1aC.mjs +0 -12
- package/dist/disposables-5nFqc1aC.mjs.map +0 -1
- package/dist/interfaces-C1hCSoLD.d.mts +0 -75
- package/dist/interfaces-C1hCSoLD.d.mts.map +0 -1
- package/dist/jobs-lLcPhIqq.mjs +0 -12
- package/dist/metadata-Tc6jhIBi.mjs +0 -12
- package/dist/metadata-Tc6jhIBi.mjs.map +0 -1
- package/dist/router-builder-CrWKq6O2.mjs +0 -12
- package/dist/settings-CFtEAQUs.mjs +0 -14
- package/dist/url-for-Cyh7pJCb.mjs +0 -12
|
@@ -0,0 +1,1985 @@
|
|
|
1
|
+
|
|
2
|
+
import { i as SettingsDeclaration, s as VarOrigin, t as ConfigVar } from "./settings-BnE75hnr.mjs";
|
|
3
|
+
import "./index-Dms8LzHG.mjs";
|
|
4
|
+
import { C as RuntimeResponse, Ct as KickPlugin, I as RouteName, Nt as ResponseInfo, O as RequestContext, R as UrlForArgs, Rt as ConditionOutcome, S as RuntimeCapabilities, V as AdapterFactory, _ as RouteEntry, a as KickServer, c as ActiveRuntime, g as RouteContributor, gt as ModuleFactory, p as HttpRuntime, r as AppAdapter, wt as ModuleRegistry } from "./adapter-6fjmVVc2.mjs";
|
|
5
|
+
import { t as Container } from "./container-4iJdDkRH.mjs";
|
|
6
|
+
import { p as RouteFlags, s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
|
|
7
|
+
import { C as MetaValue, c as ContextDecorator, h as DepValue, m as ContributorRegistrations, r as AppModuleEntry, u as ContextDecoratorSpec, x as ContextMetaKey } from "./app-module-Cuu-Ma_E.mjs";
|
|
8
|
+
import { c as PlatformContext, p as Reply } from "./kv-stores-BGXPKv15.mjs";
|
|
9
|
+
import "./session-ChXx7jG5.mjs";
|
|
10
|
+
import { t as ValidationErrorFactory } from "./validate-CzjCbRUn.mjs";
|
|
11
|
+
import { t as AllowedHostsOptions } from "./allowed-hosts-D6qcuK5I.mjs";
|
|
12
|
+
import { t as BuildRoutesOptions } from "./router-builder-obSpg-Ub.mjs";
|
|
13
|
+
import "./request-id-CVzJ1uHD.mjs";
|
|
14
|
+
import "./error-handler-C6JJJct_.mjs";
|
|
15
|
+
import "./csrf-ahBjt1ay.mjs";
|
|
16
|
+
import "./helmet-CEOmo516.mjs";
|
|
17
|
+
import "./breach-padding-C-Dnq8CS.mjs";
|
|
18
|
+
import "./cors-2Bwhyhpt.mjs";
|
|
19
|
+
import "./rate-limit-BgoeahE5.mjs";
|
|
20
|
+
import "./upload-CyBSlnH_.mjs";
|
|
21
|
+
import http, { IncomingMessage, ServerResponse } from "node:http";
|
|
22
|
+
import tls from "node:tls";
|
|
23
|
+
import { Express, NextFunction, Request as Request$1, RequestHandler, Response as Response$1, Router } from "express";
|
|
24
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
25
|
+
//#region src/core/kick-error.d.ts
|
|
26
|
+
/**
|
|
27
|
+
* Structured framework error with code, cause, and actionable fix hint.
|
|
28
|
+
*
|
|
29
|
+
* The goal is "the developer who hits this knows what to do next." A
|
|
30
|
+
* cryptic `Error('No binding found for: UserService')` becomes a
|
|
31
|
+
* multi-line explanation pointing at the likely cause, the exact code
|
|
32
|
+
* change to apply, and a docs link.
|
|
33
|
+
*
|
|
34
|
+
* `.message` carries the full multi-line plain-text body so Node's
|
|
35
|
+
* default `Error.toString()` and unhandled-exception printing still
|
|
36
|
+
* surface the helpful version. Call {@link formatKickError} to render a
|
|
37
|
+
* colorized version for terminals.
|
|
38
|
+
*
|
|
39
|
+
* Per-error factories live in `kick-errors.ts` — those are the public
|
|
40
|
+
* entry points framework code uses. `KickError` is exported so adopters
|
|
41
|
+
* can build their own structured errors using the same shape.
|
|
42
|
+
*/
|
|
43
|
+
interface KickErrorInit {
|
|
44
|
+
/** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */
|
|
45
|
+
code: string;
|
|
46
|
+
/** One-line headline. */
|
|
47
|
+
summary: string;
|
|
48
|
+
/** Multi-line explanation of why this happened. */
|
|
49
|
+
cause?: string;
|
|
50
|
+
/** Multi-line actionable fix — show exact code if possible. */
|
|
51
|
+
fix?: string;
|
|
52
|
+
/** Absolute URL to the docs page that covers this error. */
|
|
53
|
+
docsUrl?: string;
|
|
54
|
+
/** Arbitrary structured fields for log consumers / debug tooling. */
|
|
55
|
+
context?: Record<string, unknown>;
|
|
56
|
+
}
|
|
57
|
+
declare class KickError extends Error {
|
|
58
|
+
readonly code: string;
|
|
59
|
+
readonly summary: string;
|
|
60
|
+
readonly cause?: string;
|
|
61
|
+
readonly fix?: string;
|
|
62
|
+
readonly docsUrl?: string;
|
|
63
|
+
readonly context?: Record<string, unknown>;
|
|
64
|
+
constructor(init: KickErrorInit);
|
|
65
|
+
}
|
|
66
|
+
interface FormatKickErrorOptions {
|
|
67
|
+
/**
|
|
68
|
+
* Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /
|
|
69
|
+
* `FORCE_COLOR` env vars honoured). Pass `false` for log files,
|
|
70
|
+
* structured loggers, or HTTP response bodies.
|
|
71
|
+
*/
|
|
72
|
+
color?: boolean;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Render a {@link KickErrorInit} (or {@link KickError} instance) into a
|
|
76
|
+
* multi-line human-readable string. Identical layout regardless of
|
|
77
|
+
* colour — the colour flag only toggles ANSI codes.
|
|
78
|
+
*/
|
|
79
|
+
declare function formatKickError(err: KickErrorInit | KickError, options?: FormatKickErrorOptions): string;
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/core/circuit-breaker.d.ts
|
|
82
|
+
/**
|
|
83
|
+
* Circuit Breaker pattern for external service calls.
|
|
84
|
+
*
|
|
85
|
+
* Protects your application from cascading failures when downstream
|
|
86
|
+
* services are unhealthy by short-circuiting requests after a
|
|
87
|
+
* configurable failure threshold.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```ts
|
|
91
|
+
* const breaker = new CircuitBreaker('payment-api', {
|
|
92
|
+
* failureThreshold: 5,
|
|
93
|
+
* resetTimeout: 30_000,
|
|
94
|
+
* })
|
|
95
|
+
*
|
|
96
|
+
* const result = await breaker.execute(() => fetch('https://payment.example.com/charge'))
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
type CircuitBreakerState = 'closed' | 'open' | 'half_open';
|
|
100
|
+
interface CircuitBreakerOptions {
|
|
101
|
+
/** Number of consecutive failures before the circuit opens. */
|
|
102
|
+
failureThreshold: number;
|
|
103
|
+
/** Milliseconds to wait before transitioning from OPEN to HALF_OPEN. */
|
|
104
|
+
resetTimeout: number;
|
|
105
|
+
/** Max requests allowed in HALF_OPEN state before deciding (default 1). */
|
|
106
|
+
halfOpenMax?: number;
|
|
107
|
+
}
|
|
108
|
+
interface CircuitBreakerStats {
|
|
109
|
+
failures: number;
|
|
110
|
+
successes: number;
|
|
111
|
+
state: CircuitBreakerState;
|
|
112
|
+
lastFailure?: Date;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Error thrown when the circuit is open and calls are being rejected.
|
|
116
|
+
*/
|
|
117
|
+
declare class CircuitOpenError extends Error {
|
|
118
|
+
readonly breakerName: string;
|
|
119
|
+
constructor(breakerName: string);
|
|
120
|
+
}
|
|
121
|
+
declare class CircuitBreaker {
|
|
122
|
+
readonly name: string;
|
|
123
|
+
private state;
|
|
124
|
+
private failures;
|
|
125
|
+
private successes;
|
|
126
|
+
private halfOpenAttempts;
|
|
127
|
+
private lastFailure?;
|
|
128
|
+
private openedAt?;
|
|
129
|
+
private readonly failureThreshold;
|
|
130
|
+
private readonly resetTimeout;
|
|
131
|
+
private readonly halfOpenMax;
|
|
132
|
+
constructor(name: string, options: CircuitBreakerOptions);
|
|
133
|
+
/**
|
|
134
|
+
* Execute an async function through the circuit breaker.
|
|
135
|
+
* Throws `CircuitOpenError` if the circuit is open.
|
|
136
|
+
*/
|
|
137
|
+
execute<T>(fn: () => Promise<T>): Promise<T>;
|
|
138
|
+
/** Returns the current circuit state. */
|
|
139
|
+
getState(): CircuitBreakerState;
|
|
140
|
+
/** Returns current statistics. */
|
|
141
|
+
getStats(): CircuitBreakerStats;
|
|
142
|
+
/** Manually reset the circuit breaker to CLOSED state. */
|
|
143
|
+
reset(): void;
|
|
144
|
+
private onSuccess;
|
|
145
|
+
private onFailure;
|
|
146
|
+
private maybeTransitionToHalfOpen;
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region src/core/context-errors.d.ts
|
|
150
|
+
/**
|
|
151
|
+
* Errors thrown by the Context Contributor pipeline.
|
|
152
|
+
*
|
|
153
|
+
* `MissingContributorError`, `ContributorCycleError`, and
|
|
154
|
+
* `DuplicateContributorError` are startup-time errors raised during
|
|
155
|
+
* pipeline build (topo-sort + validation), not per-request — a
|
|
156
|
+
* misconfigured app fails to boot rather than fails a request. Per the
|
|
157
|
+
* locked design in `architecture.md` §20.4, the pipeline is validated
|
|
158
|
+
* once when each route is mounted and the resolved order is cached on
|
|
159
|
+
* the route.
|
|
160
|
+
*
|
|
161
|
+
* `MissingContextValueError` is the one request-time error here: it is
|
|
162
|
+
* raised by `ctx.require(key)` when a value a handler declared it needs
|
|
163
|
+
* is absent. See its doc comment for why that case can't be caught at
|
|
164
|
+
* startup today.
|
|
165
|
+
*/
|
|
166
|
+
/**
|
|
167
|
+
* A contributor declared `dependsOn: ['<key>']` but no other contributor
|
|
168
|
+
* (at any precedence level) produces that key for the same route.
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* ```text
|
|
172
|
+
* MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id
|
|
173
|
+
* declared at src/contributors/load-project.ts:42:18
|
|
174
|
+
* ```
|
|
175
|
+
*/
|
|
176
|
+
declare class MissingContributorError extends Error {
|
|
177
|
+
readonly key: string;
|
|
178
|
+
readonly dependent: string;
|
|
179
|
+
readonly route?: string;
|
|
180
|
+
readonly dependentDefinedAt?: string;
|
|
181
|
+
constructor(key: string, dependent: string, route?: string, dependentDefinedAt?: string);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* `ctx.require(key)` found no value under `key` in the per-request
|
|
185
|
+
* metadata store.
|
|
186
|
+
*
|
|
187
|
+
* Thrown at request time, by design. `ctx.get(key)` returns
|
|
188
|
+
* `T | undefined` for every key, so the usual workaround is a
|
|
189
|
+
* non-null assertion — `ctx.get('tenant')!` — which compiles whether or
|
|
190
|
+
* not the route actually carries the contributor that produces it. On
|
|
191
|
+
* an authorization value that is the worst possible thing to leave
|
|
192
|
+
* untypeable: dropping the decorator produces no diagnostic anywhere,
|
|
193
|
+
* and the handler reads `undefined` as though it were a real value.
|
|
194
|
+
*
|
|
195
|
+
* `ctx.require()` converts that silent hole into a loud, named failure
|
|
196
|
+
* that points at the missing contributor.
|
|
197
|
+
*
|
|
198
|
+
* A handler typed with a generated route type (`Ctx<KickRoutes…>`) also
|
|
199
|
+
* gets compile-time narrowing, so a dropped decorator fails `tsc` rather
|
|
200
|
+
* than reaching this error at all. This error remains the backstop for
|
|
201
|
+
* routes typegen couldn't prove (module/adapter/bootstrap registrations),
|
|
202
|
+
* handlers typed as plain `RequestContext`, and contributors that ran but
|
|
203
|
+
* resolved to `undefined`. See `architecture.md` §20.14.
|
|
204
|
+
*
|
|
205
|
+
* @example
|
|
206
|
+
* ```text
|
|
207
|
+
* MissingContextValueError: No context value for 'tenantPerm' on GET /projects/:id
|
|
208
|
+
* Nothing wrote this key before the handler ran. Either the contributor
|
|
209
|
+
* that produces it isn't applied to this route, or it ran and resolved
|
|
210
|
+
* to undefined (check `optional: true` contributors).
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
declare class MissingContextValueError extends Error {
|
|
214
|
+
readonly key: string;
|
|
215
|
+
readonly route?: string;
|
|
216
|
+
constructor(key: string, route?: string);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field
|
|
220
|
+
* lists the keys in the order they form the loop, with the first key
|
|
221
|
+
* repeated at the end so the path reads naturally.
|
|
222
|
+
*
|
|
223
|
+
* @example
|
|
224
|
+
* ```text
|
|
225
|
+
* ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant
|
|
226
|
+
* ```
|
|
227
|
+
*/
|
|
228
|
+
declare class ContributorCycleError extends Error {
|
|
229
|
+
readonly cycle: readonly string[];
|
|
230
|
+
readonly route?: string;
|
|
231
|
+
constructor(cycle: readonly string[], route?: string);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Two contributors at the same precedence level both produce the same key
|
|
235
|
+
* for the same route. Precedence resolution (method > class > module >
|
|
236
|
+
* adapter > global, per architecture.md §20.4) silently drops
|
|
237
|
+
* lower-precedence duplicates; this error fires only when ties occur
|
|
238
|
+
* within a single level — e.g., two method-level decorators declaring
|
|
239
|
+
* `key: 'tenant'`.
|
|
240
|
+
*
|
|
241
|
+
* `sources` is best-effort identifying labels for each conflicting
|
|
242
|
+
* registration (typically the decorator's call site or registering
|
|
243
|
+
* module/adapter name).
|
|
244
|
+
*
|
|
245
|
+
* @example
|
|
246
|
+
* ```text
|
|
247
|
+
* DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
declare class DuplicateContributorError extends Error {
|
|
251
|
+
readonly key: string;
|
|
252
|
+
readonly sources: readonly string[];
|
|
253
|
+
constructor(key: string, sources: readonly string[]);
|
|
254
|
+
}
|
|
255
|
+
//#endregion
|
|
256
|
+
//#region src/core/mount-sort.d.ts
|
|
257
|
+
/**
|
|
258
|
+
* Topological sort for plugins and adapters with `dependsOn` declarations.
|
|
259
|
+
*
|
|
260
|
+
* Mirrors the algorithm used by the Context Contributor pipeline
|
|
261
|
+
* (`contributor-pipeline.ts:topoSort`) but operates on a name-keyed
|
|
262
|
+
* `MountSortItem` shape rather than a `ContributorRegistration`. Kept
|
|
263
|
+
* standalone instead of factored generic so that:
|
|
264
|
+
*
|
|
265
|
+
* 1. The contributor pipeline doesn't need refactoring (risk reduction).
|
|
266
|
+
* 2. The error classes can carry plugin/adapter-specific diagnostic
|
|
267
|
+
* fields (`kind`, `dependent`) without bending the contributor types.
|
|
268
|
+
*/
|
|
269
|
+
/**
|
|
270
|
+
* A plugin or adapter that participates in dependency-ordered mounting.
|
|
271
|
+
* Both `KickPlugin` and `AppAdapter` satisfy this shape via their `name`
|
|
272
|
+
* and `dependsOn` fields.
|
|
273
|
+
*/
|
|
274
|
+
interface MountSortItem {
|
|
275
|
+
/** Unique mount name within the plugin/adapter set being sorted. */
|
|
276
|
+
name: string;
|
|
277
|
+
/**
|
|
278
|
+
* Other plugin/adapter names that must mount before this one. Cycles
|
|
279
|
+
* and missing names fail at boot — same fail-fast contract as the
|
|
280
|
+
* Context Contributor pipeline (architecture.md §20.4).
|
|
281
|
+
*/
|
|
282
|
+
dependsOn?: readonly string[];
|
|
283
|
+
}
|
|
284
|
+
/** What kind of mount set the sort is operating on — surfaces in error messages. */
|
|
285
|
+
type MountKind = 'plugin' | 'adapter';
|
|
286
|
+
/**
|
|
287
|
+
* Two items in the same mount set declared the same `name`. Plugin/adapter
|
|
288
|
+
* names must be unique so `dependsOn` references resolve unambiguously.
|
|
289
|
+
*/
|
|
290
|
+
declare class DuplicateMountNameError extends Error {
|
|
291
|
+
readonly kind: MountKind;
|
|
292
|
+
readonly mountName: string;
|
|
293
|
+
constructor(kind: MountKind, mountName: string);
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* A `dependsOn` entry references a plugin/adapter that isn't in the
|
|
297
|
+
* current set. The dependency might not be installed, might be misspelled,
|
|
298
|
+
* or might live in a different mount set (plugin referencing an adapter,
|
|
299
|
+
* or vice versa — they sort independently).
|
|
300
|
+
*/
|
|
301
|
+
declare class MissingMountDepError extends Error {
|
|
302
|
+
readonly kind: MountKind;
|
|
303
|
+
readonly missing: string;
|
|
304
|
+
readonly dependent: string;
|
|
305
|
+
constructor(kind: MountKind, missing: string, dependent: string);
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* The `dependsOn` declarations form a cycle. Boot fails so the cycle
|
|
309
|
+
* can't poison live traffic. The `cycle` field reports one path through
|
|
310
|
+
* the offending nodes for diagnostics — formatted `A → B → C → A`.
|
|
311
|
+
*/
|
|
312
|
+
declare class MountCycleError extends Error {
|
|
313
|
+
readonly kind: MountKind;
|
|
314
|
+
readonly cycle: readonly string[];
|
|
315
|
+
constructor(kind: MountKind, cycle: readonly string[]);
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Topologically sort `items` so every item with `dependsOn: ['X']` mounts
|
|
319
|
+
* after `X`. Items without `dependsOn` keep their input order via Kahn's
|
|
320
|
+
* algorithm with a FIFO queue seeded in input order — preserves the
|
|
321
|
+
* historical "plugins/adapters mount in declaration order" behaviour for
|
|
322
|
+
* any set that doesn't use `dependsOn`.
|
|
323
|
+
*
|
|
324
|
+
* @param items - mountable items, e.g. plugins or adapters
|
|
325
|
+
* @param kind - 'plugin' | 'adapter', used in error messages
|
|
326
|
+
* @returns a new array in valid mount order
|
|
327
|
+
* @throws {DuplicateMountNameError} two items share a name
|
|
328
|
+
* @throws {MissingMountDepError} a `dependsOn` references an unknown name
|
|
329
|
+
* @throws {MountCycleError} the dep graph contains a cycle
|
|
330
|
+
*/
|
|
331
|
+
declare function mountSort<T extends MountSortItem>(items: readonly T[], kind: MountKind): T[];
|
|
332
|
+
//#endregion
|
|
333
|
+
//#region src/core/asset-keys.d.ts
|
|
334
|
+
type AssetKeyStrategy = 'auto' | 'strip' | 'with-extension';
|
|
335
|
+
interface AssetKeyPair {
|
|
336
|
+
/** Source-relative path the file was discovered at. */
|
|
337
|
+
rel: string;
|
|
338
|
+
/** Final logical key for the manifest, including the namespace prefix. */
|
|
339
|
+
key: string;
|
|
340
|
+
}
|
|
341
|
+
interface GroupAssetKeysOptions {
|
|
342
|
+
/**
|
|
343
|
+
* Strategy applied to this namespace. Default `'auto'`.
|
|
344
|
+
*
|
|
345
|
+
* Adopters override per-namespace via `assetMap.<ns>.keys` in
|
|
346
|
+
* kick.config.ts when they want uniform behaviour (e.g. always
|
|
347
|
+
* include the extension regardless of collisions).
|
|
348
|
+
*/
|
|
349
|
+
strategy?: AssetKeyStrategy;
|
|
350
|
+
}
|
|
351
|
+
interface GroupAssetKeysResult {
|
|
352
|
+
pairs: AssetKeyPair[];
|
|
353
|
+
/**
|
|
354
|
+
* Number of collision groups resolved by keeping extensions.
|
|
355
|
+
* Surfaces as an informational log ("auto-resolved N collisions")
|
|
356
|
+
* so adopters know whether they're relying on auto-mode or not.
|
|
357
|
+
* Always 0 for `'strip'` (overwrites) and `'with-extension'`
|
|
358
|
+
* (extensions always preserved, no collision possible).
|
|
359
|
+
*/
|
|
360
|
+
collisionGroupsResolved: number;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Compute final manifest keys for a namespace's discovered paths,
|
|
364
|
+
* given the chosen strategy. Pure function — no fs / config / globals
|
|
365
|
+
* involved.
|
|
366
|
+
*
|
|
367
|
+
* @param namespace assetMap key — e.g. `'mails'`, `'pages'`.
|
|
368
|
+
* @param paths source-relative file paths (POSIX separators) discovered
|
|
369
|
+
* under the namespace's `src` directory.
|
|
370
|
+
* @param opts grouping options.
|
|
371
|
+
*/
|
|
372
|
+
declare function groupAssetKeys(namespace: string, paths: readonly string[], opts?: GroupAssetKeysOptions): GroupAssetKeysResult;
|
|
373
|
+
/** Strip the final extension from a path. `'mails/welcome.ejs'` → `'mails/welcome'`. */
|
|
374
|
+
declare function stripExt(path: string): string;
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/core/route-policy.d.ts
|
|
377
|
+
declare class RoutePolicyTable {
|
|
378
|
+
/** Bucketed by method: an incoming request only scans its own verb. */
|
|
379
|
+
private readonly byMethod;
|
|
380
|
+
add(method: string, path: string, flags: RouteFlags | undefined): void;
|
|
381
|
+
/**
|
|
382
|
+
* Flags that apply to `method pathname`, or an empty map when the path
|
|
383
|
+
* matches no flagged route — including when it matches no route at all,
|
|
384
|
+
* which is exactly the traffic this exists to keep visible.
|
|
385
|
+
*/
|
|
386
|
+
lookup(method: string, pathname: string): RouteFlags;
|
|
387
|
+
/** Drop everything — the Application rebuilds on every HMR reload. */
|
|
388
|
+
clear(): void;
|
|
389
|
+
get size(): number;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Declare that `handler` wants the policy table.
|
|
393
|
+
*
|
|
394
|
+
* Explicit hand-off rather than a module-level singleton, so the table a
|
|
395
|
+
* middleware reads is always the one belonging to the app that mounted it.
|
|
396
|
+
*/
|
|
397
|
+
declare function bindRoutePolicy<T extends object>(handler: T, receive: (table: RoutePolicyTable) => void): T;
|
|
398
|
+
/** Hand the table to a middleware if it declared the slot. */
|
|
399
|
+
declare function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void;
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/http/startup-timeline.d.ts
|
|
402
|
+
/**
|
|
403
|
+
* Where startup time goes: each phase of `setup()` / `start()`, and each
|
|
404
|
+
* adapter hook on its own, so "boot got slow" points at a name.
|
|
405
|
+
*
|
|
406
|
+
* @module @forinda/kickjs/http/startup-timeline
|
|
407
|
+
*/
|
|
408
|
+
/** One timed step, in the order it ran. */
|
|
409
|
+
interface StartupStep {
|
|
410
|
+
/** A phase (`'modules'`, `'routes'`, `'listen'`) or `'<Adapter>.<hook>'`. */
|
|
411
|
+
name: string;
|
|
412
|
+
ms: number;
|
|
413
|
+
}
|
|
414
|
+
interface StartupTimelineSnapshot {
|
|
415
|
+
totalMs: number;
|
|
416
|
+
steps: readonly StartupStep[];
|
|
417
|
+
}
|
|
418
|
+
//#endregion
|
|
419
|
+
//#region src/http/startup-checks.d.ts
|
|
420
|
+
/** One finding. `error` fails startup; `warning` is logged. */
|
|
421
|
+
interface CheckMessage {
|
|
422
|
+
/** Stable ID, e.g. `'KICK-SEC-W001'` — what `silenceChecks` matches. */
|
|
423
|
+
id: string;
|
|
424
|
+
level: 'error' | 'warning';
|
|
425
|
+
message: string;
|
|
426
|
+
/** What to change. */
|
|
427
|
+
fix?: string;
|
|
428
|
+
}
|
|
429
|
+
/** What a check can look at. */
|
|
430
|
+
interface CheckContext {
|
|
431
|
+
/** The options the app was created with. */
|
|
432
|
+
options: Readonly<Record<string, unknown>>;
|
|
433
|
+
/** Every mounted route, `{ method, path }`. */
|
|
434
|
+
routes: ReadonlyArray<{
|
|
435
|
+
method: string;
|
|
436
|
+
path: string;
|
|
437
|
+
}>;
|
|
438
|
+
production: boolean;
|
|
439
|
+
}
|
|
440
|
+
interface StartupCheck {
|
|
441
|
+
/** Names the check in logs; its messages carry their own IDs. */
|
|
442
|
+
name: string;
|
|
443
|
+
/** Run only when `NODE_ENV=production` — for deployment-only advice. */
|
|
444
|
+
deploy?: boolean;
|
|
445
|
+
run(ctx: CheckContext): CheckMessage | CheckMessage[] | undefined | void;
|
|
446
|
+
}
|
|
447
|
+
/** Declare a check — an identity helper, for the types. */
|
|
448
|
+
declare function defineCheck(check: StartupCheck): StartupCheck;
|
|
449
|
+
/** Thrown when a check reports an error; lists every error found. */
|
|
450
|
+
declare class StartupCheckError extends Error {
|
|
451
|
+
readonly messages: CheckMessage[];
|
|
452
|
+
constructor(messages: CheckMessage[]);
|
|
453
|
+
}
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region src/http/metrics.d.ts
|
|
456
|
+
interface MetricsOptions {
|
|
457
|
+
/** Where to serve the metrics. Default `/metrics`. */
|
|
458
|
+
path?: string;
|
|
459
|
+
/**
|
|
460
|
+
* Require `Authorization: Bearer <token>` to read them. The endpoint is
|
|
461
|
+
* mounted before the app's middleware (so a scraper doesn't need your
|
|
462
|
+
* auth), which also means your auth doesn't cover it — set this unless
|
|
463
|
+
* the port is only reachable by the scraper.
|
|
464
|
+
*/
|
|
465
|
+
token?: string;
|
|
466
|
+
/** Histogram buckets, in seconds. Default: Prometheus' defaults, 5ms to 10s. */
|
|
467
|
+
buckets?: number[];
|
|
468
|
+
}
|
|
469
|
+
/** The request histogram, keyed by its label set. */
|
|
470
|
+
declare class RequestHistogram {
|
|
471
|
+
private readonly series;
|
|
472
|
+
private readonly buckets;
|
|
473
|
+
/**
|
|
474
|
+
* Bounds in seconds — sorted and deduplicated here, since the exposition
|
|
475
|
+
* format needs them strictly increasing; anything not a finite positive
|
|
476
|
+
* number is rejected.
|
|
477
|
+
*/
|
|
478
|
+
constructor(buckets?: readonly number[]);
|
|
479
|
+
observe(info: Pick<ResponseInfo, 'method' | 'route' | 'status' | 'durationMs'>): void;
|
|
480
|
+
render(): string;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Serve Prometheus metrics. Add it to `adapters`:
|
|
484
|
+
*
|
|
485
|
+
* ```ts
|
|
486
|
+
* bootstrap({ modules, adapters: [metricsAdapter({ token: process.env.METRICS_TOKEN })] })
|
|
487
|
+
* ```
|
|
488
|
+
*/
|
|
489
|
+
declare function metricsAdapter(options?: MetricsOptions): AppAdapter;
|
|
490
|
+
//#endregion
|
|
491
|
+
//#region src/http/body-policy.d.ts
|
|
492
|
+
/**
|
|
493
|
+
* Set to `true` on a request (`req[RAW_BODY] = true`) by middleware that will
|
|
494
|
+
* read the body stream itself — a tus endpoint, a proxy — so the 415 below
|
|
495
|
+
* leaves it alone. Mark it in an earlier phase (an adapter's `beforeGlobal`),
|
|
496
|
+
* consume it later.
|
|
497
|
+
*/
|
|
498
|
+
declare const RAW_BODY: unique symbol;
|
|
499
|
+
//#endregion
|
|
500
|
+
//#region src/http/cron-adapter.d.ts
|
|
501
|
+
/** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */
|
|
502
|
+
declare const CRON_WORKER_ENV = "KICK_CRON_WORKER";
|
|
503
|
+
interface CronAdapterOptions {
|
|
504
|
+
/** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */
|
|
505
|
+
enabled?: boolean;
|
|
506
|
+
}
|
|
507
|
+
declare const KickCronAdapter: AdapterFactory<CronAdapterOptions, unknown>;
|
|
508
|
+
//#endregion
|
|
509
|
+
//#region src/http/tracing.d.ts
|
|
510
|
+
declare const HANDLER_CHANNEL = "kickjs:handler";
|
|
511
|
+
declare const ERROR_CHANNEL = "kickjs:error";
|
|
512
|
+
declare const RESPONSE_CHANNEL = "kickjs:response";
|
|
513
|
+
/** What subscribers to `kickjs:handler` receive. */
|
|
514
|
+
interface HandlerTraceContext {
|
|
515
|
+
method: string;
|
|
516
|
+
/** The route pattern, e.g. `/api/v1/users/:id` — the span name APMs want. */
|
|
517
|
+
route: string;
|
|
518
|
+
controller?: string;
|
|
519
|
+
handler?: string;
|
|
520
|
+
requestId?: string;
|
|
521
|
+
ctx: RequestContext;
|
|
522
|
+
}
|
|
523
|
+
//#endregion
|
|
524
|
+
//#region src/http/bootstrap.d.ts
|
|
525
|
+
/**
|
|
526
|
+
* Bootstrap a KickJS application.
|
|
527
|
+
*
|
|
528
|
+
* Creates the Express app, registers modules and adapters, and starts
|
|
529
|
+
* the HTTP server. In dev mode (`kick dev`), the Vite plugin manages
|
|
530
|
+
* the server and HMR — source changes are picked up instantly without
|
|
531
|
+
* losing database connections or WebSocket state.
|
|
532
|
+
*
|
|
533
|
+
* @returns The {@link Application} instance.
|
|
534
|
+
*
|
|
535
|
+
* @example
|
|
536
|
+
* ```ts
|
|
537
|
+
* // src/index.ts
|
|
538
|
+
* import 'reflect-metadata'
|
|
539
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
540
|
+
* import { modules } from './modules'
|
|
541
|
+
*
|
|
542
|
+
* export const app = await bootstrap({ modules })
|
|
543
|
+
* ```
|
|
544
|
+
*/
|
|
545
|
+
declare function bootstrap(options: ApplicationOptions): Promise<Application>;
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region src/http/handler.d.ts
|
|
548
|
+
/** A KickJS app exposed as request handlers. See {@link createHandler}. */
|
|
549
|
+
interface KickHandler {
|
|
550
|
+
/**
|
|
551
|
+
* Web-standard handler: `fetch(Request) → Response`. Netlify Functions,
|
|
552
|
+
* Vercel's fetch export, and anything else that speaks `Request`.
|
|
553
|
+
*
|
|
554
|
+
* Pass the platform context (Netlify's `context`, `{ waitUntil }` from
|
|
555
|
+
* `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after
|
|
556
|
+
* the response instead of being frozen with the instance.
|
|
557
|
+
*/
|
|
558
|
+
fetch(request: Request, platform?: PlatformContext): Promise<Response>;
|
|
559
|
+
/** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */
|
|
560
|
+
node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>;
|
|
561
|
+
/** Set the app up now instead of on the first request (warm-up). */
|
|
562
|
+
ready(): Promise<Application>;
|
|
563
|
+
/** Shut adapters down and stop the internal forwarding server, if one started. */
|
|
564
|
+
close(): Promise<void>;
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Build a KickJS app as request handlers instead of a listening server.
|
|
568
|
+
*
|
|
569
|
+
* Takes the same options as `bootstrap()`, or a function that imports the
|
|
570
|
+
* app's entry — the file that calls `bootstrap()`. With the entry, the app
|
|
571
|
+
* is built from that one `bootstrap({ ... })` call, so the server and the
|
|
572
|
+
* function never drift apart:
|
|
573
|
+
*
|
|
574
|
+
* ```ts
|
|
575
|
+
* // src/serverless.ts
|
|
576
|
+
* export const handler = createHandler(() => import('./index'))
|
|
577
|
+
* ```
|
|
578
|
+
*
|
|
579
|
+
* While the entry loads, its `bootstrap()` call builds the app without
|
|
580
|
+
* starting it — no port, no process signal handlers, no cluster. The app is set up once per process
|
|
581
|
+
* (per function instance), lazily on the first request, and reused after that.
|
|
582
|
+
* Nothing listens on a port, `afterStart` does not run, and no process signal
|
|
583
|
+
* handlers are registered — the platform owns the process.
|
|
584
|
+
*
|
|
585
|
+
* `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).
|
|
586
|
+
* Runtimes built on Node request/response objects — Express, the default —
|
|
587
|
+
* are served through a server bound to `127.0.0.1` on a random port inside the
|
|
588
|
+
* same process, started on first use: the `Request` is forwarded to it and its
|
|
589
|
+
* response returned. Request bodies are buffered on that path; response bodies
|
|
590
|
+
* stream. Adapters that rewrite the `res` prototype (Express does) make a
|
|
591
|
+
* direct Request→`res` bridge unreliable, which is why this forwards instead.
|
|
592
|
+
*
|
|
593
|
+
* One handler per process: the DI container is process-wide.
|
|
594
|
+
*
|
|
595
|
+
* @example
|
|
596
|
+
* ```ts
|
|
597
|
+
* // server/src/serverless.ts
|
|
598
|
+
* import 'reflect-metadata'
|
|
599
|
+
* import './config'
|
|
600
|
+
* import { createHandler } from '@forinda/kickjs'
|
|
601
|
+
* import { modules } from './modules'
|
|
602
|
+
*
|
|
603
|
+
* export const handler = createHandler({ modules })
|
|
604
|
+
*
|
|
605
|
+
* // netlify/functions/api.mjs
|
|
606
|
+
* export default (request, context) => handler.fetch(request, context)
|
|
607
|
+
* export const config = { path: '/api/*' }
|
|
608
|
+
* ```
|
|
609
|
+
*/
|
|
610
|
+
declare function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler;
|
|
611
|
+
//#endregion
|
|
612
|
+
//#region src/http/cluster.d.ts
|
|
613
|
+
interface ClusterOptions {
|
|
614
|
+
/** Number of worker processes (default: os.cpus().length) */
|
|
615
|
+
workers?: number;
|
|
616
|
+
/** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */
|
|
617
|
+
gracefulShutdownTimeout?: number;
|
|
618
|
+
/** Delay between worker restarts (ms), default: 1000 */
|
|
619
|
+
restartDelay?: number;
|
|
620
|
+
/** Max failures in restartWindow before refusing to restart, default: 5 */
|
|
621
|
+
maxFailures?: number;
|
|
622
|
+
/** Time window for counting failures (ms), default: 30000 */
|
|
623
|
+
restartWindow?: number;
|
|
624
|
+
}
|
|
625
|
+
/** Returns true if the current process is the cluster primary */
|
|
626
|
+
declare function isClusterPrimary(): boolean;
|
|
627
|
+
//#endregion
|
|
628
|
+
//#region src/http/define-http-context-decorator.d.ts
|
|
629
|
+
/**
|
|
630
|
+
* Curried form returned by {@link DefineHttpContextDecoratorFn.withParams}.
|
|
631
|
+
* Spell only the per-call params shape `P`; `K` and `D` are inferred
|
|
632
|
+
* from the spec, and `Ctx` is locked to `RequestContext`.
|
|
633
|
+
*/
|
|
634
|
+
interface DefineHttpContextDecoratorWithParams<P extends Record<string, unknown>> {
|
|
635
|
+
<K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext>;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Public shape of {@link defineHttpContextDecorator} — the positional
|
|
639
|
+
* call signature plus the curried `.withParams<P>()` helper that fixes
|
|
640
|
+
* partial-inference for the parameterised case.
|
|
641
|
+
*/
|
|
642
|
+
interface DefineHttpContextDecoratorFn {
|
|
643
|
+
<K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>, P extends Record<string, unknown> = Record<string, never>>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext>;
|
|
644
|
+
/**
|
|
645
|
+
* Curried entry point. Spell only `P`; `K` and `D` infer from the
|
|
646
|
+
* spec. `Ctx` is locked to `RequestContext`.
|
|
647
|
+
*
|
|
648
|
+
* ```ts
|
|
649
|
+
* const LoadTenant = defineHttpContextDecorator.withParams<{
|
|
650
|
+
* source: 'header' | 'subdomain'
|
|
651
|
+
* }>()({
|
|
652
|
+
* key: 'tenant',
|
|
653
|
+
* deps: { repo: TENANT_REPO }, // D inferred
|
|
654
|
+
* paramDefaults: { source: 'header' },
|
|
655
|
+
* resolve: (ctx, { repo }, params) => repo.findFor(ctx, params),
|
|
656
|
+
* })
|
|
657
|
+
* ```
|
|
658
|
+
*/
|
|
659
|
+
withParams<P extends Record<string, unknown>>(): DefineHttpContextDecoratorWithParams<P>;
|
|
660
|
+
}
|
|
661
|
+
declare const defineHttpContextDecorator: DefineHttpContextDecoratorFn;
|
|
662
|
+
//#endregion
|
|
663
|
+
//#region src/core/password.d.ts
|
|
664
|
+
/** scrypt cost. Memory per hash is `128 * N * r` bytes. */
|
|
665
|
+
interface PasswordHashOptions {
|
|
666
|
+
/** CPU/memory cost, a power of two. Default `2 ** 14`. */
|
|
667
|
+
N?: number;
|
|
668
|
+
/** Block size. Default `8`. */
|
|
669
|
+
r?: number;
|
|
670
|
+
/** Parallelism. Default `5`. */
|
|
671
|
+
p?: number;
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Hash a password for storage: `scrypt$N$r$p$salt$hash`, salt and hash in
|
|
675
|
+
* base64. The same password hashes differently every time.
|
|
676
|
+
*/
|
|
677
|
+
declare function hashPassword(password: string, options?: PasswordHashOptions): Promise<string>;
|
|
678
|
+
/** What {@link verifyPassword} returns. */
|
|
679
|
+
interface PasswordCheck {
|
|
680
|
+
/** The password matches. */
|
|
681
|
+
ok: boolean;
|
|
682
|
+
/**
|
|
683
|
+
* The hash was made with a different cost than `options` (the defaults):
|
|
684
|
+
* hash the password again and store it. Only ever true when `ok` is.
|
|
685
|
+
*/
|
|
686
|
+
needsRehash: boolean;
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* A hash format from before scrypt — bcrypt or argon2 rows imported from
|
|
690
|
+
* another system. It still verifies; on success `needsRehash` is true, so the
|
|
691
|
+
* account moves to scrypt at its next login.
|
|
692
|
+
*
|
|
693
|
+
* ```ts
|
|
694
|
+
* import bcrypt from 'bcrypt'
|
|
695
|
+
* const bcryptHashes: LegacyHasher = {
|
|
696
|
+
* matches: (stored) => /^\$2[aby]\$/.test(stored),
|
|
697
|
+
* verify: (password, stored) => bcrypt.compare(password, stored),
|
|
698
|
+
* dummy: await bcrypt.hash('dummy', 12), // the cost your rows use
|
|
699
|
+
* }
|
|
700
|
+
* await verifyPassword(input, user?.passwordHash, { legacy: [bcryptHashes] })
|
|
701
|
+
* ```
|
|
702
|
+
*/
|
|
703
|
+
interface LegacyHasher {
|
|
704
|
+
/** Whether `stored` is in this format — by prefix (`$2b$` for bcrypt, `$argon2id$`). */
|
|
705
|
+
matches(stored: string): boolean;
|
|
706
|
+
/** Whether `password` matches `stored`: the library's own check. */
|
|
707
|
+
verify(password: string, stored: string): boolean | Promise<boolean>;
|
|
708
|
+
/**
|
|
709
|
+
* A hash in this format, of any password, at the cost the rows it
|
|
710
|
+
* `matches` use. Every check runs scrypt once and each legacy hasher once —
|
|
711
|
+
* against this when the account isn't in its format — so a login takes as
|
|
712
|
+
* long for a scrypt account, an imported one or a missing one, and timing
|
|
713
|
+
* can't tell them apart. Rows at several costs: one hasher per cost, each
|
|
714
|
+
* matching its own (bcrypt's `$2b$10$` vs `$2b$12$`) with a dummy at that
|
|
715
|
+
* cost; every login then runs all of them and takes the slowest's time.
|
|
716
|
+
*/
|
|
717
|
+
dummy: string;
|
|
718
|
+
}
|
|
719
|
+
/** {@link verifyPassword}'s options: the scrypt cost, and older formats that still verify. */
|
|
720
|
+
interface VerifyPasswordOptions extends PasswordHashOptions {
|
|
721
|
+
/** Formats besides scrypt, tried in order on a hash scrypt can't read. */
|
|
722
|
+
legacy?: readonly LegacyHasher[];
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Check a password against a stored hash. Constant-time, and pass
|
|
726
|
+
* `undefined` for a user that doesn't exist: the password is still hashed,
|
|
727
|
+
* so a missing account takes as long to reject as a wrong password and the
|
|
728
|
+
* timing doesn't reveal which accounts exist. A hash not in this format
|
|
729
|
+
* (another algorithm, or corrupt) fails rather than throws, unless one of
|
|
730
|
+
* `options.legacy` reads it.
|
|
731
|
+
*/
|
|
732
|
+
declare function verifyPassword(password: string, stored: string | null | undefined, options?: VerifyPasswordOptions): Promise<PasswordCheck>;
|
|
733
|
+
//#endregion
|
|
734
|
+
//#region src/core/signing.d.ts
|
|
735
|
+
interface SignerOptions {
|
|
736
|
+
/**
|
|
737
|
+
* The signing secret. Pass a list to rotate: the first signs, every one
|
|
738
|
+
* verifies. Drop the old one once its tokens have expired.
|
|
739
|
+
*/
|
|
740
|
+
secret: string | string[];
|
|
741
|
+
/**
|
|
742
|
+
* What the tokens are for — `'password-reset'`, `'unsubscribe'`. Signers
|
|
743
|
+
* with different salts reject each other's tokens even with the same
|
|
744
|
+
* secret, so a token issued for one purpose can't be used for another.
|
|
745
|
+
*/
|
|
746
|
+
salt: string;
|
|
747
|
+
}
|
|
748
|
+
interface VerifyOptions {
|
|
749
|
+
/** Reject tokens older than this, in milliseconds. */
|
|
750
|
+
maxAge?: number;
|
|
751
|
+
}
|
|
752
|
+
/** What {@link Signer.verify} returns. */
|
|
753
|
+
type SignedCheck<T> = {
|
|
754
|
+
ok: true;
|
|
755
|
+
value: T;
|
|
756
|
+
issuedAt: Date;
|
|
757
|
+
} | {
|
|
758
|
+
ok: false;
|
|
759
|
+
reason: 'invalid' | 'expired';
|
|
760
|
+
};
|
|
761
|
+
interface Signer {
|
|
762
|
+
/** Sign a JSON-serialisable value: `payload.timestamp.signature`, URL-safe. */
|
|
763
|
+
sign(value: unknown): string;
|
|
764
|
+
/** Check a token's signature and, with `maxAge`, its age. Never throws. */
|
|
765
|
+
verify<T = unknown>(token: string, options?: VerifyOptions): SignedCheck<T>;
|
|
766
|
+
}
|
|
767
|
+
/** Create a signer for one purpose. */
|
|
768
|
+
declare function createSigner(options: SignerOptions): Signer;
|
|
769
|
+
//#endregion
|
|
770
|
+
//#region src/http/runtimes/express.d.ts
|
|
771
|
+
/**
|
|
772
|
+
* Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.
|
|
773
|
+
* Reproduces the legacy handler ordering precisely: validation → upload →
|
|
774
|
+
* `(ctx, next)` middleware → contributor runner → terminal handler, with
|
|
775
|
+
* `beforeValidation` contributors ahead of validation. Each step
|
|
776
|
+
* constructs its own `RequestContext` over the same `req`/`res` — request-scoped
|
|
777
|
+
* state lives in the AsyncLocalStorage store, not on the ctx instance, so the
|
|
778
|
+
* per-step instances share state exactly as before.
|
|
779
|
+
*/
|
|
780
|
+
declare function materializeRouter(entries: RouteEntry[]): Router;
|
|
781
|
+
/**
|
|
782
|
+
* Build an Express Router from a controller class decorated with @Get, @Post,
|
|
783
|
+
* etc. The public, back-compatible entry point: a thin shim over
|
|
784
|
+
* {@link buildRouteTable} + {@link materializeRouter}. Returns an
|
|
785
|
+
* `express.Router` exactly as before — modules pass it to `app.use(path, router)`.
|
|
786
|
+
*
|
|
787
|
+
* @see buildRouteTable for the engine-neutral route-table form.
|
|
788
|
+
*/
|
|
789
|
+
declare function buildRoutes(controllerClass: any, options?: BuildRoutesOptions): Router;
|
|
790
|
+
/**
|
|
791
|
+
* The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;
|
|
792
|
+
* apps that pass no `runtime` get this and behave exactly as before.
|
|
793
|
+
*/
|
|
794
|
+
declare function expressRuntime(): HttpRuntime<Express>;
|
|
795
|
+
//#endregion
|
|
796
|
+
//#region src/http/request-store.d.ts
|
|
797
|
+
/** Per-request storage for REQUEST-scoped DI and request context propagation */
|
|
798
|
+
interface RequestStore {
|
|
799
|
+
/** Unique request identifier */
|
|
800
|
+
requestId: string;
|
|
801
|
+
/**
|
|
802
|
+
* Per-request singleton cache for REQUEST-scoped services. Keys are
|
|
803
|
+
* heterogeneous (class constructors, `InjectionToken` objects, raw
|
|
804
|
+
* strings), so the map type stays `Map<any, any>`.
|
|
805
|
+
*/
|
|
806
|
+
instances: Map<any, any>;
|
|
807
|
+
/**
|
|
808
|
+
* Per-request key/value bag. Canonical backing store for
|
|
809
|
+
* `RequestContext.set/get` and the Context Contributor pipeline (#107)
|
|
810
|
+
* since Phase 3. Anything written here is visible to every concrete
|
|
811
|
+
* execution context constructed for the same request, regardless of
|
|
812
|
+
* which middleware/contributor wrote it.
|
|
813
|
+
*
|
|
814
|
+
* Keys are constrained to `string` per the locked decision in
|
|
815
|
+
* `architecture.md` §20.12 (#4); the value type is `unknown` because
|
|
816
|
+
* the concrete shape at each key is determined by the consumer's
|
|
817
|
+
* `ContextMeta` augmentation, not by the store itself.
|
|
818
|
+
*
|
|
819
|
+
* Prefer the {@link getRequestValue} helper over reaching into this
|
|
820
|
+
* map directly — it threads the augmented `ContextMeta` shape through
|
|
821
|
+
* `MetaValue<K>` so consumers get typed reads without an `as` cast.
|
|
822
|
+
* Writes should flow through `ctx.set(key, value)` or a Context
|
|
823
|
+
* Contributor's return value — see the `setRequestValue` note below
|
|
824
|
+
* for why this package intentionally does NOT ship a service-level
|
|
825
|
+
* write helper.
|
|
826
|
+
*/
|
|
827
|
+
values: Map<string, unknown>;
|
|
828
|
+
/** Set once {@link disposeRequestStore} has run — guards double-dispose. */
|
|
829
|
+
disposed?: boolean;
|
|
830
|
+
}
|
|
831
|
+
/** AsyncLocalStorage instance shared across the framework */
|
|
832
|
+
declare const requestStore: AsyncLocalStorage<RequestStore>;
|
|
833
|
+
/**
|
|
834
|
+
* Get the current request store. Throws if called outside a request context.
|
|
835
|
+
* Used by the Container to resolve REQUEST-scoped dependencies.
|
|
836
|
+
*/
|
|
837
|
+
declare function getRequestStore(): RequestStore;
|
|
838
|
+
/**
|
|
839
|
+
* Read a per-request `ContextMeta`-keyed value from outside a controller
|
|
840
|
+
* (services, repositories, anywhere with no `ctx` reference). Returns
|
|
841
|
+
* the augmented type for the key — `MetaValue<K>` — so consumers get the
|
|
842
|
+
* same static safety as `ctx.get(key)` without holding the context.
|
|
843
|
+
*
|
|
844
|
+
* Returns `undefined` outside an active request frame (background jobs,
|
|
845
|
+
* startup code, tests without `requestScopeMiddleware()`) — the helper
|
|
846
|
+
* is intentionally null-tolerant so calling it from a service that
|
|
847
|
+
* runs in both request and non-request paths doesn't throw.
|
|
848
|
+
*
|
|
849
|
+
* @example
|
|
850
|
+
* ```ts
|
|
851
|
+
* declare module '@forinda/kickjs' {
|
|
852
|
+
* interface ContextMeta { tenant: { id: string; name: string } }
|
|
853
|
+
* }
|
|
854
|
+
*
|
|
855
|
+
* @Service()
|
|
856
|
+
* class AuditService {
|
|
857
|
+
* log(action: string) {
|
|
858
|
+
* const tenant = getRequestValue('tenant') // typed: { id; name } | undefined
|
|
859
|
+
* db.audit.insert({ action, tenantId: tenant?.id })
|
|
860
|
+
* }
|
|
861
|
+
* }
|
|
862
|
+
* ```
|
|
863
|
+
*/
|
|
864
|
+
declare function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined;
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/http/middleware/request-scope.d.ts
|
|
867
|
+
/**
|
|
868
|
+
* Wraps each request in an AsyncLocalStorage context.
|
|
869
|
+
* Enables REQUEST-scoped DI and automatic requestId propagation to logs.
|
|
870
|
+
*
|
|
871
|
+
* Should be mounted early in the middleware pipeline (before route handlers).
|
|
872
|
+
* `Application` mounts this automatically unless `contextStore: 'manual'` is set
|
|
873
|
+
* or the user already includes one in their middleware list.
|
|
874
|
+
*/
|
|
875
|
+
declare function requestScopeMiddleware(): (req: Request$1, res: Response$1, next: NextFunction) => void;
|
|
876
|
+
//#endregion
|
|
877
|
+
//#region src/http/middleware/trace-context.d.ts
|
|
878
|
+
/**
|
|
879
|
+
* W3C Trace Context header name.
|
|
880
|
+
* @see https://www.w3.org/TR/trace-context/#traceparent-header
|
|
881
|
+
*/
|
|
882
|
+
declare const TRACEPARENT_HEADER = "traceparent";
|
|
883
|
+
interface TraceContextOptions {
|
|
884
|
+
/**
|
|
885
|
+
* When true, respond with a `traceresponse` header containing the trace ID.
|
|
886
|
+
* Useful for debugging. Default: false.
|
|
887
|
+
*/
|
|
888
|
+
propagateResponse?: boolean;
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Parsed W3C trace context fields.
|
|
892
|
+
*/
|
|
893
|
+
interface TraceContext {
|
|
894
|
+
/** W3C traceparent version (usually '00') */
|
|
895
|
+
version: string;
|
|
896
|
+
/** 32-hex-char distributed trace ID */
|
|
897
|
+
traceId: string;
|
|
898
|
+
/** 16-hex-char parent span ID */
|
|
899
|
+
parentSpanId: string;
|
|
900
|
+
/** 2-hex-char trace flags */
|
|
901
|
+
flags: string;
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Parse a W3C traceparent header value.
|
|
905
|
+
* Returns null if the format is invalid.
|
|
906
|
+
*/
|
|
907
|
+
declare function parseTraceparent(header: string): TraceContext | null;
|
|
908
|
+
/**
|
|
909
|
+
* Middleware that extracts W3C `traceparent` header and stores trace context
|
|
910
|
+
* in the request's AsyncLocalStorage store.
|
|
911
|
+
*
|
|
912
|
+
* If no valid `traceparent` header is present, a new traceId is generated
|
|
913
|
+
* so that every request always has a trace ID available for correlation.
|
|
914
|
+
*
|
|
915
|
+
* Must be mounted **after** `requestScopeMiddleware()` (which creates the store).
|
|
916
|
+
*
|
|
917
|
+
* @example
|
|
918
|
+
* ```ts
|
|
919
|
+
* bootstrap({
|
|
920
|
+
* middlewares: [
|
|
921
|
+
* requestScopeMiddleware(),
|
|
922
|
+
* traceContext(), // extracts or generates traceId
|
|
923
|
+
* requestLogger(),
|
|
924
|
+
* express.json(),
|
|
925
|
+
* ],
|
|
926
|
+
* })
|
|
927
|
+
* ```
|
|
928
|
+
*/
|
|
929
|
+
declare function traceContext(options?: TraceContextOptions): (req: Request$1, res: Response$1, next: NextFunction) => void;
|
|
930
|
+
//#endregion
|
|
931
|
+
//#region src/http/middleware/views.d.ts
|
|
932
|
+
interface ViewAdapterOptions {
|
|
933
|
+
/**
|
|
934
|
+
* Template engine — pass the engine module or a render function.
|
|
935
|
+
* Supported engines: ejs, pug, handlebars, nunjucks, or any
|
|
936
|
+
* Express-compatible engine with a __express property.
|
|
937
|
+
*
|
|
938
|
+
* @example
|
|
939
|
+
* ```ts
|
|
940
|
+
* import ejs from 'ejs'
|
|
941
|
+
* ViewAdapter({ engine: ejs, ext: 'ejs' })
|
|
942
|
+
*
|
|
943
|
+
* import pug from 'pug'
|
|
944
|
+
* ViewAdapter({ engine: pug, ext: 'pug' })
|
|
945
|
+
* ```
|
|
946
|
+
*/
|
|
947
|
+
engine: any;
|
|
948
|
+
/** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */
|
|
949
|
+
ext: string;
|
|
950
|
+
/**
|
|
951
|
+
* Directory containing template files (default: 'src/views'), relative to
|
|
952
|
+
* the project. Also looked up beside the running entry file, where
|
|
953
|
+
* `copyDirs: ['src/views']` puts it in a build (`dist/src/views`), so a
|
|
954
|
+
* deployment holding only `dist/` still finds it.
|
|
955
|
+
*/
|
|
956
|
+
viewsDir?: string;
|
|
957
|
+
/** Default layout template (optional — depends on engine) */
|
|
958
|
+
layout?: string;
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* View/template adapter — pluggable template engine support for KickJS.
|
|
962
|
+
*
|
|
963
|
+
* Registers an Express view engine and sets the views directory.
|
|
964
|
+
* Use `ctx.render()` in controllers to render templates.
|
|
965
|
+
*
|
|
966
|
+
* Migrated to the `defineAdapter()` factory in v4 — call without `new`.
|
|
967
|
+
* The pre-v4 `new ViewAdapter({...})` form is gone; see
|
|
968
|
+
* `docs/guide/migration-v3-to-v4.md` for the rename.
|
|
969
|
+
*
|
|
970
|
+
* @example
|
|
971
|
+
* ```ts
|
|
972
|
+
* import ejs from 'ejs'
|
|
973
|
+
* import { ViewAdapter } from '@forinda/kickjs'
|
|
974
|
+
*
|
|
975
|
+
* bootstrap({
|
|
976
|
+
* modules,
|
|
977
|
+
* adapters: [
|
|
978
|
+
* ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),
|
|
979
|
+
* ],
|
|
980
|
+
* })
|
|
981
|
+
*
|
|
982
|
+
* // In a controller:
|
|
983
|
+
* @Get('/dashboard')
|
|
984
|
+
* async dashboard(ctx: RequestContext) {
|
|
985
|
+
* ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })
|
|
986
|
+
* }
|
|
987
|
+
* ```
|
|
988
|
+
*/
|
|
989
|
+
declare const ViewAdapter: AdapterFactory<ViewAdapterOptions, unknown>;
|
|
990
|
+
/**
|
|
991
|
+
* Where to look for `viewsDir`: the project — `KICK_APP_ROOT` when set (the
|
|
992
|
+
* Netlify and Vercel functions `kick build:*` writes set it to where
|
|
993
|
+
* `deploy.include` files land), else the working directory — then beside the
|
|
994
|
+
* running entry file (`node dist/index.js` → `dist/<viewsDir>`, where
|
|
995
|
+
* `copyDirs` copies it). Express tries them in order.
|
|
996
|
+
*/
|
|
997
|
+
declare function viewDirs(viewsDir: string): string[];
|
|
998
|
+
//#endregion
|
|
999
|
+
//#region src/http/middleware/spa.d.ts
|
|
1000
|
+
interface SpaAdapterOptions {
|
|
1001
|
+
/**
|
|
1002
|
+
* Directory containing the built SPA files (index.html, assets, etc.)
|
|
1003
|
+
* Default: 'dist/client'
|
|
1004
|
+
*
|
|
1005
|
+
* @example
|
|
1006
|
+
* ```ts
|
|
1007
|
+
* // Vue: 'dist'
|
|
1008
|
+
* // React (Vite): 'dist'
|
|
1009
|
+
* // React (CRA): 'build'
|
|
1010
|
+
* // Svelte: 'build'
|
|
1011
|
+
* // Angular: 'dist/my-app/browser'
|
|
1012
|
+
* ```
|
|
1013
|
+
*/
|
|
1014
|
+
clientDir?: string;
|
|
1015
|
+
/**
|
|
1016
|
+
* URL prefix for API routes. SPA fallback only applies to
|
|
1017
|
+
* non-API routes (routes NOT starting with this prefix).
|
|
1018
|
+
* Default: '/api'
|
|
1019
|
+
*
|
|
1020
|
+
* Matching is segment-aware: `/api` excludes `/api` and `/api/users`, but
|
|
1021
|
+
* NOT `/apidocs` — a plain `startsWith` swallowed any path that merely
|
|
1022
|
+
* began with the same letters.
|
|
1023
|
+
*
|
|
1024
|
+
* Set to an array for multiple prefixes:
|
|
1025
|
+
* ```ts
|
|
1026
|
+
* apiPrefix: ['/api', '/graphql', '/_debug']
|
|
1027
|
+
* ```
|
|
1028
|
+
*/
|
|
1029
|
+
apiPrefix?: string | string[];
|
|
1030
|
+
/**
|
|
1031
|
+
* Additional paths to exclude from SPA fallback.
|
|
1032
|
+
* These paths will NOT serve index.html. Segment-aware, like `apiPrefix`.
|
|
1033
|
+
*
|
|
1034
|
+
* @example
|
|
1035
|
+
* ```ts
|
|
1036
|
+
* exclude: ['/health', '/metrics', '/ws']
|
|
1037
|
+
* ```
|
|
1038
|
+
*/
|
|
1039
|
+
exclude?: string[];
|
|
1040
|
+
/**
|
|
1041
|
+
* Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')
|
|
1042
|
+
* Set to false to disable caching headers.
|
|
1043
|
+
*/
|
|
1044
|
+
cacheControl?: string | false;
|
|
1045
|
+
/**
|
|
1046
|
+
* Cache-Control for index.html (default: 'no-cache')
|
|
1047
|
+
* index.html should not be cached to ensure clients get fresh builds.
|
|
1048
|
+
*/
|
|
1049
|
+
indexCacheControl?: string;
|
|
1050
|
+
/**
|
|
1051
|
+
* Serve index.html even when the client did not ask for HTML.
|
|
1052
|
+
* Default: false.
|
|
1053
|
+
*
|
|
1054
|
+
* By default the fallback only fires for requests whose `Accept` header
|
|
1055
|
+
* includes `text/html` — the rule `connect-history-api-fallback` uses. That
|
|
1056
|
+
* keeps a missing `/assets/app.js` a 404 instead of handing back an HTML
|
|
1057
|
+
* document that the browser then fails to parse as JavaScript, which is a
|
|
1058
|
+
* confusing way to discover a broken build.
|
|
1059
|
+
*
|
|
1060
|
+
* Turn this on if you have non-browser clients that deep-link into SPA
|
|
1061
|
+
* routes without an `Accept` header.
|
|
1062
|
+
*/
|
|
1063
|
+
alwaysFallback?: boolean;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Where to look for the built SPA.
|
|
1067
|
+
*
|
|
1068
|
+
* `process.cwd()` is the framework's convention (assets and env files resolve
|
|
1069
|
+
* the same way) and stays the primary base. But a relative `clientDir` then
|
|
1070
|
+
* only works when the process happens to be started from the app directory —
|
|
1071
|
+
* `node server/dist/index.js` run from a monorepo root resolved `../web/dist`
|
|
1072
|
+
* against the root and found nothing, serving no SPA with only a warning.
|
|
1073
|
+
*
|
|
1074
|
+
* So: try cwd first, and only if that misses, retry against the package root
|
|
1075
|
+
* of the entry script. Both are checked for existence before being chosen, so
|
|
1076
|
+
* this can never silently pick a directory that is not there — a genuinely
|
|
1077
|
+
* missing build still lands on the cwd path, which is what the warning names.
|
|
1078
|
+
*
|
|
1079
|
+
* Deliberately not entry-relative FIRST: under `kick dev` the entry is the CLI
|
|
1080
|
+
* binary, whose package root is the CLI itself.
|
|
1081
|
+
*
|
|
1082
|
+
* Exported for tests only — not re-exported from the package index.
|
|
1083
|
+
*/
|
|
1084
|
+
declare function resolveClientDir(clientDir: string, cwd?: string, entry?: string | undefined): string;
|
|
1085
|
+
/**
|
|
1086
|
+
* SPA adapter — serve a Vue, React, Svelte, or Angular build alongside
|
|
1087
|
+
* your KickJS API. API routes are handled by controllers; everything else
|
|
1088
|
+
* falls back to index.html for client-side routing.
|
|
1089
|
+
*
|
|
1090
|
+
* Written against the engine-agnostic `http` surface (`serveStatic` / `use`),
|
|
1091
|
+
* so it runs under Express, Fastify, and h3 alike. The previous version
|
|
1092
|
+
* reached for `express.static`, `req.path`, and `res.send`, all of which are
|
|
1093
|
+
* Express-only — it silently served nothing on the other runtimes.
|
|
1094
|
+
*
|
|
1095
|
+
* Migrated to the `defineAdapter()` factory — call without `new`, as
|
|
1096
|
+
* `ViewAdapter` has since v4.
|
|
1097
|
+
*
|
|
1098
|
+
* @example
|
|
1099
|
+
* ```ts
|
|
1100
|
+
* import { SpaAdapter } from '@forinda/kickjs/spa'
|
|
1101
|
+
*
|
|
1102
|
+
* bootstrap({
|
|
1103
|
+
* modules,
|
|
1104
|
+
* adapters: [
|
|
1105
|
+
* SpaAdapter({
|
|
1106
|
+
* clientDir: 'dist/client', // or 'build', 'dist', etc.
|
|
1107
|
+
* apiPrefix: '/api',
|
|
1108
|
+
* }),
|
|
1109
|
+
* ],
|
|
1110
|
+
* })
|
|
1111
|
+
* ```
|
|
1112
|
+
*
|
|
1113
|
+
* File structure:
|
|
1114
|
+
* ```
|
|
1115
|
+
* dist/
|
|
1116
|
+
* client/ ← SPA build output
|
|
1117
|
+
* index.html
|
|
1118
|
+
* assets/
|
|
1119
|
+
* app.js
|
|
1120
|
+
* style.css
|
|
1121
|
+
* server/ ← KickJS server
|
|
1122
|
+
* ```
|
|
1123
|
+
*/
|
|
1124
|
+
declare const SpaAdapter: AdapterFactory<SpaAdapterOptions, unknown>;
|
|
1125
|
+
//#endregion
|
|
1126
|
+
//#region src/http/health-module.d.ts
|
|
1127
|
+
/** One adapter's answer to `onHealthCheck()`. */
|
|
1128
|
+
interface HealthCheckResult {
|
|
1129
|
+
name: string;
|
|
1130
|
+
status: 'up' | 'down';
|
|
1131
|
+
/** Why a check counts as down when it didn't answer for itself. */
|
|
1132
|
+
reason?: 'timeout' | 'error';
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* What the health routes need from the running Application.
|
|
1136
|
+
*
|
|
1137
|
+
* A controller cannot reach `Application` internals, and should not: this is
|
|
1138
|
+
* the whole surface the endpoints depend on, so a replacement module can
|
|
1139
|
+
* satisfy it without knowing anything else.
|
|
1140
|
+
*/
|
|
1141
|
+
interface HealthProbe {
|
|
1142
|
+
/** True once shutdown has begun and traffic should drain away. */
|
|
1143
|
+
isDraining(): boolean;
|
|
1144
|
+
/** Aggregated `onHealthCheck()` results from every adapter that has one. */
|
|
1145
|
+
checks(): Promise<HealthCheckResult[]>;
|
|
1146
|
+
}
|
|
1147
|
+
declare const HEALTH_PROBE: import("@forinda/kickjs-di").InjectionToken<HealthProbe>;
|
|
1148
|
+
/** Config for {@link healthModule}. */
|
|
1149
|
+
interface HealthModuleConfig {
|
|
1150
|
+
/**
|
|
1151
|
+
* Route flags to put on `GET /health/live` and `GET /health/ready`.
|
|
1152
|
+
*
|
|
1153
|
+
* The framework names no flags, so it cannot decide these probes are
|
|
1154
|
+
* "public" on your behalf — the name is yours, and every consumer that
|
|
1155
|
+
* already reads it (an auth contributor's `skipWhen`, a guard's
|
|
1156
|
+
* `exemptWhen`, `SwaggerAdapter({ publicFlag })`) then covers health with no
|
|
1157
|
+
* further wiring:
|
|
1158
|
+
*
|
|
1159
|
+
* ```ts
|
|
1160
|
+
* bootstrap({ health: { flags: ['auth.public'] } })
|
|
1161
|
+
* ```
|
|
1162
|
+
*
|
|
1163
|
+
* This replaces exempting `/health/live` and `/health/ready` by pathname,
|
|
1164
|
+
* which silently stops matching if the probe paths ever move.
|
|
1165
|
+
*/
|
|
1166
|
+
flags?: RouteFlagDeclarations;
|
|
1167
|
+
/**
|
|
1168
|
+
* Milliseconds each `onHealthCheck()` gets before it counts as down
|
|
1169
|
+
* (`reason: 'timeout'`). Default 2000. Keeps one hung dependency from
|
|
1170
|
+
* hanging the probe itself, which the orchestrator would then time out.
|
|
1171
|
+
*/
|
|
1172
|
+
checkTimeout?: number;
|
|
1173
|
+
}
|
|
1174
|
+
declare class HealthController {
|
|
1175
|
+
private readonly probe;
|
|
1176
|
+
constructor(probe: HealthProbe);
|
|
1177
|
+
/**
|
|
1178
|
+
* Liveness: is the process up. Stays 200 while draining — an orchestrator
|
|
1179
|
+
* restarts a container whose liveness fails, which would kill a graceful
|
|
1180
|
+
* shutdown partway through. Readiness is what turns traffic away.
|
|
1181
|
+
*/
|
|
1182
|
+
live(): Reply<200, {
|
|
1183
|
+
status: string;
|
|
1184
|
+
uptime: number;
|
|
1185
|
+
}>;
|
|
1186
|
+
/** Readiness: is every adapter's dependency answering. */
|
|
1187
|
+
ready(): Promise<Reply<200 | 503, {
|
|
1188
|
+
status: string;
|
|
1189
|
+
checks: HealthCheckResult[];
|
|
1190
|
+
}>>;
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* `GET /health/live` and `GET /health/ready`, mounted at the root.
|
|
1194
|
+
*
|
|
1195
|
+
* A `defineModule` factory like any other module — the framework's own routes
|
|
1196
|
+
* should be declared the way it asks adopters to declare theirs, not through a
|
|
1197
|
+
* shape only the framework can produce.
|
|
1198
|
+
*
|
|
1199
|
+
* Registered automatically unless the app passes `health: false` or supplies a
|
|
1200
|
+
* module of its own. Pass `health: { flags: [...] }` to `bootstrap()` to flag
|
|
1201
|
+
* both probes — see {@link HealthModuleConfig}.
|
|
1202
|
+
*/
|
|
1203
|
+
declare const healthModule: ModuleFactory<HealthModuleConfig, unknown>;
|
|
1204
|
+
//#endregion
|
|
1205
|
+
//#region src/http/application.d.ts
|
|
1206
|
+
/**
|
|
1207
|
+
* A middleware entry in the declarative pipeline.
|
|
1208
|
+
* Can be a bare handler or an object with path scoping.
|
|
1209
|
+
*/
|
|
1210
|
+
type MiddlewareEntry = RequestHandler | {
|
|
1211
|
+
path: string;
|
|
1212
|
+
handler: RequestHandler;
|
|
1213
|
+
};
|
|
1214
|
+
/** Options for {@link Application.shutdown}. */
|
|
1215
|
+
interface ShutdownOptions {
|
|
1216
|
+
/**
|
|
1217
|
+
* Close the HTTP server and drain in-flight requests. Default `true`.
|
|
1218
|
+
*
|
|
1219
|
+
* Set `false` for a dev HMR rebuild, where the server is shared across
|
|
1220
|
+
* reloads — adapters, plugins, and disposables are still torn down, which is
|
|
1221
|
+
* the part a reload needs.
|
|
1222
|
+
*/
|
|
1223
|
+
closeServer?: boolean;
|
|
1224
|
+
}
|
|
1225
|
+
/** See {@link ApplicationOptions.server}. */
|
|
1226
|
+
interface ServerOptions {
|
|
1227
|
+
/** TLS credentials and options (`key`, `cert`, `ca`, `pfx`, `passphrase`, …). */
|
|
1228
|
+
tls?: tls.SecureContextOptions & tls.TlsOptions;
|
|
1229
|
+
/** Serve HTTP/2 with HTTP/1.1 fallback. Requires `tls` and an HTTP/2-capable runtime. */
|
|
1230
|
+
http2?: boolean;
|
|
1231
|
+
/**
|
|
1232
|
+
* Milliseconds an idle keep-alive connection stays open. Default 65000.
|
|
1233
|
+
* Keep it ABOVE your load balancer's idle timeout (AWS ALB: 60s): when the
|
|
1234
|
+
* server closes a connection the balancer is about to reuse, that request
|
|
1235
|
+
* fails with a 502. Node's own default is 5s.
|
|
1236
|
+
*/
|
|
1237
|
+
keepAliveTimeout?: number;
|
|
1238
|
+
/** Milliseconds to receive the request headers. Default `keepAliveTimeout + 1000`. */
|
|
1239
|
+
headersTimeout?: number;
|
|
1240
|
+
/** Milliseconds to receive the whole request. Default 300000; 0 disables. */
|
|
1241
|
+
requestTimeout?: number;
|
|
1242
|
+
}
|
|
1243
|
+
/** A mounted controller route, as `app.getRoutes()` lists it. */
|
|
1244
|
+
interface MountedRouteInfo {
|
|
1245
|
+
method: string;
|
|
1246
|
+
/** Full pattern, prefix and version included: `/api/v1/users/:id`. */
|
|
1247
|
+
pattern: string;
|
|
1248
|
+
controller: string;
|
|
1249
|
+
handler: string;
|
|
1250
|
+
/** Context contributors in execution order, with where each was registered. */
|
|
1251
|
+
contributors: readonly RouteContributor[];
|
|
1252
|
+
}
|
|
1253
|
+
/** What `app.describeConfig()` returns. */
|
|
1254
|
+
interface ConfigDescription {
|
|
1255
|
+
/** The app's env schema (`loadEnv` / `loadEnvFromSchema`), or the base schema. */
|
|
1256
|
+
env: ConfigVar[];
|
|
1257
|
+
/** Declared settings sections, in declaration order, each once. */
|
|
1258
|
+
sections: Array<{
|
|
1259
|
+
prefix: string;
|
|
1260
|
+
declaredBy: string;
|
|
1261
|
+
vars: ConfigVar[];
|
|
1262
|
+
}>;
|
|
1263
|
+
}
|
|
1264
|
+
/** What `app.configOrigins()` returns. */
|
|
1265
|
+
interface ConfigOrigins {
|
|
1266
|
+
/** The app's env schema. */
|
|
1267
|
+
env: VarOrigin[];
|
|
1268
|
+
/** The settings sections the app bound, in binding order. */
|
|
1269
|
+
sections: Array<{
|
|
1270
|
+
prefix: string;
|
|
1271
|
+
vars: VarOrigin[];
|
|
1272
|
+
}>;
|
|
1273
|
+
}
|
|
1274
|
+
interface ApplicationOptions {
|
|
1275
|
+
/**
|
|
1276
|
+
* Feature modules to load. Accepts both class form
|
|
1277
|
+
* (`SomeModule extends AppModule`, instantiated via `new`) and
|
|
1278
|
+
* instance form (output of {@link defineModule}'s factory call,
|
|
1279
|
+
* e.g. `TasksModule({ scope: 'admin' })`) — the loader discriminates
|
|
1280
|
+
* and either `new`-s the class or uses the instance directly.
|
|
1281
|
+
*
|
|
1282
|
+
* Static path — for conditional / dynamic registration, use the
|
|
1283
|
+
* {@link ApplicationOptions.setup} callback instead.
|
|
1284
|
+
*/
|
|
1285
|
+
modules: AppModuleEntry[];
|
|
1286
|
+
/**
|
|
1287
|
+
* Imperative module registration callback. Receives a
|
|
1288
|
+
* {@link ModuleRegistry} you call `.mount(module)` on to register
|
|
1289
|
+
* modules conditionally — based on env flags, runtime config, a
|
|
1290
|
+
* tenant list, etc. Runs after every plugin's `setup()` hook and
|
|
1291
|
+
* after the static `modules: [...]` array is collected.
|
|
1292
|
+
*
|
|
1293
|
+
* @example
|
|
1294
|
+
* ```ts
|
|
1295
|
+
* bootstrap({
|
|
1296
|
+
* modules: [HelloModule()],
|
|
1297
|
+
* setup(registry) {
|
|
1298
|
+
* if (env.ENABLE_ADMIN) registry.mount(AdminModule())
|
|
1299
|
+
* },
|
|
1300
|
+
* })
|
|
1301
|
+
* ```
|
|
1302
|
+
*/
|
|
1303
|
+
setup?(registry: ModuleRegistry): void;
|
|
1304
|
+
/** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */
|
|
1305
|
+
adapters?: AppAdapter[];
|
|
1306
|
+
/** Server port (falls back to PORT env var, then 3000) */
|
|
1307
|
+
port?: number;
|
|
1308
|
+
/**
|
|
1309
|
+
* The Node server `start()` creates in production. Omit for plain HTTP.
|
|
1310
|
+
*
|
|
1311
|
+
* - `{ tls }` — HTTPS on every runtime.
|
|
1312
|
+
* - `{ tls, http2: true }` — HTTP/2 (ALPN `h2`) with HTTP/1.1 fallback, so
|
|
1313
|
+
* HTTP/1.1 clients and WebSocket upgrades keep working. Fastify and h3
|
|
1314
|
+
* only; Express fails at boot with KICK007, and `http2` without `tls`
|
|
1315
|
+
* with KICK008.
|
|
1316
|
+
*
|
|
1317
|
+
* Ignored in dev mode, where Vite owns the server. Most deploys terminate
|
|
1318
|
+
* TLS / HTTP/2 at a proxy and need none of this.
|
|
1319
|
+
*
|
|
1320
|
+
* @example
|
|
1321
|
+
* ```ts
|
|
1322
|
+
* bootstrap({
|
|
1323
|
+
* modules,
|
|
1324
|
+
* runtime: fastifyRuntime(),
|
|
1325
|
+
* server: {
|
|
1326
|
+
* tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
|
1327
|
+
* http2: true,
|
|
1328
|
+
* },
|
|
1329
|
+
* })
|
|
1330
|
+
* ```
|
|
1331
|
+
*/
|
|
1332
|
+
server?: ServerOptions;
|
|
1333
|
+
/** Global API prefix (default: '/api'). Pass `''` to mount at the root. */
|
|
1334
|
+
apiPrefix?: string;
|
|
1335
|
+
/**
|
|
1336
|
+
* Default API version (default: 1) — routes become /{prefix}/v{version}/{path}.
|
|
1337
|
+
*
|
|
1338
|
+
* `false` opts out of URL versioning: routes mount at /{prefix}/{path}.
|
|
1339
|
+
* A module can still version itself by setting `version` on its
|
|
1340
|
+
* `ModuleRoutes` — the per-mount value always wins over this default, in
|
|
1341
|
+
* either direction.
|
|
1342
|
+
*/
|
|
1343
|
+
defaultVersion?: number | false;
|
|
1344
|
+
/**
|
|
1345
|
+
* Global middleware pipeline. Declared in order.
|
|
1346
|
+
* Replaces the hardcoded middleware stack — you control exactly what runs.
|
|
1347
|
+
*
|
|
1348
|
+
* @example
|
|
1349
|
+
* ```ts
|
|
1350
|
+
* bootstrap({
|
|
1351
|
+
* modules,
|
|
1352
|
+
* middlewares: [
|
|
1353
|
+
* helmet(),
|
|
1354
|
+
* cors(),
|
|
1355
|
+
* compression(),
|
|
1356
|
+
* morgan('dev'),
|
|
1357
|
+
* express.json({ limit: '1mb' }),
|
|
1358
|
+
* ],
|
|
1359
|
+
* })
|
|
1360
|
+
* ```
|
|
1361
|
+
*
|
|
1362
|
+
* If omitted, a sensible default is applied:
|
|
1363
|
+
* requestId(), express.json({ limit: '100kb' })
|
|
1364
|
+
*/
|
|
1365
|
+
middlewares?: MiddlewareEntry[];
|
|
1366
|
+
/** Plugins that bundle modules, adapters, middleware, and DI bindings */
|
|
1367
|
+
plugins?: KickPlugin[];
|
|
1368
|
+
/**
|
|
1369
|
+
* Global Context Contributors (#107) that apply to every route in the
|
|
1370
|
+
* application. Merge into the per-route pipeline at the `'global'`
|
|
1371
|
+
* precedence level — they lose to module, adapter, class, and method
|
|
1372
|
+
* contributors with the same key, providing app-wide defaults that any
|
|
1373
|
+
* narrower scope can override.
|
|
1374
|
+
*
|
|
1375
|
+
* @example
|
|
1376
|
+
* ```ts
|
|
1377
|
+
* const StartedAt = defineContextDecorator({
|
|
1378
|
+
* key: 'requestStartedAt',
|
|
1379
|
+
* resolve: () => Date.now(),
|
|
1380
|
+
* })
|
|
1381
|
+
*
|
|
1382
|
+
* bootstrap({
|
|
1383
|
+
* modules,
|
|
1384
|
+
* contributors: [StartedAt.registration],
|
|
1385
|
+
* })
|
|
1386
|
+
* ```
|
|
1387
|
+
*/
|
|
1388
|
+
contributors?: ContributorRegistrations;
|
|
1389
|
+
/**
|
|
1390
|
+
* Backing store strategy for {@link RequestContext} `set/get` and the
|
|
1391
|
+
* Context Contributor pipeline (#107).
|
|
1392
|
+
*
|
|
1393
|
+
* - `'auto'` (default) — Application mounts {@link requestScopeMiddleware}
|
|
1394
|
+
* automatically before any user middleware. If the user-supplied
|
|
1395
|
+
* `middleware` list already includes `requestScopeMiddleware()`,
|
|
1396
|
+
* detection skips the auto-mount so adopters can control its position.
|
|
1397
|
+
* - `'manual'` — Application never mounts the wrapper. The Context
|
|
1398
|
+
* Contributor pipeline still runs on every route — the runner is
|
|
1399
|
+
* inserted by `router-builder` regardless of ALS state. What
|
|
1400
|
+
* degrades without an ALS frame is the *backing store*:
|
|
1401
|
+
* REQUEST-scoped DI throws (no `requestStore.getStore()` to read
|
|
1402
|
+
* from) and `RequestContext.set/get` throws. Use `'manual'` only when you
|
|
1403
|
+
* genuinely intend to wrap requests in your own ALS frame (rare —
|
|
1404
|
+
* multi-tenant adapters used to do this; post-Phase 3 they share
|
|
1405
|
+
* the framework's frame instead).
|
|
1406
|
+
*/
|
|
1407
|
+
contextStore?: 'auto' | 'manual';
|
|
1408
|
+
/**
|
|
1409
|
+
* Controls whether KickJS registers process-level handlers at bootstrap.
|
|
1410
|
+
*
|
|
1411
|
+
* - `'auto'` (default) — register `uncaughtException` /
|
|
1412
|
+
* `unhandledRejection` loggers AND `SIGINT` / `SIGTERM` →
|
|
1413
|
+
* `app.shutdown()` → `process.exit(0)`.
|
|
1414
|
+
* - `'errors-only'` — register the error loggers; skip the signal
|
|
1415
|
+
* handlers. Use this when you have your own shutdown choreographer
|
|
1416
|
+
* (OpenTelemetry SDK, Sentry, custom orchestrator) that calls
|
|
1417
|
+
* `app.shutdown()` itself and you don't want two listeners racing
|
|
1418
|
+
* to call `process.exit`.
|
|
1419
|
+
* - `'manual'` — skip everything. Adopter is responsible for both
|
|
1420
|
+
* error logging and signal-driven shutdown.
|
|
1421
|
+
*
|
|
1422
|
+
* Background: many observability SDKs install their own SIGTERM
|
|
1423
|
+
* handler to flush spans/metrics before the process exits. Two
|
|
1424
|
+
* separate handlers calling `process.exit(0)` race each other and
|
|
1425
|
+
* can truncate the in-flight flush. Setting this to `'errors-only'`
|
|
1426
|
+
* or `'manual'` lets the SDK own the lifecycle while still letting
|
|
1427
|
+
* KickJS surface uncaught exceptions / rejections via the logger.
|
|
1428
|
+
*
|
|
1429
|
+
* The dev mode auto-detect (`__kickjs_httpServer` set by the Vite
|
|
1430
|
+
* plugin) suppresses signal registration regardless of this option,
|
|
1431
|
+
* since Vite owns the lifecycle in development.
|
|
1432
|
+
*/
|
|
1433
|
+
processHooks?: 'auto' | 'errors-only' | 'manual';
|
|
1434
|
+
/**
|
|
1435
|
+
* The HTTP engine driver. Defaults to {@link expressRuntime} — Express stays
|
|
1436
|
+
* the zero-config default, so existing apps are unaffected.
|
|
1437
|
+
*
|
|
1438
|
+
* Any `HttpRuntime` is accepted — pass `fastifyRuntime()` (from
|
|
1439
|
+
* `@forinda/kickjs/fastify`) or a custom engine driver. Defaults to
|
|
1440
|
+
* {@link expressRuntime}. The engine-native escape hatches
|
|
1441
|
+
* (`getRuntimeApp()`, `AdapterContext.app`) follow the active runtime via the
|
|
1442
|
+
* registry (`ActiveRuntime`, spec §4.3b) — Express by default, or the augmented
|
|
1443
|
+
* engine once the `kick/runtime` typegen output is present.
|
|
1444
|
+
*/
|
|
1445
|
+
/**
|
|
1446
|
+
* Mount the built-in `GET /health/live` and `GET /health/ready`.
|
|
1447
|
+
*
|
|
1448
|
+
* On by default. Set `false` to take them over completely — supply your own
|
|
1449
|
+
* module at `/health` and nothing collides. The built-in is registered last,
|
|
1450
|
+
* so an app module claiming the same path already wins without this.
|
|
1451
|
+
*
|
|
1452
|
+
* They mount as an ordinary module, which means they sit inside the
|
|
1453
|
+
* middleware chain: whatever guards the rest of the app guards these too.
|
|
1454
|
+
* Pass `{ flags: [...] }` to put your own route flags on both probes — the
|
|
1455
|
+
* way to make them reachable unauthenticated without exempting a pathname
|
|
1456
|
+
* that can move:
|
|
1457
|
+
*
|
|
1458
|
+
* ```ts
|
|
1459
|
+
* bootstrap({ health: { flags: ['auth.public'] } })
|
|
1460
|
+
* ```
|
|
1461
|
+
*/
|
|
1462
|
+
health?: boolean | HealthModuleConfig;
|
|
1463
|
+
runtime?: HttpRuntime;
|
|
1464
|
+
/**
|
|
1465
|
+
* Requests no route matched, when the app runs inside another handler —
|
|
1466
|
+
* `kick dev`'s Vite server, or `app.handle(req, res, next)` in a host server.
|
|
1467
|
+
*
|
|
1468
|
+
* - `true` (default): Fastify and h3 hand them back to that handler.
|
|
1469
|
+
* - `false`: they are answered here — `onNotFound`, or the built-in 404 /
|
|
1470
|
+
* 405 — the same as in production. Express always answers.
|
|
1471
|
+
*
|
|
1472
|
+
* Set `false` when the app owns its URLs, e.g. pages with an error page,
|
|
1473
|
+
* so dev answers unknown URLs the way production does.
|
|
1474
|
+
*/
|
|
1475
|
+
notFoundFallthrough?: boolean;
|
|
1476
|
+
/** Express `trust proxy` setting */
|
|
1477
|
+
trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean);
|
|
1478
|
+
/**
|
|
1479
|
+
* Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`).
|
|
1480
|
+
* Express applies it to its default parsers, so only when `middlewares` is
|
|
1481
|
+
* not provided; Fastify, h3 and the web entry parse bodies themselves and
|
|
1482
|
+
* always apply it. A larger body answers 413.
|
|
1483
|
+
*/
|
|
1484
|
+
jsonLimit?: string | number;
|
|
1485
|
+
/**
|
|
1486
|
+
* Print the route table on startup. Default: `false`. Set to `true`
|
|
1487
|
+
* to log a per-controller summary (method counts + mount paths) once
|
|
1488
|
+
* the app has mounted. Emitted at `info` level, so it is still subject
|
|
1489
|
+
* to `LOG_LEVEL` filtering (visible at the default `info`; hidden at
|
|
1490
|
+
* `warn`/`error`/`silent`).
|
|
1491
|
+
*/
|
|
1492
|
+
logRouteTable?: boolean;
|
|
1493
|
+
/**
|
|
1494
|
+
* @deprecated Use {@link ApplicationOptions.logRouteTable}. Kept as an
|
|
1495
|
+
* alias for back-compat; `logRouteTable` wins when both are set.
|
|
1496
|
+
*/
|
|
1497
|
+
logRoutesTable?: boolean;
|
|
1498
|
+
/**
|
|
1499
|
+
* Maximum time (ms) to wait for graceful shutdown before forcing exit.
|
|
1500
|
+
* Default: 30000 (30 seconds). Set to 0 to disable forced exit.
|
|
1501
|
+
*/
|
|
1502
|
+
shutdownTimeout?: number;
|
|
1503
|
+
/**
|
|
1504
|
+
* Milliseconds to keep serving after shutdown begins, with `/health/ready`
|
|
1505
|
+
* already answering 503, before the server stops accepting connections.
|
|
1506
|
+
* Load balancers and Kubernetes endpoints take a few seconds to notice an
|
|
1507
|
+
* unready instance; closing at once refuses the requests still routed here.
|
|
1508
|
+
* Default 0. Not counted against `shutdownTimeout`.
|
|
1509
|
+
*/
|
|
1510
|
+
preStopDelay?: number;
|
|
1511
|
+
/**
|
|
1512
|
+
* Enable cluster mode for multi-core utilization.
|
|
1513
|
+
*
|
|
1514
|
+
* When enabled, the primary process forks worker processes that share the
|
|
1515
|
+
* same port via Node's built-in `cluster` module (OS load balancing).
|
|
1516
|
+
*
|
|
1517
|
+
* - `true` — use all available CPU cores
|
|
1518
|
+
* - `{ workers: N }` — use exactly N workers
|
|
1519
|
+
*
|
|
1520
|
+
* Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is
|
|
1521
|
+
* forwarded to all workers.
|
|
1522
|
+
*
|
|
1523
|
+
* @example
|
|
1524
|
+
* ```ts
|
|
1525
|
+
* bootstrap({ modules, cluster: true })
|
|
1526
|
+
* bootstrap({ modules, cluster: { workers: 4 } })
|
|
1527
|
+
* ```
|
|
1528
|
+
*/
|
|
1529
|
+
cluster?: boolean | {
|
|
1530
|
+
workers?: number;
|
|
1531
|
+
};
|
|
1532
|
+
/**
|
|
1533
|
+
* Custom 404 handler for unmatched routes. When omitted, the built-in
|
|
1534
|
+
* handler returns `{ message: 'Not Found' }` with status 404.
|
|
1535
|
+
*
|
|
1536
|
+
* Connect-**shaped**, not Express-**semantic** — see {@link onError} for the
|
|
1537
|
+
* per-runtime table. The same two caveats apply: `next()` is inert on
|
|
1538
|
+
* Fastify and h3, and Express-only request members (`req.originalUrl`,
|
|
1539
|
+
* `req.path`, `req.ip`) are `undefined` there, so read `req.url`.
|
|
1540
|
+
*
|
|
1541
|
+
* @example
|
|
1542
|
+
* ```ts
|
|
1543
|
+
* bootstrap({
|
|
1544
|
+
* modules,
|
|
1545
|
+
* onNotFound: (req, res) => {
|
|
1546
|
+
* // `req.originalUrl` is Express-only — use `req.url` for portability.
|
|
1547
|
+
* res.status(404).json({ error: 'Route not found', path: req.url })
|
|
1548
|
+
* },
|
|
1549
|
+
* })
|
|
1550
|
+
* ```
|
|
1551
|
+
*
|
|
1552
|
+
* Calling `next()` hands the request to the built-in handler — the usual
|
|
1553
|
+
* 404, or the 405 with `Allow` when the path exists under another method —
|
|
1554
|
+
* so a custom handler can answer some requests and leave the rest.
|
|
1555
|
+
*/
|
|
1556
|
+
onNotFound?: (req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void;
|
|
1557
|
+
/**
|
|
1558
|
+
* Custom global error handler, receiving `(err, req, res, next)`. When
|
|
1559
|
+
* omitted, the built-in handler formats ZodError, HttpException, and
|
|
1560
|
+
* unexpected errors.
|
|
1561
|
+
*
|
|
1562
|
+
* The shape is connect-style, but it is NOT "the standard Express error
|
|
1563
|
+
* handler" on every engine — what you actually receive differs, and the
|
|
1564
|
+
* differences bite:
|
|
1565
|
+
*
|
|
1566
|
+
* | | `req` | `res` | `next` |
|
|
1567
|
+
* | --- | --- | --- | --- |
|
|
1568
|
+
* | Express | native `Request` | native `Response` | real `next` |
|
|
1569
|
+
* | Fastify | `request.raw` | reply driver | **no-op** |
|
|
1570
|
+
* | h3 | `event.node.req` | response driver | no-op (or dev fall-through) |
|
|
1571
|
+
*
|
|
1572
|
+
* Two consequences worth knowing before you write one:
|
|
1573
|
+
*
|
|
1574
|
+
* - **`next(err)` does nothing on Fastify and h3.** It is a no-op function
|
|
1575
|
+
* there, so delegating to the default handler silently drops the error.
|
|
1576
|
+
* Send a response yourself rather than passing it on.
|
|
1577
|
+
* - **Express-only request members are `undefined` elsewhere.**
|
|
1578
|
+
* `req.originalUrl`, `req.path`, and `req.ip` do not exist on the raw node
|
|
1579
|
+
* request — use `req.url` and the `x-forwarded-*` headers, or reach for
|
|
1580
|
+
* `ctx.ip` in a contributor / guard where a `RequestContext` is available.
|
|
1581
|
+
*
|
|
1582
|
+
* `res` is typed {@link RuntimeResponse} because that is what every engine
|
|
1583
|
+
* genuinely provides: `status`, `json`, `send`, `setHeader`, `render`,
|
|
1584
|
+
* `writeHead`, `end`. Express's own `Response` satisfies it.
|
|
1585
|
+
*
|
|
1586
|
+
* @example
|
|
1587
|
+
* ```ts
|
|
1588
|
+
* bootstrap({
|
|
1589
|
+
* modules,
|
|
1590
|
+
* onError: (err, req, res) => {
|
|
1591
|
+
* logger.error(err, `${req.method} ${req.url}`) // not `originalUrl`
|
|
1592
|
+
* res.status(err.status ?? 500).json({ error: err.message })
|
|
1593
|
+
* },
|
|
1594
|
+
* })
|
|
1595
|
+
* ```
|
|
1596
|
+
*/
|
|
1597
|
+
onError?: (err: any, req: any, res: RuntimeResponse, next: (err?: unknown) => void) => void;
|
|
1598
|
+
/**
|
|
1599
|
+
* Decide what a failed route validation (`@Validate` / `validate()`) throws.
|
|
1600
|
+
* Receives `{ source, issues, req }` and returns the error — by default a 422
|
|
1601
|
+
* `HttpException` with `[{ field, message }]` details. Return `undefined` to
|
|
1602
|
+
* fall back to the default for that failure.
|
|
1603
|
+
*
|
|
1604
|
+
* ```ts
|
|
1605
|
+
* bootstrap({
|
|
1606
|
+
* validationError: ({ source, issues }) =>
|
|
1607
|
+
* new ProblemException({
|
|
1608
|
+
* status: 400,
|
|
1609
|
+
* title: `Invalid ${source}`,
|
|
1610
|
+
* errors: issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
|
|
1611
|
+
* }),
|
|
1612
|
+
* })
|
|
1613
|
+
* ```
|
|
1614
|
+
*
|
|
1615
|
+
* Applies to this app's routes only.
|
|
1616
|
+
*/
|
|
1617
|
+
validationError?: ValidationErrorFactory;
|
|
1618
|
+
/**
|
|
1619
|
+
* Your own startup checks, run with the built-in ones once the app is
|
|
1620
|
+
* assembled and before it serves a request. A check returning an `error`
|
|
1621
|
+
* fails startup; a `warning` is logged.
|
|
1622
|
+
*
|
|
1623
|
+
* ```ts
|
|
1624
|
+
* const needsDb = defineCheck({
|
|
1625
|
+
* name: 'database url',
|
|
1626
|
+
* deploy: true, // production only
|
|
1627
|
+
* run: () =>
|
|
1628
|
+
* process.env.DATABASE_URL?.includes('localhost')
|
|
1629
|
+
* ? { id: 'APP-W001', level: 'warning', message: 'DATABASE_URL points at localhost' }
|
|
1630
|
+
* : undefined,
|
|
1631
|
+
* })
|
|
1632
|
+
* bootstrap({ modules, checks: [needsDb] })
|
|
1633
|
+
* ```
|
|
1634
|
+
*/
|
|
1635
|
+
checks?: StartupCheck[];
|
|
1636
|
+
/** Check IDs to skip, e.g. `['KICK-SEC-W002']` — a deliberate, reviewable exception. */
|
|
1637
|
+
silenceChecks?: string[];
|
|
1638
|
+
/**
|
|
1639
|
+
* App-wide settings sections ({@link defineSettings}): validated at startup
|
|
1640
|
+
* — a missing or invalid value fails it, naming the variables — and
|
|
1641
|
+
* injectable by their tokens. Modules, adapters and plugins declare their
|
|
1642
|
+
* own with `settings()`.
|
|
1643
|
+
*/
|
|
1644
|
+
settings?: SettingsDeclaration[];
|
|
1645
|
+
/**
|
|
1646
|
+
* Security defaults applied automatically unless opted out.
|
|
1647
|
+
*
|
|
1648
|
+
* When not specified, secure defaults are applied:
|
|
1649
|
+
* - Helmet security headers are auto-injected
|
|
1650
|
+
* - JSON body limit defaults to 1MB
|
|
1651
|
+
*
|
|
1652
|
+
* @example
|
|
1653
|
+
* ```ts
|
|
1654
|
+
* bootstrap({
|
|
1655
|
+
* modules,
|
|
1656
|
+
* security: {
|
|
1657
|
+
* helmet: false, // disable auto-helmet
|
|
1658
|
+
* },
|
|
1659
|
+
* })
|
|
1660
|
+
* ```
|
|
1661
|
+
*/
|
|
1662
|
+
security?: {
|
|
1663
|
+
/** Auto-inject helmet security headers. Default: true */
|
|
1664
|
+
helmet?: boolean;
|
|
1665
|
+
/**
|
|
1666
|
+
* Answer only requests for these hosts — `allowedHosts()` mounted first.
|
|
1667
|
+
* `'.example.com'` matches the domain and its subdomains. The health
|
|
1668
|
+
* probes are exempt: orchestrators send them to the instance's IP.
|
|
1669
|
+
*
|
|
1670
|
+
* ```ts
|
|
1671
|
+
* bootstrap({ security: { allowedHosts: ['example.com', '.example.com'] } })
|
|
1672
|
+
* ```
|
|
1673
|
+
*/
|
|
1674
|
+
allowedHosts?: string[] | AllowedHostsOptions;
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
declare class Application {
|
|
1678
|
+
private readonly options;
|
|
1679
|
+
private app;
|
|
1680
|
+
/** The HTTP engine driver. Defaults to {@link expressRuntime}. */
|
|
1681
|
+
private readonly runtime;
|
|
1682
|
+
private container;
|
|
1683
|
+
private httpServer;
|
|
1684
|
+
/** Set by startWithoutServer() — the serverless path, where cron runs over HTTP. */
|
|
1685
|
+
private handlerMode;
|
|
1686
|
+
/** The observer set this app installed — released on shutdown only if still current. */
|
|
1687
|
+
private observers;
|
|
1688
|
+
/**
|
|
1689
|
+
* Open HTTP/2 sessions. `server.close()` stops new sessions, but on older
|
|
1690
|
+
* Node (22 and earlier) existing ones keep accepting new streams — so
|
|
1691
|
+
* shutdown closes them itself.
|
|
1692
|
+
*/
|
|
1693
|
+
private readonly http2Sessions;
|
|
1694
|
+
/** Forwarding server behind {@link fetch} on Node-based runtimes. */
|
|
1695
|
+
private loopback?;
|
|
1696
|
+
private timeline;
|
|
1697
|
+
private conditionReport;
|
|
1698
|
+
private mountedRoutes;
|
|
1699
|
+
private mountedRouteInfo;
|
|
1700
|
+
private routeUrls;
|
|
1701
|
+
/** Settings prefixes bound in this setup, across its two binding phases. */
|
|
1702
|
+
private settingsPrefixes;
|
|
1703
|
+
private settingsProvided;
|
|
1704
|
+
private handlerFor?;
|
|
1705
|
+
private readonly adapters;
|
|
1706
|
+
/**
|
|
1707
|
+
* Flags of every mounted route, for middleware that runs before routing and
|
|
1708
|
+
* therefore cannot read `ctx.route` (the connect-style rate limiter). Handed
|
|
1709
|
+
* to middleware that declares the slot — see `core/route-policy.ts`.
|
|
1710
|
+
*/
|
|
1711
|
+
private readonly routePolicy;
|
|
1712
|
+
private readonly plugins;
|
|
1713
|
+
/**
|
|
1714
|
+
* Snapshot of every module-level Context Contributor registration
|
|
1715
|
+
* captured during `setup()`. The registrations themselves are
|
|
1716
|
+
* frozen by `defineContextDecorator`, so storing references is
|
|
1717
|
+
* safe — they outlive the module instances they came from.
|
|
1718
|
+
*
|
|
1719
|
+
* Used by {@link getContributors} so DevTools and adopter tooling
|
|
1720
|
+
* can render the module-level contributors alongside the adapter /
|
|
1721
|
+
* plugin / global ones. Populated once per `setup()` call; cleared
|
|
1722
|
+
* at the start of each invocation so a re-setup (test harnesses,
|
|
1723
|
+
* dev-server restarts) doesn't accumulate stale entries.
|
|
1724
|
+
*/
|
|
1725
|
+
private _moduleContributors;
|
|
1726
|
+
/** Number of HTTP requests currently being processed */
|
|
1727
|
+
private _inFlightRequests;
|
|
1728
|
+
/** Whether the application is draining (shutting down gracefully) */
|
|
1729
|
+
private _draining;
|
|
1730
|
+
/** Whether shutdown has already been initiated (prevents double-shutdown) */
|
|
1731
|
+
private _shutdownInitiated;
|
|
1732
|
+
/** Resolvers waiting for in-flight requests to reach zero */
|
|
1733
|
+
private _drainResolvers;
|
|
1734
|
+
constructor(options: ApplicationOptions);
|
|
1735
|
+
/**
|
|
1736
|
+
* Leave out adapters whose `when` says no — and, until nothing changes, any
|
|
1737
|
+
* adapter that `dependsOn` one left out, which could not run without it.
|
|
1738
|
+
*/
|
|
1739
|
+
private applyConditions;
|
|
1740
|
+
/**
|
|
1741
|
+
* Adapters with a `when` condition, and whether each is on — with the reason
|
|
1742
|
+
* when it is not. Served by DevTools at `/_debug/conditions`.
|
|
1743
|
+
*/
|
|
1744
|
+
getConditionReport(): readonly ConditionOutcome[];
|
|
1745
|
+
/** Whether the application is currently draining in-flight requests */
|
|
1746
|
+
get isDraining(): boolean;
|
|
1747
|
+
/** Number of HTTP requests currently being processed */
|
|
1748
|
+
get inFlightRequests(): number;
|
|
1749
|
+
/** Get the DI container instance */
|
|
1750
|
+
getContainer(): Container;
|
|
1751
|
+
/**
|
|
1752
|
+
* Express request handler — delegates to the internal Express app.
|
|
1753
|
+
*
|
|
1754
|
+
* Used by the Vite dev-server plugin to route requests through KickJS:
|
|
1755
|
+
* ```ts
|
|
1756
|
+
* const mod = await ssrLoadModule('virtual:kickjs/app')
|
|
1757
|
+
* mod.app.handle(req, res, next)
|
|
1758
|
+
* ```
|
|
1759
|
+
*
|
|
1760
|
+
* Also works as a standard Node.js request handler for production:
|
|
1761
|
+
* ```ts
|
|
1762
|
+
* http.createServer(app.handle.bind(app))
|
|
1763
|
+
* ```
|
|
1764
|
+
*/
|
|
1765
|
+
/**
|
|
1766
|
+
* Run a web `Request` through the app — routing, middleware, validation,
|
|
1767
|
+
* contributors, error handling — and return its `Response`, with no
|
|
1768
|
+
* listening server required.
|
|
1769
|
+
*
|
|
1770
|
+
* Runtimes with a native fetch (h3) are called directly.
|
|
1771
|
+
* Node-based runtimes (Express, Fastify) are served by forwarding to
|
|
1772
|
+
* a server bound to `127.0.0.1` inside this process, started on first use
|
|
1773
|
+
* and closed by {@link shutdown}; request bodies are buffered on that path.
|
|
1774
|
+
*
|
|
1775
|
+
* Used by `createHandler()` and by adapters (`AdapterContext.fetch`) that
|
|
1776
|
+
* call the app's own routes, such as MCP and AI tool dispatch.
|
|
1777
|
+
*/
|
|
1778
|
+
fetch(request: Request): Promise<Response>;
|
|
1779
|
+
/** The engine app, from the options — one place, so a rebuild (HMR) keeps them all. */
|
|
1780
|
+
private createEngineApp;
|
|
1781
|
+
handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void;
|
|
1782
|
+
/**
|
|
1783
|
+
* Full setup pipeline:
|
|
1784
|
+
* 1. Adapter beforeMount hooks (early routes — e.g. docs UI)
|
|
1785
|
+
* 2. Adapter middleware (phase: beforeGlobal)
|
|
1786
|
+
* 3. Global middleware (user-declared or defaults)
|
|
1787
|
+
* 4. Adapter middleware (phase: afterGlobal)
|
|
1788
|
+
* 5. Module registration + DI bootstrap (the built-in health module mounts
|
|
1789
|
+
* here with everything else — it is NOT an early route)
|
|
1790
|
+
* 6. Adapter middleware (phase: beforeRoutes)
|
|
1791
|
+
* 7. Module route mounting
|
|
1792
|
+
* 8. Adapter middleware (phase: afterRoutes)
|
|
1793
|
+
* 9. Adapter beforeStart hooks
|
|
1794
|
+
* 10. Error handlers (notFound + global)
|
|
1795
|
+
*/
|
|
1796
|
+
/** Build the adapter context object (shared across all hooks) */
|
|
1797
|
+
private adapterCtx;
|
|
1798
|
+
/**
|
|
1799
|
+
* The engine-agnostic HTTP surface handed to adapters as `ctx.http`. Each
|
|
1800
|
+
* call routes through the active runtime over the current `this.app`, so an
|
|
1801
|
+
* adapter written against this works under any runtime.
|
|
1802
|
+
*/
|
|
1803
|
+
private adapterHttp;
|
|
1804
|
+
/**
|
|
1805
|
+
* Call an adapter hook, awaiting async hooks.
|
|
1806
|
+
*
|
|
1807
|
+
* A setup hook (`beforeMount`, `beforeStart`) that throws aborts boot: the
|
|
1808
|
+
* adapter didn't finish wiring itself — a database adapter refusing to
|
|
1809
|
+
* start with pending migrations, say — and serving anyway runs on a
|
|
1810
|
+
* half-built app. `afterStart` runs once the server is already listening,
|
|
1811
|
+
* so its failure is logged and the server keeps going.
|
|
1812
|
+
*/
|
|
1813
|
+
private callHook;
|
|
1814
|
+
/**
|
|
1815
|
+
* Log advice for a hook failure: the failing adapter's own analysis first,
|
|
1816
|
+
* then the framework's. The error itself is still thrown or logged by the
|
|
1817
|
+
* caller — this only adds the explanation in front of it.
|
|
1818
|
+
*/
|
|
1819
|
+
private adviseOnFailure;
|
|
1820
|
+
/**
|
|
1821
|
+
* Where the last startup's time went: each phase and each adapter hook, in
|
|
1822
|
+
* order. Served by devtools at `/_debug/startup`.
|
|
1823
|
+
*/
|
|
1824
|
+
getStartupTimeline(): StartupTimelineSnapshot;
|
|
1825
|
+
/**
|
|
1826
|
+
* The URL of a route, by name — `'Controller.method'` — with its `:params`
|
|
1827
|
+
* filled (encoded) and an optional query string. For links built outside a
|
|
1828
|
+
* request (emails, jobs); inside one, use `ctx.urlFor()`.
|
|
1829
|
+
*
|
|
1830
|
+
* ```ts
|
|
1831
|
+
* app.urlFor('UsersController.show', { id: user.id }) // '/api/v1/users/42'
|
|
1832
|
+
* ```
|
|
1833
|
+
*/
|
|
1834
|
+
urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string;
|
|
1835
|
+
/** The app's modules — plugins', then its own — in registration order. */
|
|
1836
|
+
private collectModules;
|
|
1837
|
+
/**
|
|
1838
|
+
* Every variable the app reads — its env schema, and each declared settings
|
|
1839
|
+
* section with who declared it — and whether each is required, its default
|
|
1840
|
+
* and description. Reads no environment and validates nothing, so it works
|
|
1841
|
+
* when the environment is missing: it's what `kick env example` writes.
|
|
1842
|
+
* Call it on an app that hasn't started.
|
|
1843
|
+
*/
|
|
1844
|
+
describeConfig(): ConfigDescription;
|
|
1845
|
+
/**
|
|
1846
|
+
* Where each variable the app reads gets its value — env, a `_FILE` secret,
|
|
1847
|
+
* the schema's default, `provide()`, or nothing — for the env schema and
|
|
1848
|
+
* every bound settings section. Names only, never values. Read from the
|
|
1849
|
+
* current environment; call it on a started app.
|
|
1850
|
+
*/
|
|
1851
|
+
configOrigins(): ConfigOrigins;
|
|
1852
|
+
/** Validate settings sections and bind each under its token. */
|
|
1853
|
+
private bindSettings;
|
|
1854
|
+
/** Run the built-in and the app's startup checks against the assembled app. */
|
|
1855
|
+
private runChecks;
|
|
1856
|
+
/** Log the slowest steps — only when startup was slow enough to ask why. */
|
|
1857
|
+
private reportStartup;
|
|
1858
|
+
setup(): Promise<void>;
|
|
1859
|
+
/** Register modules and DI without starting the HTTP server (used by kick tinker) */
|
|
1860
|
+
registerOnly(): Promise<void>;
|
|
1861
|
+
/**
|
|
1862
|
+
* Make the app ready to serve requests handed to it, with no server of its
|
|
1863
|
+
* own — the serverless path behind {@link createHandler}.
|
|
1864
|
+
*
|
|
1865
|
+
* Runs the same `setup()` as {@link start} and the plugins' `onReady`, but
|
|
1866
|
+
* nothing that needs a listening server: there is no port, no `afterStart`
|
|
1867
|
+
* (it receives the `http.Server`), and no process signal handlers.
|
|
1868
|
+
*/
|
|
1869
|
+
startWithoutServer(): Promise<void>;
|
|
1870
|
+
/**
|
|
1871
|
+
* Start the HTTP server.
|
|
1872
|
+
*
|
|
1873
|
+
* In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`
|
|
1874
|
+
* created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real
|
|
1875
|
+
* `http.Server` through `afterStart({ server })` — zero adapter changes needed.
|
|
1876
|
+
*
|
|
1877
|
+
* In **production**: creates its own `http.Server` and binds to the port.
|
|
1878
|
+
*/
|
|
1879
|
+
start(): Promise<void>;
|
|
1880
|
+
/** The production server for {@link ApplicationOptions.server}. */
|
|
1881
|
+
private createNodeServer;
|
|
1882
|
+
private createBareServer;
|
|
1883
|
+
/** HMR rebuild: swap Express handler without restarting the server */
|
|
1884
|
+
rebuild(): Promise<void>;
|
|
1885
|
+
/**
|
|
1886
|
+
* Graceful shutdown with request draining.
|
|
1887
|
+
*
|
|
1888
|
+
* 1. Stops accepting new connections (server.close())
|
|
1889
|
+
* 2. Waits for in-flight requests to complete (up to shutdownTimeout)
|
|
1890
|
+
* 3. Calls adapter.shutdown() for all registered adapters
|
|
1891
|
+
* 4. Force-closes after timeout
|
|
1892
|
+
*
|
|
1893
|
+
* Safe to call multiple times — subsequent calls return the same promise.
|
|
1894
|
+
*/
|
|
1895
|
+
shutdown(options?: ShutdownOptions): Promise<void>;
|
|
1896
|
+
/**
|
|
1897
|
+
* The engine-native app instance, typed from the active runtime
|
|
1898
|
+
* ({@link ActiveRuntime} — Express by default). Prefer this over
|
|
1899
|
+
* {@link getExpressApp}; under a non-Express runtime the type follows the
|
|
1900
|
+
* augmented registry.
|
|
1901
|
+
*/
|
|
1902
|
+
getRuntimeApp(): ActiveRuntime['app'];
|
|
1903
|
+
/**
|
|
1904
|
+
* The active HTTP runtime's identity + capabilities — `name` is `'express'`
|
|
1905
|
+
* (default), `'fastify'`, or `'h3'`; `capabilities` reports what the engine
|
|
1906
|
+
* supports (render / uploads / connectMiddleware / nativeBodyParsing).
|
|
1907
|
+
* Surfaced by DevTools and the VS Code extension so tooling can show which
|
|
1908
|
+
* engine the app is running on. Cheap, side-effect free.
|
|
1909
|
+
*/
|
|
1910
|
+
getActiveRuntime(): {
|
|
1911
|
+
name: string;
|
|
1912
|
+
capabilities: RuntimeCapabilities;
|
|
1913
|
+
};
|
|
1914
|
+
/** @deprecated Use {@link getRuntimeApp}. Returns the engine-native app. */
|
|
1915
|
+
getExpressApp(): Express;
|
|
1916
|
+
/** Get registered adapters — used by DevToolsAdapter for peer discovery */
|
|
1917
|
+
getAdapters(): AppAdapter[];
|
|
1918
|
+
/**
|
|
1919
|
+
* Get registered plugins — used by DevToolsAdapter for topology
|
|
1920
|
+
* introspection (architecture.md §23). Read-only; returns the
|
|
1921
|
+
* already-sorted plugin list (post-`dependsOn` topo-sort).
|
|
1922
|
+
*/
|
|
1923
|
+
getPlugins(): readonly KickPlugin[];
|
|
1924
|
+
/**
|
|
1925
|
+
* Snapshot of every Context Contributor reachable from this app —
|
|
1926
|
+
* walks **four** registration sites: adapters, plugins, modules,
|
|
1927
|
+
* and the bootstrap `contributors` option. The devtools Topology
|
|
1928
|
+
* tab consumes this for the Contributors panel; tests + adopters
|
|
1929
|
+
* can call it for diagnostics.
|
|
1930
|
+
*
|
|
1931
|
+
* Per-route (method/class-decorator) registrations are NOT included
|
|
1932
|
+
* here — they live on the route registry rather than on any of
|
|
1933
|
+
* the four collection sites this method walks. A future RPC will
|
|
1934
|
+
* surface them separately.
|
|
1935
|
+
*
|
|
1936
|
+
* Result shape stays minimal — `{ key, source, label, dependsOn }`
|
|
1937
|
+
* — so we don't leak `resolve` closures or other internal fields.
|
|
1938
|
+
* `source` matches the five-level precedence union from
|
|
1939
|
+
* `ContributorSource` (minus `'method'` / `'class'` which require
|
|
1940
|
+
* the per-route walk noted above).
|
|
1941
|
+
*/
|
|
1942
|
+
/**
|
|
1943
|
+
* Every controller route the app mounted, with its full pattern and the
|
|
1944
|
+
* context contributors a request runs, in execution order — decorators
|
|
1945
|
+
* included. Devtools serves this per route.
|
|
1946
|
+
*/
|
|
1947
|
+
getRoutes(): readonly MountedRouteInfo[];
|
|
1948
|
+
getContributors(): ReadonlyArray<{
|
|
1949
|
+
key: string;
|
|
1950
|
+
source: 'method' | 'class' | 'module' | 'adapter' | 'plugin' | 'global';
|
|
1951
|
+
label: string;
|
|
1952
|
+
dependsOn: readonly string[];
|
|
1953
|
+
}>;
|
|
1954
|
+
getHttpServer(): KickServer | null;
|
|
1955
|
+
/**
|
|
1956
|
+
* Decide whether {@link Application} should auto-mount the
|
|
1957
|
+
* {@link requestScopeMiddleware} ALS wrapper.
|
|
1958
|
+
*
|
|
1959
|
+
* Returns `false` when:
|
|
1960
|
+
* - `contextStore: 'manual'` was set (caller manages ALS frames), or
|
|
1961
|
+
* - the user-supplied `middleware` list already includes a
|
|
1962
|
+
* `requestScopeMiddleware()` (detected via the symbol marker stamped
|
|
1963
|
+
* in `middleware/request-scope.ts`).
|
|
1964
|
+
*
|
|
1965
|
+
* Otherwise `true` — preserves the historical default of "always wrap
|
|
1966
|
+
* requests in an ALS frame" so existing apps see no behavior change.
|
|
1967
|
+
*/
|
|
1968
|
+
private shouldAutoMountRequestScope;
|
|
1969
|
+
private collectAdapterMiddleware;
|
|
1970
|
+
private mountMiddlewareList;
|
|
1971
|
+
private mountMiddlewareEntry;
|
|
1972
|
+
/**
|
|
1973
|
+
* `GET /_kick/cron/:scheduleId` — how a serverless platform
|
|
1974
|
+
* (Vercel crons) runs `@Cron` jobs: `kick build:vercel` emits one cron entry
|
|
1975
|
+
* per schedule pointing here. Mounted only in handler mode and only when
|
|
1976
|
+
* `CRON_SECRET` is set; the request must carry `Authorization: Bearer
|
|
1977
|
+
* $CRON_SECRET` (Vercel sends it). Runs every job on that schedule.
|
|
1978
|
+
*/
|
|
1979
|
+
private mountCronTrigger;
|
|
1980
|
+
/** Middleware that tracks in-flight requests for graceful draining */
|
|
1981
|
+
private requestTrackingMiddleware;
|
|
1982
|
+
}
|
|
1983
|
+
//#endregion
|
|
1984
|
+
export { HandlerTraceContext as $, requestStore as A, ContributorCycleError as At, PasswordCheck as B, KickError as Bt, TraceContextOptions as C, stripExt as Ct, RequestStore as D, MountKind as Dt, requestScopeMiddleware as E, MountCycleError as Et, Signer as F, CircuitBreakerOptions as Ft, defineHttpContextDecorator as G, VerifyPasswordOptions as H, formatKickError as Ht, SignerOptions as I, CircuitBreakerState as It, KickHandler as J, ClusterOptions as K, VerifyOptions as L, CircuitBreakerStats as Lt, expressRuntime as M, MissingContextValueError as Mt, materializeRouter as N, MissingContributorError as Nt, getRequestStore as O, MountSortItem as Ot, SignedCheck as P, CircuitBreaker as Pt, HANDLER_CHANNEL as Q, createSigner as R, CircuitOpenError as Rt, TraceContext as S, groupAssetKeys as St, traceContext as T, MissingMountDepError as Tt, hashPassword as U, PasswordHashOptions as V, KickErrorInit as Vt, verifyPassword as W, bootstrap as X, createHandler as Y, ERROR_CHANNEL as Z, resolveClientDir as _, offerRoutePolicy as _t, MiddlewareEntry as a, MetricsOptions as at, viewDirs as b, GroupAssetKeysOptions as bt, ShutdownOptions as c, CheckContext as ct, HealthController as d, StartupCheckError as dt, RESPONSE_CHANNEL as et, HealthModuleConfig as f, defineCheck as ft, SpaAdapterOptions as g, bindRoutePolicy as gt, SpaAdapter as h, RoutePolicyTable as ht, ConfigOrigins as i, RAW_BODY as it, buildRoutes as j, DuplicateContributorError as jt, getRequestValue as k, mountSort as kt, HEALTH_PROBE as l, CheckMessage as lt, healthModule as m, StartupTimelineSnapshot as mt, ApplicationOptions as n, CronAdapterOptions as nt, MountedRouteInfo as o, RequestHistogram as ot, HealthProbe as p, StartupStep as pt, isClusterPrimary as q, ConfigDescription as r, KickCronAdapter as rt, ServerOptions as s, metricsAdapter as st, Application as t, CRON_WORKER_ENV as tt, HealthCheckResult as u, StartupCheck as ut, ViewAdapter as v, AssetKeyPair as vt, parseTraceparent as w, DuplicateMountNameError as wt, TRACEPARENT_HEADER as x, GroupAssetKeysResult as xt, ViewAdapterOptions as y, AssetKeyStrategy as yt, LegacyHasher as z, FormatKickErrorOptions as zt };
|
|
1985
|
+
//# sourceMappingURL=application-BuUWvaqp.d.mts.map
|