@forinda/kickjs 3.2.0 → 4.0.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.
Files changed (187) hide show
  1. package/README.md +13 -212
  2. package/dist/{adapter-DLEHb0K6.d.mts → adapter-BNw2pGbg.d.mts} +117 -7
  3. package/dist/adapter-BNw2pGbg.d.mts.map +1 -0
  4. package/dist/{app-module-ERR9jhow.d.mts → app-module-CO0ksPCm.d.mts} +3 -3
  5. package/dist/{app-module-ERR9jhow.d.mts.map → app-module-CO0ksPCm.d.mts.map} +1 -1
  6. package/dist/{application-x8CXLOlv.mjs → application-Ce4DQN6m.mjs} +28 -9
  7. package/dist/application-Ce4DQN6m.mjs.map +1 -0
  8. package/dist/application-Czwm7Gty.d.mts +302 -0
  9. package/dist/application-Czwm7Gty.d.mts.map +1 -0
  10. package/dist/{bootstrap-CYnxozL_.mjs → bootstrap-CB7bJeJG.mjs} +6 -6
  11. package/dist/{bootstrap-CYnxozL_.mjs.map → bootstrap-CB7bJeJG.mjs.map} +1 -1
  12. package/dist/bootstrap-NxFRaNTh.d.mts +28 -0
  13. package/dist/bootstrap-NxFRaNTh.d.mts.map +1 -0
  14. package/dist/{cache-V91BNTIM.d.mts → cache-BStrqXSZ.d.mts} +2 -2
  15. package/dist/{cache-V91BNTIM.d.mts.map → cache-BStrqXSZ.d.mts.map} +1 -1
  16. package/dist/config/index.d.mts +1 -1
  17. package/dist/config/index.mjs +3 -3
  18. package/dist/{config-aWxKLk4A.mjs → config-wZ_TgBfs.mjs} +4 -4
  19. package/dist/{config-aWxKLk4A.mjs.map → config-wZ_TgBfs.mjs.map} +1 -1
  20. package/dist/{container-fIS1uLx-.d.mts → container-CnWDsxi-.d.mts} +9 -7
  21. package/dist/container-CnWDsxi-.d.mts.map +1 -0
  22. package/dist/{container-Dnk43k54.mjs → container-DYYSu58w.mjs} +313 -9
  23. package/dist/container-DYYSu58w.mjs.map +1 -0
  24. package/dist/{context-OktlOQBQ.mjs → context-BAGzqT7-.mjs} +33 -41
  25. package/dist/context-BAGzqT7-.mjs.map +1 -0
  26. package/dist/context-Ymvv-85x.d.mts +260 -0
  27. package/dist/context-Ymvv-85x.d.mts.map +1 -0
  28. package/dist/{context-decorator-GA8-hDLe.d.mts → context-decorator-B5v3VQCN.d.mts} +4 -4
  29. package/dist/{context-decorator-GA8-hDLe.d.mts.map → context-decorator-B5v3VQCN.d.mts.map} +1 -1
  30. package/dist/core/adapter.d.mts +1 -1
  31. package/dist/core/adapter.mjs +1 -1
  32. package/dist/core/app-module.d.mts +1 -1
  33. package/dist/core/app-module.mjs +1 -1
  34. package/dist/core/cache.d.mts +1 -1
  35. package/dist/core/cache.mjs +2 -2
  36. package/dist/core/cache.mjs.map +1 -1
  37. package/dist/core/container.d.mts +1 -1
  38. package/dist/core/container.mjs +2 -2
  39. package/dist/core/cron.d.mts +1 -1
  40. package/dist/core/cron.mjs +2 -2
  41. package/dist/core/decorators.d.mts +2 -2
  42. package/dist/core/decorators.mjs +48 -16
  43. package/dist/core/decorators.mjs.map +1 -1
  44. package/dist/core/errors.d.mts +1 -1
  45. package/dist/core/errors.mjs +1 -1
  46. package/dist/core/interfaces.d.mts +1 -1
  47. package/dist/core/interfaces.mjs +35 -18
  48. package/dist/core/interfaces.mjs.map +1 -1
  49. package/dist/core/logger.d.mts +2 -2
  50. package/dist/core/logger.mjs +2 -4
  51. package/dist/core/logger.mjs.map +1 -1
  52. package/dist/core/path.d.mts +1 -1
  53. package/dist/core/path.mjs +1 -1
  54. package/dist/core/plugin.d.mts +1 -1
  55. package/dist/core/plugin.mjs +1 -1
  56. package/dist/core/reactivity.d.mts +1 -1
  57. package/dist/core/reactivity.mjs +1 -1
  58. package/dist/{core-DANnH5-e.mjs → core-DBcoqPHM.mjs} +282 -8
  59. package/dist/core-DBcoqPHM.mjs.map +1 -0
  60. package/dist/cors-BfgqfLPd.d.mts +48 -0
  61. package/dist/cors-BfgqfLPd.d.mts.map +1 -0
  62. package/dist/{cron-CfsPdi7R.d.mts → cron-7zqvsmMI.d.mts} +1 -1
  63. package/dist/{cron-CfsPdi7R.d.mts.map → cron-7zqvsmMI.d.mts.map} +1 -1
  64. package/dist/csrf-DiK9zept.d.mts +52 -0
  65. package/dist/csrf-DiK9zept.d.mts.map +1 -0
  66. package/dist/{decorators-H42oPg0m.d.mts → decorators-BMvaLliz.d.mts} +147 -12
  67. package/dist/decorators-BMvaLliz.d.mts.map +1 -0
  68. package/dist/{env-Cs8Wt8A_.mjs → env-CdH5-dM_.mjs} +3 -4
  69. package/dist/{env-Cs8Wt8A_.mjs.map → env-CdH5-dM_.mjs.map} +1 -1
  70. package/dist/error-handler-Xud_3Lah.d.mts +20 -0
  71. package/dist/error-handler-Xud_3Lah.d.mts.map +1 -0
  72. package/dist/{errors-D_CWI7Bl.d.mts → errors-uaHCeXRz.d.mts} +1 -1
  73. package/dist/{errors-D_CWI7Bl.d.mts.map → errors-uaHCeXRz.d.mts.map} +1 -1
  74. package/dist/{execution-context-Dl2CKqSo.d.mts → execution-context-DKnt61pY.d.mts} +1 -1
  75. package/dist/{execution-context-Dl2CKqSo.d.mts.map → execution-context-DKnt61pY.d.mts.map} +1 -1
  76. package/dist/helmet-CaMbjzBG.d.mts +41 -0
  77. package/dist/helmet-CaMbjzBG.d.mts.map +1 -0
  78. package/dist/http/application.d.mts +2 -293
  79. package/dist/http/application.mjs +2 -2
  80. package/dist/http/bootstrap.d.mts +2 -27
  81. package/dist/http/bootstrap.mjs +2 -2
  82. package/dist/http/context.d.mts +3 -251
  83. package/dist/http/context.mjs +2 -2
  84. package/dist/http/middleware/cors.d.mts +2 -47
  85. package/dist/http/middleware/cors.mjs +1 -1
  86. package/dist/http/middleware/csrf.d.mts +2 -51
  87. package/dist/http/middleware/csrf.mjs +2 -2
  88. package/dist/http/middleware/csrf.mjs.map +1 -1
  89. package/dist/http/middleware/error-handler.d.mts +2 -19
  90. package/dist/http/middleware/error-handler.mjs +2 -2
  91. package/dist/http/middleware/helmet.d.mts +2 -40
  92. package/dist/http/middleware/helmet.mjs +1 -1
  93. package/dist/http/middleware/rate-limit.d.mts +2 -55
  94. package/dist/http/middleware/rate-limit.mjs +2 -2
  95. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  96. package/dist/http/middleware/request-id.d.mts +2 -9
  97. package/dist/http/middleware/request-id.mjs +12 -3
  98. package/dist/http/middleware/request-id.mjs.map +1 -1
  99. package/dist/http/middleware/request-logger.d.mts +2 -31
  100. package/dist/http/middleware/request-logger.mjs +2 -2
  101. package/dist/http/middleware/session.d.mts +2 -69
  102. package/dist/http/middleware/session.mjs +1 -1
  103. package/dist/http/middleware/spa.d.mts +2 -100
  104. package/dist/http/middleware/spa.mjs +5 -5
  105. package/dist/http/middleware/spa.mjs.map +1 -1
  106. package/dist/http/middleware/upload.d.mts +2 -78
  107. package/dist/http/middleware/upload.mjs +1 -1
  108. package/dist/http/middleware/validate.d.mts +2 -22
  109. package/dist/http/middleware/validate.mjs +2 -2
  110. package/dist/http/middleware/views.d.mts +2 -61
  111. package/dist/http/middleware/views.mjs +16 -15
  112. package/dist/http/middleware/views.mjs.map +1 -1
  113. package/dist/http/query/index.d.mts +1 -1
  114. package/dist/http/query/index.mjs +2 -2
  115. package/dist/http/router-builder.d.mts +2 -32
  116. package/dist/http/router-builder.mjs +10 -14
  117. package/dist/http/router-builder.mjs.map +1 -1
  118. package/dist/{index-RNK41JPE.d.mts → index-B9cyOQAe.d.mts} +1 -1
  119. package/dist/{index-RNK41JPE.d.mts.map → index-B9cyOQAe.d.mts.map} +1 -1
  120. package/dist/{index-Cf-MGrqT.d.mts → index-D-qhXg9M.d.mts} +3 -3
  121. package/dist/{index-Cf-MGrqT.d.mts.map → index-D-qhXg9M.d.mts.map} +1 -1
  122. package/dist/{index-BQM9pJrV.d.mts → index-DQyWtyp0.d.mts} +241 -5
  123. package/dist/index-DQyWtyp0.d.mts.map +1 -0
  124. package/dist/index.d.mts +34 -152
  125. package/dist/index.mjs +14 -14
  126. package/dist/interfaces-B50n7dwl.d.mts +71 -0
  127. package/dist/{interfaces-CwcdqfNq.d.mts.map → interfaces-B50n7dwl.d.mts.map} +1 -1
  128. package/dist/{logger-GK8yT0BD.d.mts → logger-CLVRZf2N.d.mts} +2 -4
  129. package/dist/{logger-GK8yT0BD.d.mts.map → logger-CLVRZf2N.d.mts.map} +1 -1
  130. package/dist/{metadata-BFuoSEX6.mjs → metadata-VQM9wChy.mjs} +2 -2
  131. package/dist/{metadata-BFuoSEX6.mjs.map → metadata-VQM9wChy.mjs.map} +1 -1
  132. package/dist/{path-Bj3vZMUY.d.mts → path-Diviu6hv.d.mts} +1 -1
  133. package/dist/path-Diviu6hv.d.mts.map +1 -0
  134. package/dist/{plugin-3rKA0Loy.d.mts → plugin-WdrDgNzk.d.mts} +45 -7
  135. package/dist/plugin-WdrDgNzk.d.mts.map +1 -0
  136. package/dist/{query-BcYEjYyX.mjs → query-DJMxdx5r.mjs} +2 -2
  137. package/dist/{query-BcYEjYyX.mjs.map → query-DJMxdx5r.mjs.map} +1 -1
  138. package/dist/rate-limit-DUwoICtI.d.mts +56 -0
  139. package/dist/rate-limit-DUwoICtI.d.mts.map +1 -0
  140. package/dist/{reactivity-CczHu3R-.d.mts → reactivity-CfJceo4H.d.mts} +1 -1
  141. package/dist/{reactivity-CczHu3R-.d.mts.map → reactivity-CfJceo4H.d.mts.map} +1 -1
  142. package/dist/request-id-BgglvZHN.d.mts +19 -0
  143. package/dist/request-id-BgglvZHN.d.mts.map +1 -0
  144. package/dist/request-logger-CWHbAzTE.d.mts +32 -0
  145. package/dist/request-logger-CWHbAzTE.d.mts.map +1 -0
  146. package/dist/router-builder-C799BAf0.d.mts +31 -0
  147. package/dist/router-builder-C799BAf0.d.mts.map +1 -0
  148. package/dist/session-N0hActOO.d.mts +70 -0
  149. package/dist/session-N0hActOO.d.mts.map +1 -0
  150. package/dist/spa-CrFR2_cz.d.mts +101 -0
  151. package/dist/spa-CrFR2_cz.d.mts.map +1 -0
  152. package/dist/upload-BueOnnLw.d.mts +79 -0
  153. package/dist/upload-BueOnnLw.d.mts.map +1 -0
  154. package/dist/validate-HwAyWTwH.d.mts +23 -0
  155. package/dist/validate-HwAyWTwH.d.mts.map +1 -0
  156. package/dist/views-DhQSXV2P.d.mts +176 -0
  157. package/dist/views-DhQSXV2P.d.mts.map +1 -0
  158. package/package.json +6 -9
  159. package/dist/adapter-DLEHb0K6.d.mts.map +0 -1
  160. package/dist/application-x8CXLOlv.mjs.map +0 -1
  161. package/dist/chunk-Bt-rz0Tp.mjs +0 -15
  162. package/dist/container-Dnk43k54.mjs.map +0 -1
  163. package/dist/container-fIS1uLx-.d.mts.map +0 -1
  164. package/dist/context-OktlOQBQ.mjs.map +0 -1
  165. package/dist/core-DANnH5-e.mjs.map +0 -1
  166. package/dist/decorators-H42oPg0m.d.mts.map +0 -1
  167. package/dist/http/application.d.mts.map +0 -1
  168. package/dist/http/bootstrap.d.mts.map +0 -1
  169. package/dist/http/context.d.mts.map +0 -1
  170. package/dist/http/middleware/cors.d.mts.map +0 -1
  171. package/dist/http/middleware/csrf.d.mts.map +0 -1
  172. package/dist/http/middleware/error-handler.d.mts.map +0 -1
  173. package/dist/http/middleware/helmet.d.mts.map +0 -1
  174. package/dist/http/middleware/rate-limit.d.mts.map +0 -1
  175. package/dist/http/middleware/request-id.d.mts.map +0 -1
  176. package/dist/http/middleware/request-logger.d.mts.map +0 -1
  177. package/dist/http/middleware/session.d.mts.map +0 -1
  178. package/dist/http/middleware/spa.d.mts.map +0 -1
  179. package/dist/http/middleware/upload.d.mts.map +0 -1
  180. package/dist/http/middleware/validate.d.mts.map +0 -1
  181. package/dist/http/middleware/views.d.mts.map +0 -1
  182. package/dist/http/router-builder.d.mts.map +0 -1
  183. package/dist/index-BQM9pJrV.d.mts.map +0 -1
  184. package/dist/index.d.mts.map +0 -1
  185. package/dist/interfaces-CwcdqfNq.d.mts +0 -54
  186. package/dist/path-Bj3vZMUY.d.mts.map +0 -1
  187. package/dist/plugin-3rKA0Loy.d.mts.map +0 -1
