@forinda/kickjs 2.0.0 → 2.1.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 (237) hide show
  1. package/README.md +85 -584
  2. package/dist/adapter-BqGjZCSm.d.mts +122 -0
  3. package/dist/adapter-BqGjZCSm.d.mts.map +1 -0
  4. package/dist/app-module-CcEbAVtB.d.mts +33 -0
  5. package/dist/app-module-CcEbAVtB.d.mts.map +1 -0
  6. package/dist/application-DNHj-_UL.mjs +449 -0
  7. package/dist/application-DNHj-_UL.mjs.map +1 -0
  8. package/dist/bootstrap-DLEZaJ3b.mjs +205 -0
  9. package/dist/bootstrap-DLEZaJ3b.mjs.map +1 -0
  10. package/dist/{core/cache.d.ts → cache-DJeMaGqb.d.mts} +33 -31
  11. package/dist/cache-DJeMaGqb.d.mts.map +1 -0
  12. package/dist/chunk-C5Qp-JxE.mjs +15 -0
  13. package/dist/container-nBSIhyqV.d.mts +141 -0
  14. package/dist/container-nBSIhyqV.d.mts.map +1 -0
  15. package/dist/core/adapter.d.mts +3 -0
  16. package/dist/core/adapter.mjs +11 -0
  17. package/dist/core/app-module.d.mts +3 -0
  18. package/dist/core/app-module.mjs +11 -0
  19. package/dist/core/cache.d.mts +3 -0
  20. package/dist/core/cache.mjs +113 -0
  21. package/dist/core/cache.mjs.map +1 -0
  22. package/dist/core/container.d.mts +3 -0
  23. package/dist/core/container.mjs +426 -0
  24. package/dist/core/container.mjs.map +1 -0
  25. package/dist/core/cron.d.mts +3 -0
  26. package/dist/core/cron.mjs +42 -0
  27. package/dist/core/cron.mjs.map +1 -0
  28. package/dist/core/decorators.d.mts +3 -0
  29. package/dist/core/decorators.mjs +213 -0
  30. package/dist/core/decorators.mjs.map +1 -0
  31. package/dist/core/errors.d.mts +3 -0
  32. package/dist/core/errors.mjs +97 -0
  33. package/dist/core/errors.mjs.map +1 -0
  34. package/dist/core/interfaces.d.mts +3 -0
  35. package/dist/core/interfaces.mjs +44 -0
  36. package/dist/core/interfaces.mjs.map +1 -0
  37. package/dist/core/logger.d.mts +3 -0
  38. package/dist/core/logger.mjs +217 -0
  39. package/dist/core/logger.mjs.map +1 -0
  40. package/dist/core/path.d.mts +3 -0
  41. package/dist/core/path.mjs +45 -0
  42. package/dist/core/path.mjs.map +1 -0
  43. package/dist/core/plugin.d.mts +3 -0
  44. package/dist/core/plugin.mjs +11 -0
  45. package/dist/core/reactivity.d.mts +3 -0
  46. package/dist/core/reactivity.mjs +189 -0
  47. package/dist/core/reactivity.mjs.map +1 -0
  48. package/dist/core-BL_H8fEZ.mjs +121 -0
  49. package/dist/core-BL_H8fEZ.mjs.map +1 -0
  50. package/dist/{core/cron.d.ts → cron-RKhH5TOd.d.mts} +16 -14
  51. package/dist/cron-RKhH5TOd.d.mts.map +1 -0
  52. package/dist/decorators-CQ93ak6Z.d.mts +154 -0
  53. package/dist/decorators-CQ93ak6Z.d.mts.map +1 -0
  54. package/dist/errors-te5Km00o.d.mts +68 -0
  55. package/dist/errors-te5Km00o.d.mts.map +1 -0
  56. package/dist/http/application.d.mts +220 -0
  57. package/dist/http/application.d.mts.map +1 -0
  58. package/dist/http/application.mjs +12 -0
  59. package/dist/http/bootstrap.d.mts +43 -0
  60. package/dist/http/bootstrap.d.mts.map +1 -0
  61. package/dist/http/bootstrap.mjs +12 -0
  62. package/dist/http/context.d.mts +131 -0
  63. package/dist/http/context.d.mts.map +1 -0
  64. package/dist/http/context.mjs +220 -0
  65. package/dist/http/context.mjs.map +1 -0
  66. package/dist/http/middleware/cors.d.mts +48 -0
  67. package/dist/http/middleware/cors.d.mts.map +1 -0
  68. package/dist/http/middleware/cors.mjs +83 -0
  69. package/dist/http/middleware/cors.mjs.map +1 -0
  70. package/dist/http/middleware/csrf.d.mts +52 -0
  71. package/dist/http/middleware/csrf.d.mts.map +1 -0
  72. package/dist/http/middleware/csrf.mjs +72 -0
  73. package/dist/http/middleware/csrf.mjs.map +1 -0
  74. package/dist/http/middleware/error-handler.d.mts +11 -0
  75. package/dist/http/middleware/error-handler.d.mts.map +1 -0
  76. package/dist/http/middleware/error-handler.mjs +52 -0
  77. package/dist/http/middleware/error-handler.mjs.map +1 -0
  78. package/dist/http/middleware/helmet.d.mts +41 -0
  79. package/dist/http/middleware/helmet.d.mts.map +1 -0
  80. package/dist/http/middleware/helmet.mjs +51 -0
  81. package/dist/http/middleware/helmet.mjs.map +1 -0
  82. package/dist/http/middleware/rate-limit.d.mts +56 -0
  83. package/dist/http/middleware/rate-limit.d.mts.map +1 -0
  84. package/dist/http/middleware/rate-limit.mjs +101 -0
  85. package/dist/http/middleware/rate-limit.mjs.map +1 -0
  86. package/dist/http/middleware/request-id.d.mts +10 -0
  87. package/dist/http/middleware/request-id.d.mts.map +1 -0
  88. package/dist/http/middleware/request-id.mjs +26 -0
  89. package/dist/http/middleware/request-id.mjs.map +1 -0
  90. package/dist/http/middleware/request-logger.d.mts +32 -0
  91. package/dist/http/middleware/request-logger.d.mts.map +1 -0
  92. package/dist/http/middleware/request-logger.mjs +49 -0
  93. package/dist/http/middleware/request-logger.mjs.map +1 -0
  94. package/dist/http/middleware/session.d.mts +67 -0
  95. package/dist/http/middleware/session.d.mts.map +1 -0
  96. package/dist/http/middleware/session.mjs +152 -0
  97. package/dist/http/middleware/session.mjs.map +1 -0
  98. package/dist/http/middleware/spa.d.mts +101 -0
  99. package/dist/http/middleware/spa.d.mts.map +1 -0
  100. package/dist/http/middleware/spa.mjs +108 -0
  101. package/dist/http/middleware/spa.mjs.map +1 -0
  102. package/dist/http/middleware/{upload.d.ts → upload.d.mts} +21 -17
  103. package/dist/http/middleware/upload.d.mts.map +1 -0
  104. package/dist/http/middleware/upload.mjs +191 -0
  105. package/dist/http/middleware/upload.mjs.map +1 -0
  106. package/dist/http/middleware/validate.d.mts +18 -0
  107. package/dist/http/middleware/validate.d.mts.map +1 -0
  108. package/dist/http/middleware/validate.mjs +62 -0
  109. package/dist/http/middleware/validate.mjs.map +1 -0
  110. package/dist/http/middleware/views.d.mts +62 -0
  111. package/dist/http/middleware/views.d.mts.map +1 -0
  112. package/dist/http/middleware/views.mjs +65 -0
  113. package/dist/http/middleware/views.mjs.map +1 -0
  114. package/dist/http/query/index.d.mts +3 -0
  115. package/dist/http/query/index.mjs +12 -0
  116. package/dist/http/{router-builder.d.ts → router-builder.d.mts} +9 -5
  117. package/dist/http/router-builder.d.mts.map +1 -0
  118. package/dist/http/router-builder.mjs +67 -0
  119. package/dist/http/router-builder.mjs.map +1 -0
  120. package/dist/index-C0gbnpSg.d.mts +107 -0
  121. package/dist/index-C0gbnpSg.d.mts.map +1 -0
  122. package/dist/index-Cls52etj.d.mts +148 -0
  123. package/dist/index-Cls52etj.d.mts.map +1 -0
  124. package/dist/index.d.mts +133 -0
  125. package/dist/index.d.mts.map +1 -0
  126. package/dist/index.mjs +126 -0
  127. package/dist/index.mjs.map +1 -0
  128. package/dist/interfaces-D-48zotH.d.mts +52 -0
  129. package/dist/interfaces-D-48zotH.d.mts.map +1 -0
  130. package/dist/logger-Dzj-TF0t.d.mts +119 -0
  131. package/dist/logger-Dzj-TF0t.d.mts.map +1 -0
  132. package/dist/metadata-fmvikBA0.mjs +76 -0
  133. package/dist/metadata-fmvikBA0.mjs.map +1 -0
  134. package/dist/{core/path.d.ts → path-LmwfhfyH.d.mts} +7 -3
  135. package/dist/path-LmwfhfyH.d.mts.map +1 -0
  136. package/dist/plugin-DIoPIpSm.d.mts +95 -0
  137. package/dist/plugin-DIoPIpSm.d.mts.map +1 -0
  138. package/dist/query-7cdHF6ry.mjs +164 -0
  139. package/dist/query-7cdHF6ry.mjs.map +1 -0
  140. package/dist/{core/reactivity.d.ts → reactivity-BbS-99ow.d.mts} +21 -20
  141. package/dist/reactivity-BbS-99ow.d.mts.map +1 -0
  142. package/package.json +73 -43
  143. package/dist/chunk-DVVP7zzD.js +0 -7
  144. package/dist/core/adapter.d.ts +0 -109
  145. package/dist/core/adapter.d.ts.map +0 -1
  146. package/dist/core/adapter.js +0 -0
  147. package/dist/core/app-module.d.ts +0 -28
  148. package/dist/core/app-module.d.ts.map +0 -1
  149. package/dist/core/app-module.js +0 -0
  150. package/dist/core/cache.d.ts.map +0 -1
  151. package/dist/core/cache.js +0 -57
  152. package/dist/core/container.d.ts +0 -63
  153. package/dist/core/container.d.ts.map +0 -1
  154. package/dist/core/container.js +0 -117
  155. package/dist/core/cron.d.ts.map +0 -1
  156. package/dist/core/cron.js +0 -22
  157. package/dist/core/decorators.d.ts +0 -153
  158. package/dist/core/decorators.d.ts.map +0 -1
  159. package/dist/core/decorators.js +0 -141
  160. package/dist/core/errors.d.ts +0 -64
  161. package/dist/core/errors.d.ts.map +0 -1
  162. package/dist/core/errors.js +0 -67
  163. package/dist/core/index.d.ts +0 -14
  164. package/dist/core/index.d.ts.map +0 -1
  165. package/dist/core/interfaces.d.ts +0 -44
  166. package/dist/core/interfaces.d.ts.map +0 -1
  167. package/dist/core/interfaces.js +0 -25
  168. package/dist/core/logger.d.ts +0 -43
  169. package/dist/core/logger.d.ts.map +0 -1
  170. package/dist/core/logger.js +0 -54
  171. package/dist/core/path.d.ts.map +0 -1
  172. package/dist/core/path.js +0 -12
  173. package/dist/core/plugin.d.ts +0 -90
  174. package/dist/core/plugin.d.ts.map +0 -1
  175. package/dist/core/plugin.js +0 -0
  176. package/dist/core/reactivity.d.ts.map +0 -1
  177. package/dist/core/reactivity.js +0 -101
  178. package/dist/core-B6Okew3W.js +0 -7
  179. package/dist/http/application.d.ts +0 -103
  180. package/dist/http/application.d.ts.map +0 -1
  181. package/dist/http/application.js +0 -167
  182. package/dist/http/bootstrap.d.ts +0 -22
  183. package/dist/http/bootstrap.d.ts.map +0 -1
  184. package/dist/http/bootstrap.js +0 -40
  185. package/dist/http/context.d.ts +0 -129
  186. package/dist/http/context.d.ts.map +0 -1
  187. package/dist/http/context.js +0 -115
  188. package/dist/http/index.d.ts +0 -16
  189. package/dist/http/index.d.ts.map +0 -1
  190. package/dist/http/middleware/cors.d.ts +0 -43
  191. package/dist/http/middleware/cors.d.ts.map +0 -1
  192. package/dist/http/middleware/cors.js +0 -31
  193. package/dist/http/middleware/csrf.d.ts +0 -47
  194. package/dist/http/middleware/csrf.d.ts.map +0 -1
  195. package/dist/http/middleware/csrf.js +0 -25
  196. package/dist/http/middleware/error-handler.d.ts +0 -6
  197. package/dist/http/middleware/error-handler.d.ts.map +0 -1
  198. package/dist/http/middleware/error-handler.js +0 -37
  199. package/dist/http/middleware/helmet.d.ts +0 -36
  200. package/dist/http/middleware/helmet.d.ts.map +0 -1
  201. package/dist/http/middleware/helmet.js +0 -20
  202. package/dist/http/middleware/rate-limit.d.ts +0 -51
  203. package/dist/http/middleware/rate-limit.d.ts.map +0 -1
  204. package/dist/http/middleware/rate-limit.js +0 -46
  205. package/dist/http/middleware/request-id.d.ts +0 -5
  206. package/dist/http/middleware/request-id.d.ts.map +0 -1
  207. package/dist/http/middleware/request-id.js +0 -12
  208. package/dist/http/middleware/request-logger.d.ts +0 -27
  209. package/dist/http/middleware/request-logger.d.ts.map +0 -1
  210. package/dist/http/middleware/request-logger.js +0 -16
  211. package/dist/http/middleware/session.d.ts +0 -62
  212. package/dist/http/middleware/session.d.ts.map +0 -1
  213. package/dist/http/middleware/session.js +0 -76
  214. package/dist/http/middleware/spa.d.ts +0 -93
  215. package/dist/http/middleware/spa.d.ts.map +0 -1
  216. package/dist/http/middleware/spa.js +0 -52
  217. package/dist/http/middleware/upload.d.ts.map +0 -1
  218. package/dist/http/middleware/upload.js +0 -119
  219. package/dist/http/middleware/validate.d.ts +0 -13
  220. package/dist/http/middleware/validate.d.ts.map +0 -1
  221. package/dist/http/middleware/validate.js +0 -45
  222. package/dist/http/middleware/views.d.ts +0 -56
  223. package/dist/http/middleware/views.d.ts.map +0 -1
  224. package/dist/http/middleware/views.js +0 -18
  225. package/dist/http/query/index.d.ts +0 -4
  226. package/dist/http/query/index.d.ts.map +0 -1
  227. package/dist/http/query/index.js +0 -10
  228. package/dist/http/query/parse-query.d.ts +0 -44
  229. package/dist/http/query/parse-query.d.ts.map +0 -1
  230. package/dist/http/query/types.d.ts +0 -100
  231. package/dist/http/query/types.d.ts.map +0 -1
  232. package/dist/http/router-builder.d.ts.map +0 -1
  233. package/dist/http/router-builder.js +0 -37
  234. package/dist/index.d.ts +0 -25
  235. package/dist/index.d.ts.map +0 -1
  236. package/dist/index.js +0 -103
  237. package/dist/query-Bym31XRp.js +0 -88
