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