package/README.md CHANGED
@@ -1,244 +1,45 @@
1
- # KickJS
1
+ # @forinda/kickjs
2
2
 
3
- A production-grade, decorator-driven Node.js framework built on Express 5 and TypeScript.
3
+ Decorator-driven Node.js framework on Express 5 + TypeScript. Custom DI, module system, code generators, Zod-native validation, Vite HMR.
4
4
 
5
- NestJS ergonomics without the complexity — decorators, DI, module system, and code generators, powered by Zod and Vite.
6
-
7
- ## Install Manually
5
+ ## Install
8
6
 
9
7
  ```bash
10
- pnpm init
8
+ # Scaffold a new project (recommended)
9
+ npx @forinda/kickjs-cli new my-api && cd my-api && pnpm dev
10
+
11
+ # Or add to an existing project
11
12
  pnpm add @forinda/kickjs express reflect-metadata zod
12
13
  pnpm add -D @forinda/kickjs-cli
13
14
  ```
14
15
 
15
- ## Scaffold with CLI
16
-
17
- ```bash
18
- # Using npx
19
- npx @forinda/kickjs-cli new my-api
20
- # Using global install
21
- pnpm add -g @forinda/kickjs-cli
22
- kick new my-api
23
- # pnpm
24
- pnpm dlx @forinda/kickjs-cli new my-api
25
- # yarn
26
- yarn dlx @forinda/kickjs-cli new my-api
27
- ```
28
-
29
- ## Quick Start
30
-
31
- ```bash
32
- kick new my-api && cd my-api && kick dev
33
- ```
34
-
35
- ## Hello World
36
-
37
- A fresh `kick new my-api` scaffolds a complete project. Here are the files
38
- that matter, exactly as the CLI generates them:
39
-
40
- ```ts
41
- // src/modules/hello/hello.service.ts
42
- import { Service } from '@forinda/kickjs'
43
-
44
- @Service()
45
- export class HelloService {
46
- greet(name: string) {
47
- return { message: `Hello ${name} from KickJS!`, timestamp: new Date().toISOString() }
48
- }
49
-
50
- healthCheck() {
51
- return { status: 'ok', uptime: process.uptime() }
52
- }
53
- }
54
- ```
16
+ ## Quick Example
55
17
 
56
18
  ```ts
57
19
  // src/modules/hello/hello.controller.ts
58
- import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
59
- import { HelloService } from './hello.service'
20
+ import { Controller, Get, type RequestContext } from '@forinda/kickjs'
60
21
 
61
- @Controller()
22
+ @Controller('/hello')
62
23
  export class HelloController {
63
- @Autowired() private readonly helloService!: HelloService
64
-
65
24
  @Get('/')
66
- index(ctx: Ctx<KickRoutes.HelloController['index']>) {
67
- ctx.json(this.helloService.greet('World'))
68
- }
69
-
70
- @Get('/health')
71
- health(ctx: Ctx<KickRoutes.HelloController['health']>) {
72
- ctx.json(this.helloService.healthCheck())
73
- }
74
- }
75
- ```
76
-
77
- ```ts
78
- // src/modules/hello/hello.module.ts
79
- import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
80
- import { HelloController } from './hello.controller'
81
-
82
- export class HelloModule implements AppModule {
83
- routes(): ModuleRoutes {
84
- return {
85
- path: '/hello',
86
- router: buildRoutes(HelloController),
87
- controller: HelloController,
88
- }
25
+ hello(ctx: RequestContext) {
26
+ ctx.json({ message: 'Hello from KickJS' })
89
27
  }
90
28
  }
91
29
  ```