@@ -0,0 +1,122 @@
1
+
2
+ import { i as Constructor, o as MaybePromise } from "./interfaces-D-48zotH.mjs";
3
+ import { t as Container } from "./container-nBSIhyqV.mjs";
4
+ import http from "node:http";
5
+ import { Express } from "express";
6
+
7
+ //#region src/core/adapter.d.ts
8
+ /**
9
+ * Where in the middleware pipeline an adapter's middleware should be inserted.
10
+ *
11
+ * beforeGlobal → runs before any user-defined global middleware
12
+ * afterGlobal → runs after global middleware, before module routes
13
+ * beforeRoutes → just before module routes are mounted
14
+ * afterRoutes → after module routes but before error handlers
15
+ */
16
+ type MiddlewarePhase = 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes';
17
+ /** A middleware entry contributed by an adapter */
18
+ interface AdapterMiddleware {
19
+ /** Express-compatible handler: (req, res, next) => void */
20
+ handler: any;
21
+ /** Which phase to insert into (default: 'afterGlobal') */
22
+ phase?: MiddlewarePhase;
23
+ /** Optional path to scope the middleware to (e.g. '/api/v1/auth') */
24
+ path?: string;
25
+ }
26
+ /**
27
+ * Context passed to adapter lifecycle hooks.
28
+ * Populated by the Application — provides access to the Express app,
29
+ * DI container, http.Server, and environment info without requiring
30
+ * external type imports. Cast `app` or `server` if you need specific types.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * beforeMount({ app, container }: AdapterContext) {
35
+ * app.use(myMiddleware())
36
+ * }
37
+ * ```
38
+ */
39
+ interface AdapterContext {
40
+ /** Express application instance — fully typed */
41
+ app: Express;
42
+ /** DI container */
43
+ container: Container;
44
+ /** Node.js http.Server — only available in afterStart */
45
+ server?: http.Server;
46
+ /** Current NODE_ENV value (default: 'development') */
47
+ env: string;
48
+ /** true when NODE_ENV === 'production' */
49
+ isProduction: boolean;
50
+ }
51
+ /**
52
+ * Adapters plug into the Application lifecycle.
53
+ * Implement this to add WebSocket, database, rate limiting, docs, etc.
54
+ *
55
+ * All hooks receive an `AdapterContext` populated by the framework.
56
+ * No external type imports needed — the context is fully typed from KickJS internals.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * import type { AppAdapter, AdapterContext } from '@forinda/kickjs-core/adapter'
61
+ *
62
+ * class SentryAdapter implements AppAdapter {
63
+ * name = 'SentryAdapter'
64
+ *
65
+ * beforeMount({ app, container }: AdapterContext) {
66
+ * app.use(Sentry.expressRequestHandler())
67
+ * }
68
+ *
69
+ * afterStart({ server }: AdapterContext) {
70
+ * // server is the http.Server — available after listen()
71
+ * }
72
+ *
73
+ * async shutdown() {
74
+ * await Sentry.close(2000)
75
+ * }
76
+ * }
77
+ * ```
78
+ */
79
+ interface AppAdapter {
80
+ /** Human-readable name for logging */
81
+ name?: string;
82
+ /**
83
+ * Return middleware entries to be inserted into the pipeline.
84
+ * The `phase` controls ordering relative to global middleware and routes.
85
+ */
86
+ middleware?(): AdapterMiddleware[];
87
+ /**
88
+ * Called before global middleware — register early routes (docs UI, health).
89
+ * May return a Promise — async rejections are caught and logged.
90
+ */
91
+ beforeMount?(ctx: AdapterContext): void | Promise<void>;
92
+ /**
93
+ * Called for each module route that gets mounted.
94
+ * Use this to collect route metadata (e.g. for OpenAPI spec generation).
95
+ */
96
+ onRouteMount?(controllerClass: Constructor, mountPath: string): void;
97
+ /**
98
+ * Called after modules registered, before HTTP server starts.
99
+ * May return a Promise — async rejections are caught and logged.
100
+ */
101
+ beforeStart?(ctx: AdapterContext): void | Promise<void>;
102
+ /**
103
+ * Called after the HTTP server is listening — attach to the raw http.Server.
104
+ * May return a Promise — async rejections are caught and logged.
105
+ */
106
+ afterStart?(ctx: AdapterContext): void | Promise<void>;
107
+ /**
108
+ * Called by the /health/ready endpoint. Return the health status of your adapter's
109
+ * backing service (database, Redis, queue, etc.).
110
+ */
111
+ onHealthCheck?(): Promise<{
112
+ name: string;
113
+ status: 'up' | 'down';
114
+ }>;
115
+ /** Called on shutdown — clean up connections */
116
+ shutdown?(): MaybePromise;
117
+ }
118
+ /** Constructor type for AppAdapter classes */
119
+ type AppAdapterClass = new () => AppAdapter;
120
+ //#endregion
121
+ export { MiddlewarePhase as a, AppAdapterClass as i, AdapterMiddleware as n, AppAdapter as r, AdapterContext as t };
122
+ //# sourceMappingURL=adapter-BqGjZCSm.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter-BqGjZCSm.d.mts","names":[],"sources":["../src/core/adapter.ts"],"mappings":";;;;;;;;;AAaA;;;;;AAGA;KAHY,eAAA;;UAGK,iBAAA;EAEf;EAAA,OAAA;EAEQ;EAAR,KAAA,GAAQ,eAAA;EAEJ;EAAJ,IAAA;AAAA;;;;;;;;;;;;;;UAgBe,cAAA;EAQf;EANA,GAAA,EAAK,OAAA;EAQO;EANZ,SAAA,EAAW,SAAA;EAqCI;EAnCf,MAAA,GAAS,IAAA,CAAK,MAAA;;EAEd,GAAA;EA+CkB;EA7ClB,YAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+Be,UAAA;EAsCa;EApC5B,IAAA;EAuCA;;;;EAjCA,UAAA,KAAe,iBAAA;EAqCU;;;;EA/BzB,WAAA,EAAa,GAAA,EAAK,cAAA,UAAwB,OAAA;;;;;EAM1C,YAAA,EAAc,eAAA,EAAiB,WAAA,EAAa,SAAA;;;;;EAM5C,WAAA,EAAa,GAAA,EAAK,cAAA,UAAwB,OAAA;;;;;EAM1C,UAAA,EAAY,GAAA,EAAK,cAAA,UAAwB,OAAA;;;;;EAMzC,aAAA,KAAkB,OAAA;IAAU,IAAA;IAAc,MAAA;EAAA;;EAG1C,QAAA,KAAa,YAAA;AAAA;;KAIH,eAAA,aAA4B,UAAA"}
@@ -0,0 +1,33 @@
1
+
2
+ import { t as Container } from "./container-nBSIhyqV.mjs";
3
+
4
+ //#region src/core/app-module.d.ts
5
+ /**
6
+ * Route set returned by a module's routes() method.
7
+ * Combined with versioning: /{apiPrefix}/v{version}{path}
8
+ */
9
+ interface ModuleRoutes {
10
+ /** URL prefix (e.g. '/users') */
11
+ path: string;
12
+ /** Express Router instance (from buildRoutes) */
13
+ router: any;
14
+ /** Optional API version override (defaults to Application.defaultVersion) */
15
+ version?: number;
16
+ /** Controller class for OpenAPI introspection */
17
+ controller?: any;
18
+ }
19
+ /**
20
+ * Interface that every feature module must implement.
21
+ * Modules register their DI bindings and declare their routes.
22
+ */
23
+ interface AppModule {
24
+ /** Bind interfaces to implementations in the container */
25
+ register(container: Container): void;
26
+ /** Return route definitions for this module, or null for non-HTTP modules */
27
+ routes(): ModuleRoutes | ModuleRoutes[] | null;
28
+ }
29
+ /** Constructor type for AppModule classes */
30
+ type AppModuleClass = new () => AppModule;
31
+ //#endregion
32
+ export { AppModuleClass as n, ModuleRoutes as r, AppModule as t };
33
+ //# sourceMappingURL=app-module-CcEbAVtB.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app-module-CcEbAVtB.d.mts","names":[],"sources":["../src/core/app-module.ts"],"mappings":";;;;;;AAMA;;UAAiB,YAAA;EAAY;EAE3B,IAAA;EAEA;EAAA,MAAA;EAIA;EAFA,OAAA;EAEU;EAAV,UAAA;AAAA;;;;;UAOe,SAAA;EAIsB;EAFrC,QAAA,CAAS,SAAA,EAAW,SAAA;EAAA;EAEpB,MAAA,IAAU,YAAA,GAAe,YAAA;AAAA;;KAIf,cAAA,aAA2B,SAAA"}
@@ -0,0 +1,449 @@
1
+ /**
2
+ * @forinda/kickjs v2.1.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import { METADATA } from "./core/interfaces.mjs";
12
+ import { Logger, createLogger } from "./core/logger.mjs";
13
+ import { t as getClassMeta } from "./metadata-fmvikBA0.mjs";
14
+ import { Container } from "./core/container.mjs";
15
+ import { normalizePath } from "./core/path.mjs";
16
+ import "./core-BL_H8fEZ.mjs";
17
+ import { requestId } from "./http/middleware/request-id.mjs";
18
+ import { errorHandler, notFoundHandler } from "./http/middleware/error-handler.mjs";
19
+ import http from "node:http";
20
+ import express from "express";
21
+ import crypto from "node:crypto";
22
+ import { AsyncLocalStorage } from "node:async_hooks";
23
+ //#region src/http/request-store.ts
24
+ /** AsyncLocalStorage instance shared across the framework */
25
+ const requestStore = new AsyncLocalStorage();
26
+ /**
27
+ * Get the current request store. Throws if called outside a request context.
28
+ * Used by the Container to resolve REQUEST-scoped dependencies.
29
+ */
30
+ function getRequestStore() {
31
+ const store = requestStore.getStore();
32
+ if (!store) throw new Error("No active request context. REQUEST-scoped services can only be resolved during an HTTP request.");
33
+ return store;
34
+ }
35
+ //#endregion
36
+ //#region src/http/middleware/request-scope.ts
37
+ /**
38
+ * Wraps each request in an AsyncLocalStorage context.
39
+ * Enables REQUEST-scoped DI and automatic requestId propagation to logs.
40
+ *
41
+ * Should be mounted early in the middleware pipeline (before route handlers).
42
+ */
43
+ function requestScopeMiddleware() {
44
+ return (req, _res, next) => {
45
+ const requestIdHeader = req.headers["x-request-id"];
46
+ const store = {
47
+ requestId: (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) || crypto.randomUUID(),
48
+ instances: /* @__PURE__ */ new Map(),
49
+ values: /* @__PURE__ */ new Map()
50
+ };
51
+ requestStore.run(store, () => next());
52
+ };
53
+ }
54
+ //#endregion
55
+ //#region src/http/application.ts
56
+ const log = createLogger("Application");
57
+ /**
58
+ * The main application class. Wires together Express, the DI container,
59
+ * feature modules, adapters, and the middleware pipeline.
60
+ */
61
+ var Application = class {
62
+ app;
63
+ container;
64
+ httpServer = null;
65
+ adapters;
66
+ plugins;
67
+ /** Number of HTTP requests currently being processed */
68
+ _inFlightRequests = 0;
69
+ /** Whether the application is draining (shutting down gracefully) */
70
+ _draining = false;
71
+ /** Whether shutdown has already been initiated (prevents double-shutdown) */
72
+ _shutdownInitiated = false;
73
+ /** Resolvers waiting for in-flight requests to reach zero */
74
+ _drainResolvers = [];
75
+ constructor(options) {
76
+ this.options = options;
77
+ this.app = express();
78
+ this.container = Container.getInstance();
79
+ this.plugins = options.plugins ?? [];
80
+ this.adapters = [...this.plugins.flatMap((p) => p.adapters?.() ?? []), ...options.adapters ?? []];
81
+ Container._requestStoreProvider = () => requestStore.getStore() ?? null;
82
+ Logger._contextProvider = () => {
83
+ const store = requestStore.getStore();
84
+ if (!store) return null;
85
+ const ctx = { requestId: store.requestId };
86
+ const traceId = store.values.get("traceId");
87
+ if (traceId) ctx.traceId = traceId;
88
+ const spanId = store.values.get("spanId");
89
+ if (spanId) ctx.spanId = spanId;
90
+ return ctx;
91
+ };
92
+ }
93
+ /** Whether the application is currently draining in-flight requests */
94
+ get isDraining() {
95
+ return this._draining;
96
+ }
97
+ /** Number of HTTP requests currently being processed */
98
+ get inFlightRequests() {
99
+ return this._inFlightRequests;
100
+ }
101
+ /** Get the DI container instance */
102
+ getContainer() {
103
+ return this.container;
104
+ }
105
+ /**
106
+ * Express request handler — delegates to the internal Express app.
107
+ *
108
+ * Used by the Vite dev-server plugin to route requests through KickJS:
109
+ * ```ts
110
+ * const mod = await ssrLoadModule('virtual:kickjs/app')
111
+ * mod.app.handle(req, res, next)
112
+ * ```
113
+ *
114
+ * Also works as a standard Node.js request handler for production:
115
+ * ```ts
116
+ * http.createServer(app.handle.bind(app))
117
+ * ```
118
+ */
119
+ handle(req, res, next) {
120
+ if (next) this.app(req, res, next);
121
+ else this.app(req, res);
122
+ }
123
+ /**
124
+ * Full setup pipeline:
125
+ * 1. Adapter beforeMount hooks (early routes — docs, health)
126
+ * 2. Adapter middleware (phase: beforeGlobal)
127
+ * 3. Global middleware (user-declared or defaults)
128
+ * 4. Adapter middleware (phase: afterGlobal)
129
+ * 5. Module registration + DI bootstrap
130
+ * 6. Adapter middleware (phase: beforeRoutes)
131
+ * 7. Module route mounting
132
+ * 8. Adapter middleware (phase: afterRoutes)
133
+ * 9. Error handlers (notFound + global)
134
+ * 10. Adapter beforeStart hooks
135
+ */
136
+ /** Build the adapter context object (shared across all hooks) */
137
+ adapterCtx(server) {
138
+ const env = process.env.NODE_ENV ?? "development";
139
+ return {
140
+ app: this.app,
141
+ container: this.container,
142
+ server,
143
+ env,
144
+ isProduction: env === "production"
145
+ };
146
+ }
147
+ /** Call an adapter hook, awaiting async hooks and catching errors */
148
+ async callHook(hook, ctx) {
149
+ if (!hook) return;
150
+ try {
151
+ const result = hook(ctx);
152
+ if (result && typeof result.then === "function") await result;
153
+ } catch (err) {
154
+ log.error(err, "Adapter hook failed");
155
+ }
156
+ }
157
+ async setup() {
158
+ log.info("Bootstrapping application...");
159
+ const adapterMw = this.collectAdapterMiddleware();
160
+ this.app.__kickApp = this;
161
+ const ctx = this.adapterCtx();
162
+ for (const adapter of this.adapters) await this.callHook(adapter.beforeMount?.bind(adapter), ctx);
163
+ this.app.disable("x-powered-by");
164
+ this.app.set("trust proxy", this.options.trustProxy ?? false);
165
+ this.app.use(this.requestTrackingMiddleware());
166
+ this.mountHealthEndpoints();
167
+ this.app.use(requestScopeMiddleware());
168
+ this.mountMiddlewareList(adapterMw.beforeGlobal);
169
+ for (const plugin of this.plugins) plugin.register?.(this.container);
170
+ for (const plugin of this.plugins) try {
171
+ const mw = plugin.middleware?.() ?? [];
172
+ for (const handler of mw) this.app.use(handler);
173
+ } catch (err) {
174
+ log.error(err, `Plugin middleware failed: ${plugin.name ?? "unknown"}`);
175
+ }
176
+ if (this.options.middleware) for (const entry of this.options.middleware) this.mountMiddlewareEntry(entry);
177
+ else {
178
+ this.app.use(requestId());
179
+ this.app.use(express.json({ limit: this.options.jsonLimit ?? "100kb" }));
180
+ }
181
+ this.mountMiddlewareList(adapterMw.afterGlobal);
182
+ const modules = [...this.plugins.flatMap((p) => p.modules?.() ?? []), ...this.options.modules].map((ModuleClass) => {
183
+ const mod = new ModuleClass();
184
+ mod.register(this.container);
185
+ return mod;
186
+ });
187
+ this.container.bootstrap();
188
+ this.mountMiddlewareList(adapterMw.beforeRoutes);
189
+ const apiPrefix = this.options.apiPrefix ?? "/api";
190
+ const defaultVersion = this.options.defaultVersion ?? 1;
191
+ const shouldLogRoutes = this.options.logRoutesTable ?? process.env.NODE_ENV !== "production";
192
+ const mountedRoutes = [];
193
+ for (const mod of modules) {
194
+ const result = mod.routes();
195
+ if (!result) continue;
196
+ const routeSets = Array.isArray(result) ? result : [result];
197
+ for (const route of routeSets) {
198
+ const mountPath = `${apiPrefix}/v${route.version ?? defaultVersion}${normalizePath(route.path)}`;
199
+ this.app.use(mountPath, route.router);
200
+ if (route.controller) {
201
+ for (const adapter of this.adapters) try {
202
+ adapter.onRouteMount?.(route.controller, mountPath);
203
+ } catch (err) {
204
+ log.error(err, `adapter.onRouteMount() failed for ${mountPath}`);
205
+ }
206
+ if (shouldLogRoutes) mountedRoutes.push({
207
+ controller: route.controller,
208
+ mountPath
209
+ });
210
+ }
211
+ }
212
+ }
213
+ if (shouldLogRoutes && mountedRoutes.length > 0) {
214
+ const methodOrder = [
215
+ "GET",
216
+ "POST",
217
+ "PUT",
218
+ "PATCH",
219
+ "DELETE",
220
+ "HEAD",
221
+ "OPTIONS"
222
+ ];
223
+ const methodRank = (m) => {
224
+ const i = methodOrder.indexOf(m);
225
+ return i === -1 ? 99 : i;
226
+ };
227
+ let totalRoutes = 0;
228
+ log.info("Routes:");
229
+ for (const { controller, mountPath } of mountedRoutes) {
230
+ const defs = getClassMeta(METADATA.ROUTES, controller, []);
231
+ if (defs.length === 0) continue;
232
+ const counts = {};
233
+ for (const def of defs) {
234
+ const m = def.method.toUpperCase();
235
+ counts[m] = (counts[m] || 0) + 1;
236
+ }
237
+ totalRoutes += defs.length;
238
+ const methods = Object.entries(counts).sort(([a], [b]) => methodRank(a) - methodRank(b)).map(([m, n]) => `${n} ${m}`).join(", ");
239
+ const name = controller.name || "Controller";
240
+ log.info(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`);
241
+ }
242
+ log.info(` Total: ${totalRoutes} routes`);
243
+ }
244
+ this.mountMiddlewareList(adapterMw.afterRoutes);
245
+ this.app.use(this.options.onNotFound ?? notFoundHandler());
246
+ this.app.use(this.options.onError ?? errorHandler());
247
+ for (const adapter of this.adapters) await this.callHook(adapter.beforeStart?.bind(adapter), ctx);
248
+ }
249
+ /** Register modules and DI without starting the HTTP server (used by kick tinker) */
250
+ async registerOnly() {
251
+ await this.setup();
252
+ }
253
+ /**
254
+ * Start the HTTP server.
255
+ *
256
+ * In **dev mode** (Vite plugin active): reuses `globalThis.__kickjs_httpServer`
257
+ * created by Vite. Adapters (WsAdapter, Socket.IO, etc.) receive the real
258
+ * `http.Server` through `afterStart({ server })` — zero adapter changes needed.
259
+ *
260
+ * In **production**: creates its own `http.Server` and binds to the port.
261
+ */
262
+ async start() {
263
+ await this.setup();
264
+ const g = globalThis;
265
+ if (g.__kickjs_httpServer) {
266
+ this.httpServer = g.__kickjs_httpServer;
267
+ log.info("Attached to Vite dev server (adapters use Vite httpServer)");
268
+ for (const adapter of this.adapters) {
269
+ const ctx = this.adapterCtx(this.httpServer);
270
+ await this.callHook(adapter.afterStart?.bind(adapter), ctx);
271
+ }
272
+ for (const plugin of this.plugins) await plugin.onReady?.(this.container);
273
+ return;
274
+ }
275
+ const port = this.options.port ?? parseInt(process.env.PORT || "3000", 10);
276
+ this.httpServer = http.createServer(this.app);
277
+ this.httpServer.on("error", (err) => {
278
+ if (err.code === "EADDRINUSE") {
279
+ log.error(`Port ${port} is already in use. Kill the existing process or use a different port:\n PORT=${port + 1} kick dev\n lsof -i :${port} # find what's using it\n kill <PID> # stop it`);
280
+ process.exit(1);
281
+ }
282
+ throw err;
283
+ });
284
+ await new Promise((resolve, reject) => {
285
+ this.httpServer.listen(port, async () => {
286
+ try {
287
+ log.info(`Server running on http://localhost:${port}`);
288
+ for (const adapter of this.adapters) {
289
+ const afterCtx = this.adapterCtx(this.httpServer);
290
+ await this.callHook(adapter.afterStart?.bind(adapter), afterCtx);
291
+ }
292
+ for (const plugin of this.plugins) await plugin.onReady?.(this.container);
293
+ resolve();
294
+ } catch (err) {
295
+ reject(err);
296
+ }
297
+ });
298
+ });
299
+ }
300
+ /** HMR rebuild: swap Express handler without restarting the server */
301
+ async rebuild() {
302
+ const prevApp = this.app;
303
+ const prevContainer = this.container;
304
+ try {
305
+ Container.reset();
306
+ this.container = Container.getInstance();
307
+ this.app = express();
308
+ await this.setup();
309
+ } catch (err) {
310
+ log.error(err, "HMR rebuild failed, keeping previous app");
311
+ this.app = prevApp;
312
+ this.container = prevContainer;
313
+ return;
314
+ }
315
+ if (this.httpServer) {
316
+ this.httpServer.removeAllListeners("request");
317
+ this.httpServer.on("request", this.app);
318
+ log.info("HMR: Express app rebuilt and swapped");
319
+ }
320
+ }
321
+ /**
322
+ * Graceful shutdown with request draining.
323
+ *
324
+ * 1. Stops accepting new connections (server.close())
325
+ * 2. Waits for in-flight requests to complete (up to shutdownTimeout)
326
+ * 3. Calls adapter.shutdown() for all registered adapters
327
+ * 4. Force-closes after timeout
328
+ *
329
+ * Safe to call multiple times — subsequent calls return the same promise.
330
+ */
331
+ async shutdown() {
332
+ if (this._shutdownInitiated) {
333
+ log.info("Shutdown already in progress, skipping duplicate call");
334
+ return;
335
+ }
336
+ this._shutdownInitiated = true;
337
+ this._draining = true;
338
+ log.info("Shutting down — draining in-flight requests...");
339
+ const timeoutMs = this.options.shutdownTimeout ?? 3e4;
340
+ let timer;
341
+ const forceExitPromise = timeoutMs > 0 ? new Promise((resolve) => {
342
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
343
+ timer.unref();
344
+ }) : new Promise(() => {});
345
+ try {
346
+ if (this.httpServer) this.httpServer.close(() => {});
347
+ if (this._inFlightRequests > 0) {
348
+ log.info(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`);
349
+ const drainPromise = new Promise((resolve) => {
350
+ this._drainResolvers.push(() => resolve("drained"));
351
+ });
352
+ if (await Promise.race([drainPromise, forceExitPromise]) === "timeout") log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`);
353
+ else log.info("All in-flight requests completed");
354
+ }
355
+ const results = await Promise.allSettled([...this.plugins.map((plugin) => Promise.resolve(plugin.shutdown?.())), ...this.adapters.map((adapter) => Promise.resolve(adapter.shutdown?.()))]);
356
+ for (const result of results) if (result.status === "rejected") log.error({ err: result.reason }, "Adapter shutdown failed");
357
+ } finally {
358
+ if (timer) clearTimeout(timer);
359
+ }
360
+ }
361
+ getExpressApp() {
362
+ return this.app;
363
+ }
364
+ /** Get registered adapters — used by DevToolsAdapter for peer discovery */
365
+ getAdapters() {
366
+ return this.adapters;
367
+ }
368
+ getHttpServer() {
369
+ return this.httpServer;
370
+ }
371
+ collectAdapterMiddleware() {
372
+ const result = {
373
+ beforeGlobal: [],
374
+ afterGlobal: [],
375
+ beforeRoutes: [],
376
+ afterRoutes: []
377
+ };
378
+ for (const adapter of this.adapters) {
379
+ const entries = adapter.middleware?.() ?? [];
380
+ for (const entry of entries) result[entry.phase ?? "afterGlobal"].push(entry);
381
+ }
382
+ return result;
383
+ }
384
+ mountMiddlewareList(entries) {
385
+ for (const entry of entries) if (entry.path) this.app.use(entry.path, entry.handler);
386
+ else this.app.use(entry.handler);
387
+ }
388
+ mountMiddlewareEntry(entry) {
389
+ if (typeof entry === "function") this.app.use(entry);
390
+ else this.app.use(entry.path, entry.handler);
391
+ }
392
+ /** Middleware that tracks in-flight requests for graceful draining */
393
+ requestTrackingMiddleware() {
394
+ return (_req, res, next) => {
395
+ this._inFlightRequests++;
396
+ const onFinish = () => {
397
+ res.removeListener("finish", onFinish);
398
+ res.removeListener("close", onFinish);
399
+ this._inFlightRequests--;
400
+ if (this._draining && this._inFlightRequests === 0) {
401
+ for (const resolve of this._drainResolvers) resolve();
402
+ this._drainResolvers = [];
403
+ }
404
+ };
405
+ res.on("finish", onFinish);
406
+ res.on("close", onFinish);
407
+ next();
408
+ };
409
+ }
410
+ /** Mount /health/live and /health/ready endpoints at the root (no API prefix) */
411
+ mountHealthEndpoints() {
412
+ this.app.get("/health/live", (_req, res) => {
413
+ if (this._draining) res.status(503).json({
414
+ status: "draining",
415
+ uptime: process.uptime()
416
+ });
417
+ else res.json({
418
+ status: "ok",
419
+ uptime: process.uptime()
420
+ });
421
+ });
422
+ this.app.get("/health/ready", async (_req, res) => {
423
+ if (this._draining) {
424
+ res.status(503).json({
425
+ status: "draining",
426
+ checks: []
427
+ });
428
+ return;
429
+ }
430
+ const adaptersWithHealth = this.adapters.filter((a) => a.onHealthCheck);
431
+ const results = (await Promise.allSettled(adaptersWithHealth.map((a) => a.onHealthCheck()))).map((c, i) => {
432
+ if (c.status === "fulfilled") return c.value;
433
+ return {
434
+ name: adaptersWithHealth[i].name ?? "unknown",
435
+ status: "down"
436
+ };
437
+ });
438
+ const healthy = results.every((r) => r.status === "up");
439
+ res.status(healthy ? 200 : 503).json({
440
+ status: healthy ? "ready" : "degraded",
441
+ checks: results
442
+ });
443
+ });
444
+ }
445
+ };
446
+ //#endregion
447
+ export { requestStore as i, requestScopeMiddleware as n, getRequestStore as r, Application as t };
448
+
449
+ //# sourceMappingURL=application-DNHj-_UL.mjs.map