92
30
 
93
- ```ts
94
- // src/modules/index.ts
95
- import type { AppModuleClass } from '@forinda/kickjs'
96
- import { HelloModule } from './hello/hello.module'
97
-
98
- export const modules: AppModuleClass[] = [HelloModule]
99
- ```
100
-
101
31
  ```ts
102
32
  // src/index.ts
103
33
  import 'reflect-metadata'
104
- import './config' // registers env schema before bootstrap
105
34
  import { bootstrap } from '@forinda/kickjs'
106
35
  import { modules } from './modules'
107
36
 
108
37
  export const app = await bootstrap({ modules })
109
38
  ```
110
39
 
111
- ## What's Included
112
-
113
- Everything you need for a production API — one import:
114
-
115
- ```typescript
116
- import {
117
- // DI + Decorators
118
- Controller, Get, Post, Put, Delete, Patch,
119
- Service, Repository, Autowired, Inject, Value, Middleware,
120
- createToken, // typed DI tokens: createToken<T>('name')
121
-
122
- // Application
123
- bootstrap, Application, buildRoutes,
124
- RequestContext, type Ctx, type RouteShape,
125
-
126
- // Middleware
127
- helmet, cors, csrf, rateLimit, requestId, requestLogger,
128
- validate, upload, session, traceContext,
129
-
130
- // Query parsing
131
- parseQuery, type QueryFieldConfig, type ParsedQuery,
132
-
133
- // Utilities
134
- Container, HttpException, createLogger,
135
- ref, computed, watch,
136
-
137
- // Types
138
- type AppAdapter, type AdapterContext, type AppModule,
139
- type MiddlewareHandler, type ModuleRoutes,
140
- } from '@forinda/kickjs'
141
- ```
142
-
143
- ## Typed Routes, Body, Query, and Env
144
-
145
- `kick typegen` (auto-runs on `kick dev`) generates `KickRoutes` and `KickEnv`
146
- from your codebase. Route handlers, request bodies, query strings, and
147
- `@Value` injections are all type-checked end-to-end:
148
-
149
- ```ts
150
- import { Controller, Post, Value, type Ctx } from '@forinda/kickjs'
151
- import { z } from 'zod'
152
-
153
- const createUserBody = z.object({ name: z.string(), email: z.string().email() })
154
-
155
- @Controller('/users')
156
- class UserController {
157
- // Typed env injection — keys come from KickEnv (your src/config/index.ts)
158
- @Value('DATABASE_URL') private dbUrl!: string
159
-
160
- @Post('/', { body: createUserBody, name: 'CreateUser' })
161
- create(ctx: Ctx<KickRoutes.UserController['create']>) {
162
- ctx.body.email // ✅ string — inferred from the Zod schema
163
- ctx.created({ id: '1', ...ctx.body })
164
- }
165
- }
166
- ```
167
-
168
- ## Typed DI Tokens
169
-
170
- ```typescript
171
- import { createToken, Inject, Service } from '@forinda/kickjs'
172
-
173
- export const USER_REPO = createToken<UserRepository>('user.repo')
174
-
175
- @Service()
176
- class UserService {
177
- constructor(@Inject(USER_REPO) private readonly repo: UserRepository) {}
178
- // repo is typed as UserRepository — no casts
179
- }
180
- ```
181
-
182
- ## Typed Adapter Hooks
183
-
184
- ```typescript
185
- import type { AppAdapter, AdapterContext } from '@forinda/kickjs'
186
-
187
- class MyAdapter implements AppAdapter {
188
- name = 'MyAdapter'
189
-
190
- beforeMount({ app, container, isProduction }: AdapterContext) {
191
- // app: Express, container: Container, isProduction: boolean
192
- app.use(myMiddleware())
193
- }
194
-
195
- afterStart({ server }: AdapterContext) {
196
- // server: http.Server — attach WebSocket, etc.
197
- }
198
-
199
- async shutdown() {
200
- await cleanup()
201
- }
202
- }
203
- ```
204
-
205
- ## Ecosystem
206
-
207
- | Package | Description |
208
- |---------|-------------|
209
- | [`@forinda/kickjs`](https://www.npmjs.com/package/@forinda/kickjs) | Core framework (DI, decorators, Express 5, middleware) |
210
- | [`@forinda/kickjs-config`](https://www.npmjs.com/package/@forinda/kickjs-config) | Zod-based env validation, ConfigService, `@Value` |
211
- | [`@forinda/kickjs-swagger`](https://www.npmjs.com/package/@forinda/kickjs-swagger) | Auto OpenAPI from decorators + Zod schemas |
212
- | [`@forinda/kickjs-cli`](https://www.npmjs.com/package/@forinda/kickjs-cli) | Scaffolding, DDD generators, custom commands |
213
- | [`@forinda/kickjs-testing`](https://www.npmjs.com/package/@forinda/kickjs-testing) | `createTestApp`, `createTestModule` |
214
- | [`@forinda/kickjs-prisma`](https://www.npmjs.com/package/@forinda/kickjs-prisma) | Prisma adapter (v5/6/7) |
215
- | [`@forinda/kickjs-drizzle`](https://www.npmjs.com/package/@forinda/kickjs-drizzle) | Drizzle adapter, query builder |
216
- | [`@forinda/kickjs-auth`](https://www.npmjs.com/package/@forinda/kickjs-auth) | JWT, API key, OAuth strategies |
217
- | [`@forinda/kickjs-ws`](https://www.npmjs.com/package/@forinda/kickjs-ws) | WebSocket with `@WsController` |
218
- | [`@forinda/kickjs-queue`](https://www.npmjs.com/package/@forinda/kickjs-queue) | BullMQ, RabbitMQ, Kafka |
219
- | [`@forinda/kickjs-cron`](https://www.npmjs.com/package/@forinda/kickjs-cron) | `@Cron` decorator scheduling |
220
- | [`@forinda/kickjs-mailer`](https://www.npmjs.com/package/@forinda/kickjs-mailer) | SMTP, Resend, SES |
221
- | [`@forinda/kickjs-graphql`](https://www.npmjs.com/package/@forinda/kickjs-graphql) | `@Resolver`, `@Query`, `@Mutation` |
222
- | [`@forinda/kickjs-otel`](https://www.npmjs.com/package/@forinda/kickjs-otel) | OpenTelemetry tracing + metrics |
223
- | [`@forinda/kickjs-devtools`](https://www.npmjs.com/package/@forinda/kickjs-devtools) | Debug dashboard at `/_debug` |
224
- | [`@forinda/kickjs-notifications`](https://www.npmjs.com/package/@forinda/kickjs-notifications) | Email, Slack, Discord, webhook |
225
- | [`@forinda/kickjs-multi-tenant`](https://www.npmjs.com/package/@forinda/kickjs-multi-tenant) | Tenant resolution middleware |
226
- | [`@forinda/kickjs-ai`](https://www.npmjs.com/package/@forinda/kickjs-ai) | Providers (OpenAI, Anthropic), `@AiTool`, memory, RAG, agent loop |
227
- | [`@forinda/kickjs-mcp`](https://www.npmjs.com/package/@forinda/kickjs-mcp) | Model Context Protocol server adapter + `kick mcp` CLI |
228
-
229
- ## CLI
230
-
231
- ```bash
232
- kick new my-api # Scaffold project
233
- kick dev # Vite HMR dev server
234
- kick build # Production build
235
- kick g module users # Generate full DDD module (18 files)
236
- kick g module users --repo prisma # With Prisma repository
237
- ```
238
-
239
40
  ## Documentation
240
41
 
241
- [forinda.github.io/kick-js](https://forinda.github.io/kick-js/)
42
+ [forinda.github.io/kick-js](https://forinda.github.io/kick-js/) — full guide, API reference, tutorials, and example apps.
242
43
 
243
44
  ## License
244
45
 
@@ -1,10 +1,72 @@
1
1
 
2
- import { i as Constructor, o as MaybePromise } from "./interfaces-CwcdqfNq.mjs";
3
- import { t as Container } from "./container-fIS1uLx-.mjs";
4
- import { r as ContributorRegistration } from "./context-decorator-GA8-hDLe.mjs";
2
+ import { i as Constructor, o as MaybePromise } from "./interfaces-B50n7dwl.mjs";
3
+ import { t as Container } from "./container-CnWDsxi-.mjs";
4
+ import { r as ContributorRegistration } from "./context-decorator-B5v3VQCN.mjs";
5
5
  import http from "node:http";
6
6
  import { Express } from "express";
7
7
 
8
+ //#region src/core/augmentation.d.ts
9
+ /**
10
+ * Augmentation registry — runtime no-op + the canonical
11
+ * `KickJsPluginRegistry` interface that `kick typegen` augments.
12
+ *
13
+ * See `architecture.md` §21.2.1 (typegen for `dependsOn`) and §21.3.3
14
+ * (standardized augmentation registry) for the design rationale.
15
+ *
16
+ * @module @forinda/kickjs/core/augmentation
17
+ */
18
+ /**
19
+ * Marker interface that lists every plugin/adapter in the project. The
20
+ * keys are the literal `name` field passed to `defineAdapter` /
21
+ * `definePlugin` (or declared on a `class implements AppAdapter`); the
22
+ * values are the kind tag (`'plugin' | 'adapter'`).
23
+ *
24
+ * The framework ships this empty. `kick typegen` augments it from
25
+ * source so `keyof KickJsPluginRegistry` resolves to a string-literal
26
+ * union of every name in scope — and therefore so do `dependsOn`
27
+ * declarations on plugins/adapters.
28
+ */
29
+ interface KickJsPluginRegistry {}
30
+ /**
31
+ * Resolves to a string-literal union of every registered plugin/adapter
32
+ * name when the project's typegen has populated `KickJsPluginRegistry`,
33
+ * or to `string` when the registry is empty (no typegen pass yet).
34
+ *
35
+ * Falling back to `string` keeps fresh projects compiling — the typegen
36
+ * narrowing is a progressive enhancement, not a hard prerequisite.
37
+ */
38
+ type KickJsPluginName = keyof KickJsPluginRegistry extends never ? string : keyof KickJsPluginRegistry & string;
39
+ /**
40
+ * Metadata attached to a `defineAugmentation` call. The fields are
41
+ * documentation-only — `kick typegen` surfaces them in the generated
42
+ * `.kickjs/types/augmentations.d.ts` so adopters can browse every
43
+ * augmentable interface from one place.
44
+ */
45
+ interface AugmentationMeta {
46
+ /** One-line description of what the augmentation customises. */
47
+ description?: string;
48
+ /** Tiny TS snippet showing a typical shape (`'{ foo: string }'`). */
49
+ example?: string;
50
+ }
51
+ /**
52
+ * Advertise an augmentable interface so `kick typegen` can list it in
53
+ * `.kickjs/types/augmentations.d.ts`. Runtime no-op — exists purely as
54
+ * a static marker for the typegen scanner to discover.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { defineAugmentation } from '@forinda/kickjs'
59
+ *
60
+ * export interface FeatureFlags {} // augmentable
61
+ *
62
+ * defineAugmentation('FeatureFlags', {
63
+ * description: 'Flags consumed by FlagsPlugin',
64
+ * example: '{ beta: boolean; rolloutPercentage: number }',
65
+ * })
66
+ * ```
67
+ */
68
+ declare function defineAugmentation(name: string, meta?: AugmentationMeta): void;
69
+ //#endregion
8
70
  //#region src/core/adapter.d.ts
9
71
  /**
10
72
  * Where in the middleware pipeline an adapter's middleware should be inserted.
@@ -58,7 +120,7 @@ interface AdapterContext {
58
120
  *
59
121
  * @example
60
122
  * ```ts
61
- * import type { AppAdapter, AdapterContext } from '@forinda/kickjs-core/adapter'
123
+ * import type { AppAdapter, AdapterContext } from '@forinda/kickjs/adapter'
62
124
  *
63
125
  * class SentryAdapter implements AppAdapter {
64
126
  * name = 'SentryAdapter'
@@ -78,8 +140,32 @@ interface AdapterContext {
78
140
  * ```
79
141
  */
80
142
  interface AppAdapter {
81
- /** Human-readable name for logging */
143
+ /**
144
+ * Human-readable name for logging and `dependsOn` resolution.
145
+ * Required when the adapter (or any other in the same set) declares
146
+ * `dependsOn` — sort errors will reference adapters by name.
147
+ */
82
148
  name?: string;
149
+ /**
150
+ * Other adapter names that must mount before this one. The framework
151
+ * topologically sorts adapters at boot — cycles or unknown names throw
152
+ * via `MountCycleError` / `MissingMountDepError` so bad configurations
153
+ * fail boot rather than corrupt live traffic.
154
+ *
155
+ * Common pattern: `TenantAdapter` populates `req.tenant` and
156
+ * `AuthAdapter` reads it for tenant-scoped RBAC, so AuthAdapter
157
+ * declares `dependsOn = ['TenantAdapter']`. Adapters without
158
+ * `dependsOn` retain their declaration order.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * class AuthAdapter implements AppAdapter {
163
+ * name = 'AuthAdapter'
164
+ * dependsOn = ['TenantAdapter']
165
+ * }
166
+ * ```
167
+ */
168
+ dependsOn?: readonly KickJsPluginName[];
83
169
  /**
84
170
  * Return middleware entries to be inserted into the pipeline.
85
171
  * The `phase` controls ordering relative to global middleware and routes.
@@ -143,9 +229,33 @@ interface AppAdapter {
143
229
  }>;
144
230
  /** Called on shutdown — clean up connections */
145
231
  shutdown?(): MaybePromise;
232
+ /**
233
+ * Optional DevTools introspection hook (architecture.md §23). Returns
234
+ * a snapshot describing this adapter's current state, metrics, and DI
235
+ * tokens. DevTools awaits the result, so async work is fine — but keep
236
+ * the implementation cheap (counters + flags, no DB round trips) since
237
+ * the topology endpoint polls on a short interval.
238
+ *
239
+ * The return type is intentionally untyped at this layer to avoid
240
+ * `@forinda/kickjs` taking on a runtime dep on `@forinda/kickjs-devtools-kit`.
241
+ * Adapter authors should import and return `IntrospectionSnapshot`
242
+ * from `@forinda/kickjs-devtools-kit` directly.
243
+ */
244
+ introspect?(): unknown | Promise<unknown>;
245
+ /**
246
+ * Optional DevTools tabs this adapter contributes (architecture.md §23).
247
+ * Returns an array of `DevtoolsTabDescriptor` shapes — typically one
248
+ * entry per adapter-owned panel (iframe / launch / html view).
249
+ *
250
+ * Same untyped-at-this-layer convention as {@link introspect}: adapter
251
+ * authors import `defineDevtoolsTab` (or the bare type) from
252
+ * `@forinda/kickjs-devtools-kit` so `@forinda/kickjs` doesn't take on
253
+ * a runtime dep on the kit.
254
+ */
255
+ devtoolsTabs?(): readonly unknown[];
146
256
  }
147
257
  /** Constructor type for AppAdapter classes */
148
258
  type AppAdapterClass = new () => AppAdapter;
149
259
  //#endregion
150
- export { MiddlewarePhase as a, AppAdapterClass as i, AdapterMiddleware as n, AppAdapter as r, AdapterContext as t };
151
- //# sourceMappingURL=adapter-DLEHb0K6.d.mts.map
260
+ export { MiddlewarePhase as a, KickJsPluginRegistry as c, AppAdapterClass as i, defineAugmentation as l, AdapterMiddleware as n, AugmentationMeta as o, AppAdapter as r, KickJsPluginName as s, AdapterContext as t };
261
+ //# sourceMappingURL=adapter-BNw2pGbg.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter-BNw2pGbg.d.mts","names":[],"sources":["../src/core/augmentation.ts","../src/core/adapter.ts"],"mappings":";;;;;;;;;;;;;;;AAqBA;;;;;AAUA;;;;;AAUA;;;UApBiB,oBAAA;AA4CjB;;;;;;;;AAAA,KAlCY,gBAAA,SAAyB,oBAAA,gCAE3B,oBAAA;;;;AClBV;;;UD0BiB,gBAAA;EC1BU;ED4B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js";
2
+ import { t as Container } from "./container-CnWDsxi-.mjs";
3
+ import { r as ContributorRegistration } from "./context-decorator-B5v3VQCN.mjs";
4
4
 
5
5
  //#region src/core/app-module.d.ts
6
6
  /**
@@ -47,4 +47,4 @@ interface AppModule {
47
47
  type AppModuleClass = new () => AppModule;
48
48
  //#endregion
49
49
  export { AppModuleClass as n, ModuleRoutes as r, AppModule as t };
50
- //# sourceMappingURL=app-module-ERR9jhow.d.mts.map
50
+ //# sourceMappingURL=app-module-CO0ksPCm.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"app-module-ERR9jhow.d.mts","names":[],"sources":["../src/core/app-module.ts"],"mappings":";;;;;;;AAOA;;UAAiB,YAAA;EAAY;EAE3B,IAAA;EAEA;EAAA,MAAA;EAIA;EAFA,OAAA;EAEU;EAAV,UAAA;AAAA;;;;;;;;;;;;UAce,SAAA;EAWE;EATjB,QAAA,EAAU,SAAA,EAAW,SAAA;EAWrB;;;;;AAIF;;;EANE,YAAA,KAAiB,uBAAA,cAAqC,uBAAA;EAMR;EAJ9C,MAAA,IAAU,YAAA,GAAe,YAAA;AAAA;;KAIf,cAAA,aAA2B,SAAA"}
1
+ {"version":3,"file":"app-module-CO0ksPCm.d.mts","names":[],"sources":["../src/core/app-module.ts"],"mappings":";;;;;;;AAOA;;UAAiB,YAAA;EAAY;EAE3B,IAAA;EAEA;EAAA,MAAA;EAIA;EAFA,OAAA;EAEU;EAAV,UAAA;AAAA;;;;;;;;;;;;UAce,SAAA;EAWE;EATjB,QAAA,EAAU,SAAA,EAAW,SAAA;EAWrB;;;;;AAIF;;;EANE,YAAA,KAAiB,uBAAA,cAAqC,uBAAA;EAMR;EAJ9C,MAAA,IAAU,YAAA,GAAe,YAAA;AAAA;;KAIf,cAAA,aAA2B,SAAA"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v3.2.0
2
+ * @forinda/kickjs v4.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,15 +8,15 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
+ import { t as Container } from "./container-DYYSu58w.mjs";
11
12
  import { METADATA } from "./core/interfaces.mjs";
12
13
  import { Logger, createLogger } from "./core/logger.mjs";
13
- import { t as getClassMeta } from "./metadata-BFuoSEX6.mjs";
14
- import { t as Container } from "./container-Dnk43k54.mjs";
14
+ import { t as getClassMeta } from "./metadata-VQM9wChy.mjs";
15
15
  import { normalizePath } from "./core/path.mjs";
16
- import "./core-DANnH5-e.mjs";
16
+ import { s as mountSort } from "./core-DBcoqPHM.mjs";
17
17
  import { requestId } from "./http/middleware/request-id.mjs";
18
18
  import { errorHandler, notFoundHandler } from "./http/middleware/error-handler.mjs";
19
- import { r as requestStore } from "./context-OktlOQBQ.mjs";
19
+ import { r as requestStore } from "./context-BAGzqT7-.mjs";
20
20
  import { _setExternalContributorSources } from "./http/router-builder.mjs";
21
21
  import http from "node:http";
22
22
  import express from "express";
@@ -43,11 +43,13 @@ const REQUEST_SCOPE_MIDDLEWARE_MARKER = Symbol.for("@kickjs/requestScopeMiddlewa
43
43
  function requestScopeMiddleware() {
44
44
  const mw = (req, _res, next) => {
45
45
  const requestIdHeader = req.headers["x-request-id"];
46
+ const requestId = (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID();
46
47
  const store = {
47
- requestId: (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID(),
48
+ requestId,
48
49
  instances: /* @__PURE__ */ new Map(),
49
50
  values: /* @__PURE__ */ new Map()
50
51
  };
52
+ req.requestId = requestId;
51
53
  requestStore.run(store, () => next());
52
54
  };
53
55
  mw[REQUEST_SCOPE_MIDDLEWARE_MARKER] = true;
@@ -89,8 +91,17 @@ var Application = class {
89
91
  this.options = options;
90
92
  this.app = express();
91
93
  this.container = Container.getInstance();
92
- this.plugins = options.plugins ?? [];
93
- this.adapters = [...this.plugins.flatMap((p) => p.adapters?.() ?? []), ...options.adapters ?? []];
94
+ this.plugins = mountSort(options.plugins ?? [], "plugin");
95
+ const allAdapters = [...this.plugins.flatMap((p) => p.adapters?.() ?? []), ...options.adapters ?? []];
96
+ let anonAdapterCount = 0;
97
+ this.adapters = mountSort(allAdapters.map((adapter) => {
98
+ if (!adapter.name) {
99
+ const ctorName = adapter.constructor?.name;
100
+ const fallback = ctorName && ctorName !== "Object" ? ctorName : `AnonymousAdapter#${anonAdapterCount++}`;
101
+ return Object.assign(adapter, { name: fallback });
102
+ }
103
+ return adapter;
104
+ }), "adapter");
94
105
  Container._requestStoreProvider = () => requestStore.getStore() ?? null;
95
106
  Logger._contextProvider = () => {
96
107
  const store = requestStore.getStore();
@@ -420,6 +431,14 @@ var Application = class {
420
431
  getAdapters() {
421
432
  return this.adapters;
422
433
  }
434
+ /**
435
+ * Get registered plugins — used by DevToolsAdapter for topology
436
+ * introspection (architecture.md §23). Read-only; returns the
437
+ * already-sorted plugin list (post-`dependsOn` topo-sort).
438
+ */
439
+ getPlugins() {
440
+ return this.plugins;
441
+ }
423
442
  getHttpServer() {
424
443
  return this.httpServer;
425
444
  }
@@ -520,4 +539,4 @@ var Application = class {
520
539
  //#endregion
521
540
  export { requestScopeMiddleware as n, Application as t };
522
541
 
523
- //# sourceMappingURL=application-x8CXLOlv.mjs.map
542
+ //# sourceMappingURL=application-Ce4DQN6m.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-Ce4DQN6m.mjs","names":[],"sources":["../src/http/middleware/request-scope.ts","../src/http/application.ts"],"sourcesContent":["import crypto from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\nimport { requestStore, type RequestStore } from '../request-store'\n\n/**\n * Marker symbol stamped on the function returned by {@link requestScopeMiddleware}.\n *\n * `Application.setup()` uses {@link isRequestScopeMiddleware} to detect whether\n * the user-supplied middleware list already contains the request-scope wrapper,\n * and skips its automatic auto-mount when one is found. Lets adopters control\n * the exact position of the ALS frame in their pipeline (e.g., after a custom\n * tracing wrapper) without ending up with two nested frames.\n */\n// `Symbol.for(...)` returns a plain `symbol` (not `unique symbol`), but the\n// runtime detection marker doesn't need the unique nominal property — it only\n// needs the interned-slot reference equality that `Symbol.for` already provides.\nconst REQUEST_SCOPE_MIDDLEWARE_MARKER = Symbol.for('@kickjs/requestScopeMiddleware')\n\n/**\n * Wraps each request in an AsyncLocalStorage context.\n * Enables REQUEST-scoped DI and automatic requestId propagation to logs.\n *\n * Should be mounted early in the middleware pipeline (before route handlers).\n * `Application` mounts this automatically unless `contextStore: 'manual'` is set\n * or the user already includes one in their middleware list.\n */\nexport function requestScopeMiddleware() {\n const mw = (req: Request, _res: Response, next: NextFunction) => {\n const requestIdHeader = req.headers['x-request-id']\n const requestId =\n (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID()\n const store: RequestStore = {\n requestId,\n instances: new Map(),\n // Explicit generic locks the \"string keys only\" decision\n // (architecture.md §20.12 #4) at construction time, so accidental\n // non-string keys can't slip in via the inferred Map<any, any>.\n values: new Map<string, unknown>(),\n }\n // Surface the requestId on req so the standalone requestId() middleware\n // (when also mounted) reuses this value instead of generating a divergent\n // second one. Without this, log lines that read from the ALS store would\n // disagree with the X-Request-Id response header for any request that\n // didn't carry an inbound x-request-id header.\n ;(req as Request & { requestId?: string }).requestId = requestId\n requestStore.run(store, () => next())\n }\n ;(mw as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] = true\n return mw\n}\n\n/**\n * Returns `true` when `value` is the function produced by {@link requestScopeMiddleware}.\n *\n * Detection uses a `Symbol.for(...)` marker so the check survives different\n * copies of `@forinda/kickjs` loaded under different module identities (e.g.,\n * a published package alongside a workspace-linked one during local dev).\n */\nexport function isRequestScopeMiddleware(value: unknown): boolean {\n if (typeof value !== 'function') return false\n return (value as unknown as Record<symbol, unknown>)[REQUEST_SCOPE_MIDDLEWARE_MARKER] === true\n}\n","import http from 'node:http'\nimport express, { type Express, type RequestHandler } from 'express'\nimport {\n Container,\n createLogger,\n Logger,\n normalizePath,\n METADATA,\n type AppModule,\n type AppModuleClass,\n type AppAdapter,\n type AdapterContext,\n type AdapterMiddleware,\n type ContributorRegistration,\n type KickPlugin,\n type RouteDefinition,\n type SourcedRegistration,\n mountSort,\n} from '../core'\nimport { getClassMeta } from '../core/metadata'\nimport { requestId } from './middleware/request-id'\nimport { notFoundHandler, errorHandler } from './middleware/error-handler'\nimport { requestScopeMiddleware, isRequestScopeMiddleware } from './middleware/request-scope'\nimport { _setExternalContributorSources } from './router-builder'\nimport { requestStore, getRequestStore } from './request-store'\n\nconst log = createLogger('Application')\n\n/**\n * A middleware entry in the declarative pipeline.\n * Can be a bare handler or an object with path scoping.\n */\nexport type MiddlewareEntry = RequestHandler | { path: string; handler: RequestHandler }\n\nexport interface ApplicationOptions {\n /** Feature modules to load */\n modules: AppModuleClass[]\n /** Adapters that hook into the lifecycle (DB, Redis, Swagger, etc.) */\n adapters?: AppAdapter[]\n /** Server port (falls back to PORT env var, then 3000) */\n port?: number\n /** Global API prefix (default: '/api') */\n apiPrefix?: string\n /** Default API version (default: 1) — routes become /{prefix}/v{version}/{path} */\n defaultVersion?: number\n\n /**\n * Global middleware pipeline. Declared in order.\n * Replaces the hardcoded middleware stack — you control exactly what runs.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * middleware: [\n * helmet(),\n * cors(),\n * compression(),\n * morgan('dev'),\n * express.json({ limit: '1mb' }),\n * ],\n * })\n * ```\n *\n * If omitted, a sensible default is applied:\n * requestId(), express.json({ limit: '100kb' })\n */\n middleware?: MiddlewareEntry[]\n\n /** Plugins that bundle modules, adapters, middleware, and DI bindings */\n plugins?: KickPlugin[]\n\n /**\n * Global Context Contributors (#107) that apply to every route in the\n * application. Merge into the per-route pipeline at the `'global'`\n * precedence level — they lose to module, adapter, class, and method\n * contributors with the same key, providing app-wide defaults that any\n * narrower scope can override.\n *\n * @example\n * ```ts\n * const StartedAt = defineContextDecorator({\n * key: 'requestStartedAt',\n * resolve: () => Date.now(),\n * })\n *\n * bootstrap({\n * modules,\n * contributors: [StartedAt.registration],\n * })\n * ```\n */\n contributors?: ContributorRegistration[] | readonly ContributorRegistration[]\n\n /**\n * Backing store strategy for {@link RequestContext} `set/get` and the\n * Context Contributor pipeline (#107).\n *\n * - `'auto'` (default) — Application mounts {@link requestScopeMiddleware}\n * automatically before any user middleware. If the user-supplied\n * `middleware` list already includes `requestScopeMiddleware()`,\n * detection skips the auto-mount so adopters can control its position.\n * - `'manual'` — Application never mounts the wrapper. The Context\n * Contributor pipeline still runs on every route — the runner is\n * inserted by `router-builder` regardless of ALS state. What\n * degrades without an ALS frame is the *backing store*:\n * REQUEST-scoped DI throws (no `requestStore.getStore()` to read\n * from), `Logger` loses its requestId context, and\n * `RequestContext.set/get` throws. Use `'manual'` only when you\n * genuinely intend to wrap requests in your own ALS frame (rare —\n * multi-tenant adapters used to do this; post-Phase 3 they share\n * the framework's frame instead).\n */\n contextStore?: 'auto' | 'manual'\n\n /** Express `trust proxy` setting */\n trustProxy?: boolean | number | string | ((ip: string, hopIndex: number) => boolean)\n /** Maximum JSON body size (only used when middleware is not provided) */\n jsonLimit?: string | number\n /**\n * Log route summary on startup. Default: true in dev, false in production.\n * Set to `true` to always log, `false` to always suppress.\n */\n logRoutesTable?: boolean\n /**\n * Maximum time (ms) to wait for graceful shutdown before forcing exit.\n * Default: 30000 (30 seconds). Set to 0 to disable forced exit.\n */\n shutdownTimeout?: number\n\n /**\n * Enable cluster mode for multi-core utilization.\n *\n * When enabled, the primary process forks worker processes that share the\n * same port via Node's built-in `cluster` module (OS load balancing).\n *\n * - `true` — use all available CPU cores\n * - `{ workers: N }` — use exactly N workers\n *\n * Workers are auto-restarted on crash. SIGTERM/SIGINT on the primary is\n * forwarded to all workers.\n *\n * @example\n * ```ts\n * bootstrap({ modules, cluster: true })\n * bootstrap({ modules, cluster: { workers: 4 } })\n * ```\n */\n cluster?: boolean | { workers?: number }\n\n /**\n * Custom 404 handler for unmatched routes. Receives the raw Express\n * `(req, res, next)` args. When omitted, the built-in handler returns\n * `{ message: 'Not Found' }` with status 404.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onNotFound: (req, res) => {\n * res.status(404).json({ error: 'Route not found', path: req.originalUrl })\n * },\n * })\n * ```\n */\n onNotFound?: (req: any, res: any, next: any) => void\n\n /**\n * Custom global error handler. Receives `(err, req, res, next)` — the\n * standard Express error-handling signature. When omitted, the built-in\n * handler formats ZodError, HttpException, and unexpected errors.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * onError: (err, req, res, next) => {\n * logger.error(err)\n * res.status(err.status ?? 500).json({ error: err.message })\n * },\n * })\n * ```\n */\n onError?: (err: any, req: any, res: any, next: any) => void\n\n /**\n * Security defaults applied automatically unless opted out.\n *\n * When not specified, secure defaults are applied:\n * - Helmet security headers are auto-injected\n * - JSON body limit defaults to 1MB\n *\n * @example\n * ```ts\n * bootstrap({\n * modules,\n * security: {\n * helmet: false, // disable auto-helmet\n * },\n * })\n * ```\n */\n security?: {\n /** Auto-inject helmet security headers. Default: true */\n helmet?: boolean\n }\n}\n\n/**\n * The main application class. Wires together Express, the DI container,\n * feature modules, adapters, and the middleware pipeline.\n */\nexport class Application {\n private app: Express\n private container: Container\n private httpServer: http.Server | null = null\n private readonly adapters: AppAdapter[]\n\n private readonly plugins: KickPlugin[]\n\n /** Number of HTTP requests currently being processed */\n private _inFlightRequests = 0\n /** Whether the application is draining (shutting down gracefully) */\n private _draining = false\n /** Whether shutdown has already been initiated (prevents double-shutdown) */\n private _shutdownInitiated = false\n /** Resolvers waiting for in-flight requests to reach zero */\n private _drainResolvers: Array<() => void> = []\n\n constructor(private readonly options: ApplicationOptions) {\n this.app = express()\n this.container = Container.getInstance()\n\n // Sort plugins by `dependsOn` declarations BEFORE reading their adapters/etc.\n // Plugins without `dependsOn` keep their declaration order — this is a\n // pure refinement; no behaviour change for apps that don't use the field.\n this.plugins = mountSort(options.plugins ?? [], 'plugin')\n\n // Build adapter list from plugin adapters + user adapters, synthesize\n // a stable name for any anonymous adapter (so duplicate-name detection\n // and `dependsOn` resolution have something to key on), then sort by\n // adapter `dependsOn`. Plugin-shipped adapters keep their plugin's\n // relative order unless their own `dependsOn` says otherwise.\n const allAdapters = [\n ...this.plugins.flatMap((p) => p.adapters?.() ?? []),\n ...(options.adapters ?? []),\n ]\n let anonAdapterCount = 0\n const namedAdapters: Array<AppAdapter & { name: string }> = allAdapters.map((adapter) => {\n if (!adapter.name) {\n // `constructor.name === 'Object'` for plain object-literal adapters —\n // useless as an identity since two anonymous literals would collide.\n // Only borrow the constructor name when it's an actual class.\n const ctorName = adapter.constructor?.name\n const fallback =\n ctorName && ctorName !== 'Object' ? ctorName : `AnonymousAdapter#${anonAdapterCount++}`\n return Object.assign(adapter, { name: fallback })\n }\n return adapter as AppAdapter & { name: string }\n })\n this.adapters = mountSort(namedAdapters, 'adapter')\n // Wire the request store provider so Container can resolve REQUEST-scoped deps\n Container._requestStoreProvider = () => requestStore.getStore() ?? null\n // Wire logger context provider so logs auto-include requestId\n Logger._contextProvider = () => {\n const store = requestStore.getStore()\n if (!store) return null\n const ctx: Record<string, any> = { requestId: store.requestId }\n const traceId = store.values.get('traceId')\n if (traceId) ctx.traceId = traceId\n const spanId = store.values.get('spanId')\n if (spanId) ctx.spanId = spanId\n return ctx\n }\n }\n\n /** Whether the application is currently draining in-flight requests */\n get isDraining(): boolean {\n return this._draining\n }\n\n /** Number of HTTP requests currently being processed */\n get inFlightRequests(): number {\n return this._inFlightRequests\n }\n\n /** Get the DI container instance */\n getContainer(): Container {\n return this.container\n }\n\n /**\n * Express request handler — delegates to the internal Express app.\n *\n * Used by the Vite dev-server plugin to route requests through KickJS:\n * ```ts\n * const mod = await ssrLoadModule('virtual:kickjs/app')\n * mod.app.handle(req, res, next)\n * ```\n *\n * Also works as a standard Node.js request handler for production:\n * ```ts\n * http.createServer(app.handle.bind(app))\n * ```\n */\n handle(req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void): void {\n if (next) {\n this.app(req as any, res as any, next)\n } else {\n this.app(req as any, res as any)\n }\n }\n\n /**\n * Full setup pipeline:\n * 1. Adapter beforeMount hooks (early routes — docs, health)\n * 2. Adapter middleware (phase: beforeGlobal)\n * 3. Global middleware (user-declared or defaults)\n * 4. Adapter middleware (phase: afterGlobal)\n * 5. Module registration + DI bootstrap\n * 6. Adapter middleware (phase: beforeRoutes)\n * 7. Module route mounting\n * 8. Adapter middleware (phase: afterRoutes)\n * 9. Error handlers (notFound + global)\n * 10. Adapter beforeStart hooks\n */\n /** Build the adapter context object (shared across all hooks) */\n private adapterCtx(server?: any): AdapterContext {\n const env = process.env.NODE_ENV ?? 'development'\n return {\n app: this.app,\n container: this.container,\n server,\n env,\n isProduction: env === 'production',\n }\n }\n\n /** Call an adapter hook, awaiting async hooks and catching errors */\n private async callHook(\n hook: ((ctx: AdapterContext) => void | Promise<void>) | undefined,\n ctx: AdapterContext,\n ): Promise<void> {\n if (!hook) return\n try {\n const result = hook(ctx)\n if (result && typeof (result as Promise<void>).then === 'function') {\n await result\n }\n } catch (err) {\n log.error(err, 'Adapter hook failed')\n }\n }\n\n async setup(): Promise<void> {\n log.debug('Bootstrapping application...')\n\n // Collect adapter middleware by phase\n const adapterMw = this.collectAdapterMiddleware()\n\n // Expose the Application instance on the Express app for adapter discovery\n ;(this.app as any).__kickApp = this\n\n const ctx = this.adapterCtx()\n\n // ── 1. Adapter beforeMount hooks ──────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(adapter.beforeMount?.bind(adapter), ctx)\n }\n\n // ── 2. Hardened defaults ──────────────────────────────────────────\n this.app.disable('x-powered-by')\n this.app.set('trust proxy', this.options.trustProxy ?? false)\n\n // ── 2a. In-flight request tracking ──────────────────────────────\n this.app.use(this.requestTrackingMiddleware())\n\n // ── 2b. Health check endpoints (before middleware, at root) ──────\n this.mountHealthEndpoints()\n\n // ── 2c. Request scope (AsyncLocalStorage) ────────────────────────\n // Auto-mounted unless the user opted out (`contextStore: 'manual'`)\n // or already included one in their middleware list.\n if (this.shouldAutoMountRequestScope()) {\n this.app.use(requestScopeMiddleware())\n }\n\n // ── 3. Adapter middleware: beforeGlobal ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeGlobal)\n\n // ── 3b. Plugin registration ──────────────────────────────────────\n for (const plugin of this.plugins) {\n plugin.register?.(this.container)\n }\n\n // ── 3c. Plugin middleware ─────────────────────────────────────────\n for (const plugin of this.plugins) {\n try {\n const mw = plugin.middleware?.() ?? []\n for (const handler of mw) {\n this.app.use(handler)\n }\n } catch (err) {\n log.error(err, `Plugin middleware failed: ${(plugin as any).name ?? 'unknown'}`)\n }\n }\n\n // ── 4. Global middleware ─────────────────────────────────────────\n // Auto-inject helmet unless opted out\n const autoHelmet = this.options.security?.helmet !== false\n if (autoHelmet) {\n try {\n const { helmet: helmetFn } = await import('./middleware/helmet')\n this.app.use(helmetFn())\n } catch {\n // helmet middleware not available — skip silently\n }\n }\n\n if (this.options.middleware) {\n // User-declared pipeline — full control\n for (const entry of this.options.middleware) {\n this.mountMiddlewareEntry(entry)\n }\n } else {\n // Sensible defaults when no middleware declared\n this.app.use(requestId())\n this.app.use(express.json({ limit: this.options.jsonLimit ?? '1mb' }))\n }\n\n // ── 5. Adapter middleware: afterGlobal ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterGlobal)\n\n // ── 6. Module registration + DI bootstrap ────────────────────────\n // Plugin modules first, then user modules\n const allModuleClasses = [\n ...this.plugins.flatMap((p) => p.modules?.() ?? []),\n ...this.options.modules,\n ]\n const modules = allModuleClasses.map((ModuleClass) => {\n const mod = new ModuleClass()\n // `register()` is optional — modules whose classes are entirely\n // decorator-managed (@Service, @Controller, @Repository) don't need it.\n mod.register?.(this.container)\n return mod\n })\n this.container.bootstrap()\n\n // ── 7. Adapter middleware: beforeRoutes ───────────────────────────\n this.mountMiddlewareList(adapterMw.beforeRoutes)\n\n // ── 8. Mount module routes with versioning ───────────────────────\n const apiPrefix = this.options.apiPrefix ?? '/api'\n const defaultVersion = this.options.defaultVersion ?? 1\n const shouldLogRoutes = this.options.logRoutesTable ?? process.env.NODE_ENV !== 'production'\n\n // Collect route metadata during mounting (avoids calling mod.routes() twice)\n const mountedRoutes: Array<{ controller: any; mountPath: string }> = []\n\n // Context Contributors (#107) — collect adapter + plugin + global once;\n // per-module sources are computed inside the loop so module isolation is\n // preserved.\n //\n // Plugin contributors merge at the same `'adapter'` precedence as adapter\n // contributors. Plugins are conceptually \"bundles of adapters + extras\",\n // so a plugin that ships a typed contributor without standing up an\n // accompanying adapter behaves identically to one that does.\n const adapterSources: SourcedRegistration[] = []\n for (const adapter of this.adapters) {\n const adapterContribs = adapter.contributors?.() ?? []\n const adapterLabel = adapter.name ?? adapter.constructor.name ?? 'adapter'\n for (const registration of adapterContribs) {\n adapterSources.push({ source: 'adapter', registration, label: adapterLabel })\n }\n }\n for (const plugin of this.plugins) {\n const pluginContribs = plugin.contributors?.() ?? []\n const pluginLabel = plugin.name ?? plugin.constructor?.name ?? 'plugin'\n for (const registration of pluginContribs) {\n adapterSources.push({ source: 'adapter', registration, label: pluginLabel })\n }\n }\n const globalSources: SourcedRegistration[] = (this.options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration,\n label: 'bootstrap',\n }),\n )\n\n for (const mod of modules) {\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: mod.constructor?.name ?? 'module',\n }),\n )\n\n // Thread per-module + adapter + global sources to buildRoutes via the\n // module-scoped slot. Module setup is sequential, so the slot is\n // race-free; the finally block clears it even if mod.routes() throws.\n _setExternalContributorSources([...moduleSources, ...adapterSources, ...globalSources])\n let result: ReturnType<AppModule['routes']>\n try {\n result = mod.routes()\n } finally {\n _setExternalContributorSources([])\n }\n if (!result) continue // Non-HTTP modules (queues, cron) may return null\n\n const routeSets = Array.isArray(result) ? result : [result]\n\n for (const route of routeSets) {\n const version = route.version ?? defaultVersion\n const mountPath = `${apiPrefix}/v${version}${normalizePath(route.path)}`\n this.app.use(mountPath, route.router)\n\n // Notify adapters (e.g. SwaggerAdapter for OpenAPI spec generation)\n if (route.controller) {\n for (const adapter of this.adapters) {\n try {\n adapter.onRouteMount?.(route.controller, mountPath)\n } catch (err) {\n log.error(err, `adapter.onRouteMount() failed for ${mountPath}`)\n }\n }\n if (shouldLogRoutes) {\n mountedRoutes.push({ controller: route.controller, mountPath })\n }\n }\n }\n }\n\n // ── 8b. Log route summary ─────────────────────────────────────────\n if (shouldLogRoutes && mountedRoutes.length > 0) {\n const methodOrder = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']\n const methodRank = (m: string) => {\n const i = methodOrder.indexOf(m)\n return i === -1 ? 99 : i\n }\n\n let totalRoutes = 0\n log.debug('Routes:')\n\n for (const { controller, mountPath } of mountedRoutes) {\n const defs: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controller,\n [],\n )\n if (defs.length === 0) continue\n\n const counts: Record<string, number> = {}\n for (const def of defs) {\n const m = def.method.toUpperCase()\n counts[m] = (counts[m] || 0) + 1\n }\n totalRoutes += defs.length\n\n const methods = Object.entries(counts)\n .sort(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([m, n]) => `${n} ${m}`)\n .join(', ')\n const name = controller.name || 'Controller'\n log.debug(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`)\n }\n\n log.debug(` Total: ${totalRoutes} routes`)\n }\n\n // ── 9. Adapter middleware: afterRoutes ────────────────────────────\n this.mountMiddlewareList(adapterMw.afterRoutes)\n\n // ── 10. Error handlers ───────────────────────────────────────────\n this.app.use(this.options.onNotFound ?? notFoundHandler())\n this.app.use(this.options.onError ?? errorHandler())\n\n // ── 11. Adapter beforeStart hooks ────────────────────────────────\n for (const adapter of this.adapters) {\n await this.callHook(adapter.beforeStart?.bind(adapter), ctx)\n }\n }\n\n /** Register modules and DI without starting the HTTP server (used by kick tinker) */\n async registerOnly(): Promise<void> {\n await this.setup()\n }\n\n /**\n * Start the HTTP server.\n *\n * In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`\n * created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real\n * `http.Server` through `afterStart({ server })` — zero adapter changes needed.\n *\n * In **production**: creates its own `http.Server` and binds to the port.\n */\n async start(): Promise<void> {\n await this.setup()\n\n const g = globalThis as any\n\n if (g.__kickjs_httpServer) {\n // ── DEV MODE: Vite owns the http.Server ──────────────────────\n // Don't create a new server or listen — Vite is already listening.\n // Just wire up adapters with the Vite-created server.\n this.httpServer = g.__kickjs_httpServer\n log.debug('Attached to Vite dev server')\n\n for (const adapter of this.adapters) {\n const ctx = this.adapterCtx(this.httpServer!)\n await this.callHook(adapter.afterStart?.bind(adapter), ctx)\n }\n\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n\n return\n }\n\n // ── PRODUCTION: Create and own the http.Server ─────────────────\n const port = this.options.port ?? parseInt(process.env.PORT || '3000', 10)\n this.httpServer = http.createServer(this.app)\n\n this.httpServer.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n log.error(\n `Port ${port} is already in use. Kill the existing process or use a different port:\\n` +\n ` PORT=${port + 1} kick dev\\n` +\n ` lsof -i :${port} # find what's using it\\n` +\n ` kill <PID> # stop it`,\n )\n process.exit(1)\n }\n throw err\n })\n\n // Wrap listen in a Promise so afterStart/onReady errors propagate\n await new Promise<void>((resolve, reject) => {\n this.httpServer!.listen(port, async () => {\n try {\n log.info(`Server running on http://localhost:${port}`)\n\n for (const adapter of this.adapters) {\n const afterCtx = this.adapterCtx(this.httpServer!)\n await this.callHook(adapter.afterStart?.bind(adapter), afterCtx)\n }\n\n // Plugin onReady hooks\n for (const plugin of this.plugins) {\n await plugin.onReady?.(this.container)\n }\n\n resolve()\n } catch (err) {\n reject(err)\n }\n })\n })\n }\n\n /** HMR rebuild: swap Express handler without restarting the server */\n async rebuild(): Promise<void> {\n // Build the new app fully before swapping — if setup() throws,\n // the old app keeps running so the server stays responsive.\n const prevApp = this.app\n const prevContainer = this.container\n\n try {\n Container.reset()\n this.container = Container.getInstance()\n this.app = express()\n await this.setup()\n } catch (err) {\n log.error(err, 'HMR rebuild failed, keeping previous app')\n // Restore previous state so the server stays responsive\n this.app = prevApp\n this.container = prevContainer\n return\n }\n\n if (this.httpServer) {\n this.httpServer.removeAllListeners('request')\n this.httpServer.on('request', this.app)\n log.debug('HMR: Express app rebuilt and swapped')\n }\n }\n\n /**\n * Graceful shutdown with request draining.\n *\n * 1. Stops accepting new connections (server.close())\n * 2. Waits for in-flight requests to complete (up to shutdownTimeout)\n * 3. Calls adapter.shutdown() for all registered adapters\n * 4. Force-closes after timeout\n *\n * Safe to call multiple times — subsequent calls return the same promise.\n */\n async shutdown(): Promise<void> {\n // Prevent double-shutdown — return immediately if already initiated\n if (this._shutdownInitiated) {\n log.debug('Shutdown already in progress, skipping duplicate call')\n return\n }\n this._shutdownInitiated = true\n this._draining = true\n\n log.debug('Shutting down — draining in-flight requests...')\n\n const timeoutMs = this.options.shutdownTimeout ?? 30_000\n let timer: ReturnType<typeof setTimeout> | undefined\n\n // Start a force-exit timer if timeout is configured\n const forceExitPromise =\n timeoutMs > 0\n ? new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n timer.unref()\n })\n : new Promise<never>(() => {}) // never resolves — no forced exit\n\n try {\n // Step 1: Stop accepting new connections.\n // server.close() prevents new connections. Its callback fires only when\n // ALL existing connections are fully closed, so we do NOT await it here —\n // we track request draining separately via the tracking middleware.\n if (this.httpServer) {\n this.httpServer.close(() => {})\n }\n\n // Step 2: Wait for in-flight requests to drain (or timeout)\n if (this._inFlightRequests > 0) {\n log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`)\n const drainPromise = new Promise<'drained'>((resolve) => {\n this._drainResolvers.push(() => resolve('drained'))\n })\n\n const result = await Promise.race([drainPromise, forceExitPromise])\n if (result === 'timeout') {\n log.warn(\n `Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`,\n )\n } else {\n log.debug('All in-flight requests completed')\n }\n }\n\n // Step 3: Run all plugin + adapter shutdowns concurrently\n const results = await Promise.allSettled([\n ...this.plugins.map((plugin) => Promise.resolve(plugin.shutdown?.())),\n ...this.adapters.map((adapter) => Promise.resolve(adapter.shutdown?.())),\n ])\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error({ err: result.reason }, 'Adapter shutdown failed')\n }\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n getExpressApp(): Express {\n return this.app\n }\n\n /** Get registered adapters — used by DevToolsAdapter for peer discovery */\n getAdapters(): AppAdapter[] {\n return this.adapters\n }\n\n /**\n * Get registered plugins — used by DevToolsAdapter for topology\n * introspection (architecture.md §23). Read-only; returns the\n * already-sorted plugin list (post-`dependsOn` topo-sort).\n */\n getPlugins(): readonly KickPlugin[] {\n return this.plugins\n }\n\n getHttpServer(): http.Server | null {\n return this.httpServer\n }\n\n // ── Internal helpers ────────────────────────────────────────────────\n\n /**\n * Decide whether {@link Application} should auto-mount the\n * {@link requestScopeMiddleware} ALS wrapper.\n *\n * Returns `false` when:\n * - `contextStore: 'manual'` was set (caller manages ALS frames), or\n * - the user-supplied `middleware` list already includes a\n * `requestScopeMiddleware()` (detected via the symbol marker stamped\n * in `middleware/request-scope.ts`).\n *\n * Otherwise `true` — preserves the historical default of \"always wrap\n * requests in an ALS frame\" so existing apps see no behavior change.\n */\n private shouldAutoMountRequestScope(): boolean {\n if (this.options.contextStore === 'manual') return false\n\n const userEntries = this.options.middleware ?? []\n for (const entry of userEntries) {\n const handler = typeof entry === 'function' ? entry : entry.handler\n if (isRequestScopeMiddleware(handler)) return false\n }\n return true\n }\n\n private collectAdapterMiddleware() {\n const result = {\n beforeGlobal: [] as AdapterMiddleware[],\n afterGlobal: [] as AdapterMiddleware[],\n beforeRoutes: [] as AdapterMiddleware[],\n afterRoutes: [] as AdapterMiddleware[],\n }\n\n for (const adapter of this.adapters) {\n const entries = adapter.middleware?.() ?? []\n for (const entry of entries) {\n const phase = entry.phase ?? 'afterGlobal'\n result[phase].push(entry)\n }\n }\n\n return result\n }\n\n private mountMiddlewareList(entries: AdapterMiddleware[]): void {\n for (const entry of entries) {\n if (entry.path) {\n this.app.use(entry.path, entry.handler)\n } else {\n this.app.use(entry.handler)\n }\n }\n }\n\n private mountMiddlewareEntry(entry: MiddlewareEntry): void {\n if (typeof entry === 'function') {\n this.app.use(entry)\n } else {\n this.app.use(entry.path, entry.handler)\n }\n }\n\n /** Middleware that tracks in-flight requests for graceful draining */\n private requestTrackingMiddleware(): RequestHandler {\n return (_req, res, next) => {\n this._inFlightRequests++\n const onFinish = () => {\n res.removeListener('finish', onFinish)\n res.removeListener('close', onFinish)\n this._inFlightRequests--\n // If draining and no more in-flight requests, resolve all waiters\n if (this._draining && this._inFlightRequests === 0) {\n for (const resolve of this._drainResolvers) {\n resolve()\n }\n this._drainResolvers = []\n }\n }\n res.on('finish', onFinish)\n res.on('close', onFinish)\n next()\n }\n }\n\n /** Mount /health/live and /health/ready endpoints at the root (no API prefix) */\n private mountHealthEndpoints(): void {\n this.app.get('/health/live', (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', uptime: process.uptime() })\n } else {\n res.json({ status: 'ok', uptime: process.uptime() })\n }\n })\n\n this.app.get('/health/ready', async (_req, res) => {\n if (this._draining) {\n res.status(503).json({ status: 'draining', checks: [] })\n return\n }\n const adaptersWithHealth = this.adapters.filter((a) => a.onHealthCheck)\n const checks = await Promise.allSettled(adaptersWithHealth.map((a) => a.onHealthCheck!()))\n const results = checks.map((c, i) => {\n if (c.status === 'fulfilled') return c.value\n return { name: adaptersWithHealth[i].name ?? 'unknown', status: 'down' as const }\n })\n const healthy = results.every((r) => r.status === 'up')\n res.status(healthy ? 200 :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