@forinda/kickjs 8.6.0 → 8.7.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 (158) hide show
  1. package/dist/{adapter-2bnoYEPX.d.mts → adapter-DK8WDonT.d.mts} +101 -5
  2. package/dist/adapter-DK8WDonT.d.mts.map +1 -0
  3. package/dist/{application-_QOiAVx2.d.mts → application-B6Gp1nqK.d.mts} +94 -13
  4. package/dist/application-B6Gp1nqK.d.mts.map +1 -0
  5. package/dist/application-D2scwBz-.mjs +12 -0
  6. package/dist/application-D2scwBz-.mjs.map +1 -0
  7. package/dist/bootstrap-Dds2PVAn.mjs +12 -0
  8. package/dist/bootstrap-Dds2PVAn.mjs.map +1 -0
  9. package/dist/cache-C0qL0NSD.d.mts.map +1 -1
  10. package/dist/{client-ip-DF_smNX7.mjs → client-ip-BuY7_pDD.mjs} +2 -2
  11. package/dist/{client-ip-DF_smNX7.mjs.map → client-ip-BuY7_pDD.mjs.map} +1 -1
  12. package/dist/config/index.d.mts +1 -1
  13. package/dist/config/index.mjs +2 -2
  14. package/dist/{config-CIOXZmLS.mjs → config-DBebCpg_.mjs} +3 -3
  15. package/dist/{config-CIOXZmLS.mjs.map → config-DBebCpg_.mjs.map} +1 -1
  16. package/dist/container-Cqow_bOU.mjs +132 -0
  17. package/dist/container-Cqow_bOU.mjs.map +1 -0
  18. package/dist/context-CHuuc9r6.mjs +12 -0
  19. package/dist/context-CHuuc9r6.mjs.map +1 -0
  20. package/dist/{context-errors-Ch0DuUQo.mjs → context-errors-VduncZFQ.mjs} +2 -2
  21. package/dist/{context-errors-Ch0DuUQo.mjs.map → context-errors-VduncZFQ.mjs.map} +1 -1
  22. package/dist/{contributor-runner-DujKZy4N.mjs → contributor-runner-BoVekHyj.mjs} +3 -3
  23. package/dist/{contributor-runner-DujKZy4N.mjs.map → contributor-runner-BoVekHyj.mjs.map} +1 -1
  24. package/dist/core/adapter.d.mts +2 -2
  25. package/dist/core/adapter.mjs +1 -1
  26. package/dist/core/app-module.mjs +1 -1
  27. package/dist/core/cache.mjs +2 -2
  28. package/dist/core/cache.mjs.map +1 -1
  29. package/dist/core/container.mjs +2 -2
  30. package/dist/core/cron.d.mts +2 -2
  31. package/dist/core/cron.mjs +2 -2
  32. package/dist/core/cron.mjs.map +1 -1
  33. package/dist/core/decorators.d.mts +1 -1
  34. package/dist/core/decorators.mjs +2 -2
  35. package/dist/core/decorators.mjs.map +1 -1
  36. package/dist/core/errors.mjs +1 -1
  37. package/dist/core/interfaces.mjs +1 -1
  38. package/dist/core/logger.mjs +1 -1
  39. package/dist/core/path.mjs +1 -1
  40. package/dist/core/plugin.d.mts +1 -1
  41. package/dist/core/plugin.mjs +1 -1
  42. package/dist/core/reactivity.mjs +1 -1
  43. package/dist/{core-y8QbzHM5.mjs → core-Chc61ahe.mjs} +3 -3
  44. package/dist/{core-y8QbzHM5.mjs.map → core-Chc61ahe.mjs.map} +1 -1
  45. package/dist/cron-BTGytNg-.d.mts +122 -0
  46. package/dist/cron-BTGytNg-.d.mts.map +1 -0
  47. package/dist/{csrf-C4MwaMp4.d.mts → csrf-COFjRrUz.d.mts} +2 -2
  48. package/dist/{csrf-C4MwaMp4.d.mts.map → csrf-COFjRrUz.d.mts.map} +1 -1
  49. package/dist/{csrf-RP5hgc0c.mjs → csrf-D-8W1iv7.mjs} +3 -3
  50. package/dist/csrf-D-8W1iv7.mjs.map +1 -0
  51. package/dist/{decorate-D85rEnU-.mjs → decorate-D9n58F0b.mjs} +1 -1
  52. package/dist/{decorators-mg0qJ6Qc.d.mts → decorators-DOcWsXci.d.mts} +2 -2
  53. package/dist/{decorators-mg0qJ6Qc.d.mts.map → decorators-DOcWsXci.d.mts.map} +1 -1
  54. package/dist/{define-adapter-C1Db6xfO.mjs → define-adapter-BJunWqi0.mjs} +2 -2
  55. package/dist/{define-adapter-C1Db6xfO.mjs.map → define-adapter-BJunWqi0.mjs.map} +1 -1
  56. package/dist/{disposables-CEAxve3A.mjs → disposables-BFIEp5VA.mjs} +2 -2
  57. package/dist/{disposables-CEAxve3A.mjs.map → disposables-BFIEp5VA.mjs.map} +1 -1
  58. package/dist/{env-BelmDj19.mjs → env-8BLpzy-M.mjs} +3 -3
  59. package/dist/{env-BelmDj19.mjs.map → env-8BLpzy-M.mjs.map} +1 -1
  60. package/dist/{error-handler-C1uWVGVY.d.mts → error-handler-DxF2EogM.d.mts} +2 -2
  61. package/dist/{error-handler-C1uWVGVY.d.mts.map → error-handler-DxF2EogM.d.mts.map} +1 -1
  62. package/dist/{handler-DHlakr0v.mjs → handler-MSvgGVk0.mjs} +3 -3
  63. package/dist/handler-MSvgGVk0.mjs.map +1 -0
  64. package/dist/http/application.d.mts +2 -2
  65. package/dist/http/application.mjs +2 -2
  66. package/dist/http/bootstrap.d.mts +1 -1
  67. package/dist/http/bootstrap.mjs +2 -2
  68. package/dist/http/context.d.mts +1 -1
  69. package/dist/http/context.mjs +2 -2
  70. package/dist/http/middleware/cors.mjs +1 -1
  71. package/dist/http/middleware/csrf.d.mts +1 -1
  72. package/dist/http/middleware/csrf.mjs +2 -2
  73. package/dist/http/middleware/error-handler.d.mts +1 -1
  74. package/dist/http/middleware/error-handler.mjs +2 -2
  75. package/dist/http/middleware/helmet.mjs +1 -1
  76. package/dist/http/middleware/rate-limit.mjs +2 -2
  77. package/dist/http/middleware/request-id.mjs +1 -1
  78. package/dist/http/middleware/request-logger.mjs +2 -2
  79. package/dist/http/middleware/session.mjs +2 -2
  80. package/dist/http/middleware/spa.d.mts +1 -1
  81. package/dist/http/middleware/spa.mjs +2 -2
  82. package/dist/http/middleware/upload.d.mts +1 -1
  83. package/dist/http/middleware/upload.mjs +2 -2
  84. package/dist/http/middleware/validate.mjs +1 -1
  85. package/dist/http/middleware/views.d.mts +1 -1
  86. package/dist/http/middleware/views.mjs +2 -2
  87. package/dist/http/query/index.mjs +2 -2
  88. package/dist/http/router-builder.d.mts +1 -1
  89. package/dist/http/router-builder.mjs +2 -2
  90. package/dist/http/runtimes/fastify.d.mts +1 -1
  91. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  92. package/dist/http/runtimes/fastify.mjs +3 -3
  93. package/dist/http/runtimes/fastify.mjs.map +1 -1
  94. package/dist/http/runtimes/h3-web.d.mts +1 -1
  95. package/dist/http/runtimes/h3-web.d.mts.map +1 -1
  96. package/dist/http/runtimes/h3-web.mjs +2 -2
  97. package/dist/http/runtimes/h3-web.mjs.map +1 -1
  98. package/dist/http/runtimes/h3.d.mts +1 -6
  99. package/dist/http/runtimes/h3.d.mts.map +1 -1
  100. package/dist/http/runtimes/h3.mjs +2 -2
  101. package/dist/http/runtimes/h3.mjs.map +1 -1
  102. package/dist/{index-Btz1W0X5.d.mts → index-ClP0EE9p.d.mts} +2 -2
  103. package/dist/{index-Btz1W0X5.d.mts.map → index-ClP0EE9p.d.mts.map} +1 -1
  104. package/dist/index.d.mts +11 -11
  105. package/dist/index.mjs +2 -2
  106. package/dist/index.mjs.map +1 -1
  107. package/dist/{kv-stores-Dx5RvIaP.d.mts → kv-stores-B-1WZ2Fh.d.mts} +34 -4
  108. package/dist/kv-stores-B-1WZ2Fh.d.mts.map +1 -0
  109. package/dist/{kv-stores-DUFcps01.mjs → kv-stores-BDcvhJBw.mjs} +3 -3
  110. package/dist/{kv-stores-DUFcps01.mjs.map → kv-stores-BDcvhJBw.mjs.map} +1 -1
  111. package/dist/{metadata-B8_KXybT.mjs → metadata-BClL-Eb0.mjs} +2 -2
  112. package/dist/{metadata-B8_KXybT.mjs.map → metadata-BClL-Eb0.mjs.map} +1 -1
  113. package/dist/{module-registry-BFrJ1PQ4.mjs → module-registry-kVXS3peW.mjs} +2 -2
  114. package/dist/{module-registry-BFrJ1PQ4.mjs.map → module-registry-kVXS3peW.mjs.map} +1 -1
  115. package/dist/observers-C5Jid4FV.mjs +12 -0
  116. package/dist/observers-C5Jid4FV.mjs.map +1 -0
  117. package/dist/{query-CC7o6I5K.mjs → query-1Q69dPhY.mjs} +2 -2
  118. package/dist/{query-CC7o6I5K.mjs.map → query-1Q69dPhY.mjs.map} +1 -1
  119. package/dist/{respond-B-EDymxF.mjs → respond-DBRvpEI5.mjs} +2 -2
  120. package/dist/{respond-B-EDymxF.mjs.map → respond-DBRvpEI5.mjs.map} +1 -1
  121. package/dist/route-flag-B1lQht6v.d.mts.map +1 -1
  122. package/dist/{route-flag-B4sNP7zH.mjs → route-flag-BCBTtP_4.mjs} +3 -3
  123. package/dist/route-flag-BCBTtP_4.mjs.map +1 -0
  124. package/dist/{route-policy-CDlMbl1b.mjs → route-policy-FeJHstvF.mjs} +2 -2
  125. package/dist/route-policy-FeJHstvF.mjs.map +1 -0
  126. package/dist/{router-builder-cTsA2XtO.mjs → router-builder-Brup4e82.mjs} +3 -3
  127. package/dist/{router-builder-cTsA2XtO.mjs.map → router-builder-Brup4e82.mjs.map} +1 -1
  128. package/dist/{router-builder-C6gmK0nZ.d.mts → router-builder-CUs9Gq4X.d.mts} +3 -3
  129. package/dist/{router-builder-C6gmK0nZ.d.mts.map → router-builder-CUs9Gq4X.d.mts.map} +1 -1
  130. package/dist/{runtime-C-7Yhs7a.mjs → runtime-CV0SS-X5.mjs} +3 -3
  131. package/dist/runtime-CV0SS-X5.mjs.map +1 -0
  132. package/dist/{upload-TW2ZuECF.d.mts → upload-BukLMawc.d.mts} +3 -3
  133. package/dist/{upload-TW2ZuECF.d.mts.map → upload-BukLMawc.d.mts.map} +1 -1
  134. package/dist/{upload-config-CoE6BzM4.mjs → upload-config-BBp5QfWQ.mjs} +2 -2
  135. package/dist/{upload-config-CoE6BzM4.mjs.map → upload-config-BBp5QfWQ.mjs.map} +1 -1
  136. package/dist/web.d.mts +22 -7
  137. package/dist/web.d.mts.map +1 -1
  138. package/dist/web.mjs +2 -2
  139. package/dist/web.mjs.map +1 -1
  140. package/package.json +14 -9
  141. package/dist/adapter-2bnoYEPX.d.mts.map +0 -1
  142. package/dist/application-DZiG1QCw.mjs +0 -12
  143. package/dist/application-DZiG1QCw.mjs.map +0 -1
  144. package/dist/application-_QOiAVx2.d.mts.map +0 -1
  145. package/dist/bootstrap-BEbka3UV.mjs +0 -12
  146. package/dist/bootstrap-BEbka3UV.mjs.map +0 -1
  147. package/dist/container-DF8FRoY8.mjs +0 -117
  148. package/dist/container-DF8FRoY8.mjs.map +0 -1
  149. package/dist/context-BTqeZH1A.mjs +0 -12
  150. package/dist/context-BTqeZH1A.mjs.map +0 -1
  151. package/dist/cron-DOOtTY4q.d.mts +0 -30
  152. package/dist/cron-DOOtTY4q.d.mts.map +0 -1
  153. package/dist/csrf-RP5hgc0c.mjs.map +0 -1
  154. package/dist/handler-DHlakr0v.mjs.map +0 -1
  155. package/dist/kv-stores-Dx5RvIaP.d.mts.map +0 -1
  156. package/dist/route-flag-B4sNP7zH.mjs.map +0 -1
  157. package/dist/route-policy-CDlMbl1b.mjs.map +0 -1
  158. package/dist/runtime-C-7Yhs7a.mjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
 
2
2
  import { i as Constructor, o as MaybePromise } from "./interfaces-C1hCSoLD.mjs";
3
3
  import { s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
4
- import { g as FileUploadConfig, k as RouteDefinition, x as MiddlewareHandler } from "./decorators-mg0qJ6Qc.mjs";
4
+ import { g as FileUploadConfig, k as RouteDefinition, x as MiddlewareHandler } from "./decorators-DOcWsXci.mjs";
5
5
  import { p as RouteFlags } from "./route-flag-B1lQht6v.mjs";
6
6
  import { C as MetaValue, S as ExecutionContext, m as ContributorRegistrations, o as AnyContributorRegistration, r as AppModuleEntry, t as AppModule, x as ContextMetaKey } from "./app-module-DCA65GZZ.mjs";
7
7
  import "./cache-C0qL0NSD.mjs";
@@ -9,7 +9,44 @@ import { i as ProblemDetails } from "./errors-By6UueCm.mjs";
9
9
  import { S as QueryFieldConfig, T as TypedParsedQuery, t as ParseQueryOptions, v as PaginatedResponse } from "./index-BfT5KZ-M.mjs";
10
10
  import "reflect-metadata";
11
11
  import http, { IncomingMessage, ServerResponse } from "node:http";
12
+ import https from "node:https";
13
+ import http2 from "node:http2";
12
14
  import { ErrorRequestHandler, Express as Express$1, NextFunction, Request as Request$1, RequestHandler, Response as Response$1 } from "express";
15
+ //#region src/core/observers.d.ts
16
+ /** Where an error came from. Integrations may report their own sources. */
17
+ type ErrorSource = 'request' | 'uncaught' | 'unhandled-rejection' | 'background' | 'job' | (string & {});
18
+ interface ErrorInfo {
19
+ source: ErrorSource;
20
+ requestId?: string;
21
+ method?: string;
22
+ /** The request URL path, as received. */
23
+ path?: string;
24
+ /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */
25
+ route?: string;
26
+ /** The status the error was answered with, for request errors. */
27
+ status?: number;
28
+ /** Anything else the reporter knows — a queue and job name, a cron schedule. */
29
+ context?: Record<string, unknown>;
30
+ }
31
+ interface ResponseInfo {
32
+ method: string;
33
+ path: string;
34
+ /** The matched route pattern, or undefined when no route matched (404s). */
35
+ route?: string;
36
+ status: number;
37
+ durationMs: number;
38
+ requestId?: string;
39
+ }
40
+ /**
41
+ * Report an error to every observer. The framework calls this for request
42
+ * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and
43
+ * queue job failures; call it from your own integrations too (a cron runner,
44
+ * a message consumer). Never throws.
45
+ */
46
+ declare function reportError(error: unknown, info: ErrorInfo): void;
47
+ /** Report a finished response to every observer. Never throws. */
48
+ declare function reportResponse(info: ResponseInfo): void;
49
+ //#endregion
13
50
  //#region src/core/introspect.d.ts
14
51
  /**
15
52
  * Per-primitive introspection snapshot — the JSON shape an adapter or
@@ -436,6 +473,19 @@ interface KickPlugin {
436
473
  * Use for post-startup logic like logging, health registration, etc.
437
474
  */
438
475
  onReady?(container: Container): void | Promise<void>;
476
+ /**
477
+ * Observe every error the app reports — request errors (any status; filter
478
+ * on `info.status`), uncaught exceptions, unhandled rejections, failed
479
+ * `waitUntil` work, failed queue jobs, and anything passed to
480
+ * `reportError()`. Observe-only: the response is not yours to change, and a
481
+ * throw here is logged and skipped. The place to wire Sentry & co.
482
+ */
483
+ onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
484
+ /**
485
+ * Observe every finished response — method, path, the matched route
486
+ * pattern, status, duration. Only timed while something listens.
487
+ */
488
+ onResponse?(info: ResponseInfo): void | Promise<void>;
439
489
  /**
440
490
  * Called during application shutdown — release what this plugin owns
441
491
  * (connections, intervals, subscriptions).
@@ -1527,6 +1577,14 @@ TKeys extends ContextMetaKey = ContextMetaKey> implements ExecutionContext<TKeys
1527
1577
  * ```
1528
1578
  */
1529
1579
  sendResponse(response: Response): Promise<void>;
1580
+ /**
1581
+ * Keep `promise` running after the response is sent — an audit log, an
1582
+ * email, an analytics call. The Node server's `shutdown()` waits for it;
1583
+ * `createHandler()` and the web entry hand it to the platform's
1584
+ * `waitUntil` when you pass the platform context in. A rejection is
1585
+ * logged, never unhandled. Same as the standalone `waitUntil()` export.
1586
+ */
1587
+ waitUntil(promise: Promise<unknown>): void;
1530
1588
  sse<T = unknown>(): SseHandler<T>;
1531
1589
  }
1532
1590
  /**
@@ -1672,11 +1730,22 @@ interface RouteMeta {
1672
1730
  * question. See `core/route-flag.ts`.
1673
1731
  */
1674
1732
  flags?: RouteFlags;
1733
+ /**
1734
+ * The full mounted pattern (`/api/v1/users/:id`) — set by the Application
1735
+ * for controller routes. `path` is relative to the module mount.
1736
+ */
1737
+ pattern?: string;
1675
1738
  }
1676
1739
  interface MatchedRoute {
1677
1740
  method: RouteMethod;
1678
1741
  /** Path as declared on the handler, e.g. `/:id`. */
1679
1742
  path: string;
1743
+ /**
1744
+ * The full route pattern including the mount prefix and version, e.g.
1745
+ * `/api/v1/users/:id` — what metrics and spans should be keyed by. Falls
1746
+ * back to `path` for routes registered without a mount.
1747
+ */
1748
+ pattern: string;
1680
1749
  controller?: Constructor;
1681
1750
  handlerName?: string;
1682
1751
  /** Enabled flags only — see {@link RouteMeta.flags}. */
@@ -1781,6 +1850,13 @@ interface RuntimeCapabilities {
1781
1850
  * false — it relies on the `express.json()` connect middleware.
1782
1851
  */
1783
1852
  nativeBodyParsing: boolean;
1853
+ /**
1854
+ * The engine's `nodeHandler` works behind `node:http2` (the HTTP/2
1855
+ * compatibility API), so `server: { http2: true }` may use it. Fastify/h3:
1856
+ * true. Express: false — it does not run on that layer. Absent = false, so
1857
+ * custom runtimes opt in explicitly.
1858
+ */
1859
+ http2?: boolean;
1784
1860
  }
1785
1861
  /**
1786
1862
  * The engine driver. KickJS owns decorators → {@link RouteTable}, the
@@ -1904,6 +1980,8 @@ interface AdapterMiddleware {
1904
1980
  * }
1905
1981
  * ```
1906
1982
  */
1983
+ /** The Node server behind the app — see `ApplicationOptions.server`. */
1984
+ type KickServer = http.Server | https.Server | http2.Http2SecureServer;
1907
1985
  interface AdapterContext {
1908
1986
  /**
1909
1987
  * Engine-agnostic HTTP surface — the supported way to add routes, mounts,
@@ -1932,8 +2010,13 @@ interface AdapterContext {
1932
2010
  fetch(request: Request): Promise<Response>;
1933
2011
  /** DI container */
1934
2012
  container: Container;
1935
- /** Node.js http.Server — only available in afterStart */
1936
- server?: http.Server;
2013
+ /**
2014
+ * The Node server the app listens on — only available in afterStart. An
2015
+ * `http.Server` by default; an `https.Server` or `Http2SecureServer` when
2016
+ * `bootstrap({ server })` sets `tls` / `http2`. All three emit `upgrade`
2017
+ * for HTTP/1.1 clients, which is what WebSocket libraries attach to.
2018
+ */
2019
+ server?: KickServer;
1937
2020
  /** Current NODE_ENV value (default: 'development') */
1938
2021
  env: string;
1939
2022
  /** true when NODE_ENV === 'production' */
@@ -2058,6 +2141,19 @@ interface AppAdapter {
2058
2141
  name: string;
2059
2142
  status: 'up' | 'down';
2060
2143
  }>;
2144
+ /**
2145
+ * Observe every error the app reports — request errors (any status; filter
2146
+ * on `info.status`), uncaught exceptions, unhandled rejections, failed
2147
+ * `waitUntil` work, failed queue jobs, and anything passed to
2148
+ * `reportError()`. Observe-only: the response is not yours to change, and a
2149
+ * throw here is logged and skipped. The place to wire Sentry & co.
2150
+ */
2151
+ onError?(error: unknown, info: ErrorInfo): void | Promise<void>;
2152
+ /**
2153
+ * Observe every finished response — method, path, the matched route
2154
+ * pattern, status, duration. Only timed while something listens.
2155
+ */
2156
+ onResponse?(info: ResponseInfo): void | Promise<void>;
2061
2157
  /**
2062
2158
  * Called on shutdown — release what this adapter owns.
2063
2159
  *
@@ -2102,5 +2198,5 @@ interface AppAdapter {
2102
2198
  /** Constructor type for AppAdapter classes */
2103
2199
  type AppAdapterClass = new () => AppAdapter;
2104
2200
  //#endregion
2105
- export { ModuleList as $, AdapterFactory as A, getClassMeta as B, UseConnectOptions as C, RouteShape as D, RequestContext as E, BuildPipelineOptions as F, getMethodMetaOrUndefined as G, getMetaMap as H, ContributorPipeline as I, pushMethodMeta as J, hasClassMeta as K, ContributorSource as L, defineAdapter as M, RunContributorsOptions as N, SseHandler as O, runContributors as P, setMethodMeta as Q, SourcedRegistration as R, RuntimeTypeMap as S, DeepReadonly as T, getMetaRecord as U, getClassMetaOrUndefined as V, getMethodMeta as W, setInMetaMap as X, setClassMeta as Y, setInMetaRecord as Z, RouteMethod as _, IntrospectionKind as _t, MiddlewarePath as a, DefinePluginOptions as at, RuntimeCapabilities as b, AdapterHttp as c, definePlugin as ct, ExpressRuntimeTypes as d, MutableModuleRegistry as dt, defineModules as et, HttpRuntime as f, AugmentationMeta as ft, RouteMeta as g, IntrospectFn as gt, RouteEntry as h, defineAugmentation as ht, AppAdapterClass as i, BuildContext as it, DefineAdapterOptions as j, AdapterAsyncOptions as k, ConnectMiddleware as l, KickPlugin as lt, MatchedRoute as m, KickJsPluginRegistry as mt, AdapterMiddleware as n, ModuleFactory as nt, MiddlewarePhase as o, PluginAsyncOptions as ot, KickRuntimeRegister as p, KickJsPluginName as pt, pushClassMeta as q, AppAdapter as r, defineModule as rt, ActiveRuntime as s, PluginFactory as st, AdapterContext as t, DefineModuleOptions as tt, CtxHandler as u, ModuleRegistry as ut, RouteTable as v, IntrospectionSnapshot as vt, Ctx as w, RuntimeResponse as x, RuntimeAppOptions as y, buildPipeline as z };
2106
- //# sourceMappingURL=adapter-2bnoYEPX.d.mts.map
2201
+ export { setMethodMeta as $, AdapterAsyncOptions as A, buildPipeline as B, RuntimeTypeMap as C, reportError as Ct, RequestContext as D, DeepReadonly as E, runContributors as F, getMethodMeta as G, getClassMetaOrUndefined as H, BuildPipelineOptions as I, pushClassMeta as J, getMethodMetaOrUndefined as K, ContributorPipeline as L, DefineAdapterOptions as M, defineAdapter as N, RouteShape as O, RunContributorsOptions as P, setInMetaRecord as Q, ContributorSource as R, RuntimeResponse as S, ResponseInfo as St, Ctx as T, getMetaMap as U, getClassMeta as V, getMetaRecord as W, setClassMeta as X, pushMethodMeta as Y, setInMetaMap as Z, RouteMeta as _, IntrospectFn as _t, KickServer as a, BuildContext as at, RuntimeAppOptions as b, ErrorInfo as bt, ActiveRuntime as c, PluginFactory as ct, CtxHandler as d, ModuleRegistry as dt, ModuleList as et, ExpressRuntimeTypes as f, MutableModuleRegistry as ft, RouteEntry as g, defineAugmentation as gt, MatchedRoute as h, KickJsPluginRegistry as ht, AppAdapterClass as i, defineModule as it, AdapterFactory as j, SseHandler as k, AdapterHttp as l, definePlugin as lt, KickRuntimeRegister as m, KickJsPluginName as mt, AdapterMiddleware as n, DefineModuleOptions as nt, MiddlewarePath as o, DefinePluginOptions as ot, HttpRuntime as p, AugmentationMeta as pt, hasClassMeta as q, AppAdapter as r, ModuleFactory as rt, MiddlewarePhase as s, PluginAsyncOptions as st, AdapterContext as t, defineModules as tt, ConnectMiddleware as u, KickPlugin as ut, RouteMethod as v, IntrospectionKind as vt, UseConnectOptions as w, reportResponse as wt, RuntimeCapabilities as x, ErrorSource as xt, RouteTable as y, IntrospectionSnapshot as yt, SourcedRegistration as z };
2202
+ //# sourceMappingURL=adapter-DK8WDonT.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter-DK8WDonT.d.mts","names":[],"sources":["../src/core/observers.ts","../src/core/introspect.ts","../src/core/augmentation.ts","../src/core/module-registry.ts","../src/core/plugin.ts","../src/core/define-plugin.ts","../src/core/define-module.ts","../src/core/define-modules.ts","../src/core/metadata.ts","../src/core/contributor-pipeline.ts","../src/core/contributor-runner.ts","../src/core/define-adapter.ts","../src/http/context.ts","../src/http/runtime.ts","../src/core/adapter.ts"],"mappings":";;;;;;;;;;;;;;;;KAoBY;UAQK;EACf,QAAQ;EACR;EACA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;UAGK;EACf;EACA;;EAEA;EACA;EACA;EACA;;;;;;;;iBAiFc,YAAY,gBAAgB,MAAM;;iBAKlC,eAAe,MAAM;;;;;;;;;;;;;;;;;;;;;UCrHpB;;;;;;;;;;EAUf;;EAEA;;EAEA,MAAM;;EAEN;;;;;EAKA,QAAQ;;EAER;IAAW;IAA6B;;;;;;EAKxC,UAAU;;EAEV;;;;;;;;KASU;;;;;;KAOA,qBAAqB,wBAAwB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;UC3ChD;;;;;;;;;KAUL,yBAAyB,oDAE3B;;;;;;;;;;;UAYO;;;;;EAKf;;;;;;;EAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2Ec,mBAAmB,cAAc,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCnGvC;;;;;;;;;;;EAWf,MAAM,QAAQ;;;;;;;;;;;cAYH,iCAAiC;WACnC,SAAS;EAElB,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCEC;;EAEf;;;;;;;;;;;;;;;;;;;EAoBA,qBAAqB;;;;;EAMrB,UAAU,WAAW;;;;;;;;;;;;;;EAerB,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;EA2BZ,OAAO,UAAU;;;;;EAMjB,aAAa;;;;;;;;;EAUb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCA,iBAAiB;;;;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BAAsB;;;;;;;;;;;;;;;;EAiBxC,aAAa;;;;;;;;;;;;;EAcb,eAAe,wBAAwB,QAAQ;;;;;;;;;;;EAY/C;;;KAIU,4BAA4B"}
@@ -1,21 +1,22 @@
1
1
 
2
2
  import { s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
3
- import "./index-Btz1W0X5.mjs";
3
+ import "./index-ClP0EE9p.mjs";
4
+ import { D as RequestContext, S as RuntimeResponse, a as KickServer, c as ActiveRuntime, dt as ModuleRegistry, g as RouteEntry, j as AdapterFactory, p as HttpRuntime, r as AppAdapter, rt as ModuleFactory, ut as KickPlugin, x as RuntimeCapabilities } from "./adapter-DK8WDonT.mjs";
4
5
  import { p as RouteFlags, s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
5
6
  import { C as MetaValue, c as ContextDecorator, h as DepValue, m as ContributorRegistrations, r as AppModuleEntry, u as ContextDecoratorSpec, x as ContextMetaKey } from "./app-module-DCA65GZZ.mjs";
6
- import { A as AdapterFactory, E as RequestContext, b as RuntimeCapabilities, f as HttpRuntime, h as RouteEntry, lt as KickPlugin, nt as ModuleFactory, r as AppAdapter, s as ActiveRuntime, ut as ModuleRegistry, x as RuntimeResponse } from "./adapter-2bnoYEPX.mjs";
7
- import { l as Reply } from "./kv-stores-Dx5RvIaP.mjs";
8
- import { t as BuildRoutesOptions } from "./router-builder-C6gmK0nZ.mjs";
7
+ import { l as Reply, p as PlatformContext } from "./kv-stores-B-1WZ2Fh.mjs";
8
+ import { t as BuildRoutesOptions } from "./router-builder-CUs9Gq4X.mjs";
9
9
  import "./request-id-CVzJ1uHD.mjs";
10
10
  import "./validate-DMYpUnrf.mjs";
11
- import "./error-handler-C1uWVGVY.mjs";
12
- import "./csrf-C4MwaMp4.mjs";
11
+ import "./error-handler-DxF2EogM.mjs";
12
+ import "./csrf-COFjRrUz.mjs";
13
13
  import "./helmet-C2QEU6S-.mjs";
14
14
  import "./cors-CsibNTQ6.mjs";
15
15
  import "./rate-limit-Bwed3jOV.mjs";
16
16
  import "./session-BHgRyfqZ.mjs";
17
- import "./upload-TW2ZuECF.mjs";
17
+ import "./upload-BukLMawc.mjs";
18
18
  import http, { IncomingMessage, ServerResponse } from "node:http";
19
+ import tls from "node:tls";
19
20
  import { Express, NextFunction, Request as Request$1, RequestHandler, Response as Response$1, Router } from "express";
20
21
  import { AsyncLocalStorage } from "node:async_hooks";
21
22
  //#region src/core/disposables.d.ts
@@ -413,6 +414,30 @@ declare function bindRoutePolicy<T extends object>(handler: T, receive: (table:
413
414
  /** Hand the table to a middleware if it declared the slot. */
414
415
  declare function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void;
415
416
  //#endregion
417
+ //#region src/http/cron-adapter.d.ts
418
+ /** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */
419
+ declare const CRON_WORKER_ENV = "KICK_CRON_WORKER";
420
+ interface CronAdapterOptions {
421
+ /** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */
422
+ enabled?: boolean;
423
+ }
424
+ declare const KickCronAdapter: AdapterFactory<CronAdapterOptions, unknown>;
425
+ //#endregion
426
+ //#region src/http/tracing.d.ts
427
+ declare const HANDLER_CHANNEL = "kickjs:handler";
428
+ declare const ERROR_CHANNEL = "kickjs:error";
429
+ declare const RESPONSE_CHANNEL = "kickjs:response";
430
+ /** What subscribers to `kickjs:handler` receive. */
431
+ interface HandlerTraceContext {
432
+ method: string;
433
+ /** The route pattern, e.g. `/api/v1/users/:id` — the span name APMs want. */
434
+ route: string;
435
+ controller?: string;
436
+ handler?: string;
437
+ requestId?: string;
438
+ ctx: RequestContext;
439
+ }
440
+ //#endregion
416
441
  //#region src/http/bootstrap.d.ts
417
442
  /**
418
443
  * Bootstrap a KickJS application.
@@ -442,10 +467,14 @@ interface KickHandler {
442
467
  /**
443
468
  * Web-standard handler: `fetch(Request) → Response`. Netlify Functions,
444
469
  * Vercel's fetch export, and anything else that speaks `Request`.
470
+ *
471
+ * Pass the platform context (Netlify's `context`, `{ waitUntil }` from
472
+ * `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after
473
+ * the response instead of being frozen with the instance.
445
474
  */
446
- fetch(request: Request): Promise<Response>;
475
+ fetch(request: Request, platform?: PlatformContext): Promise<Response>;
447
476
  /** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */
448
- node(req: IncomingMessage, res: ServerResponse): Promise<void>;
477
+ node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>;
449
478
  /** Set the app up now instead of on the first request (warm-up). */
450
479
  ready(): Promise<Application>;
451
480
  /** Shut adapters down and stop the internal forwarding server, if one started. */
@@ -480,7 +509,7 @@ interface KickHandler {
480
509
  * export const handler = createHandler({ modules })
481
510
  *
482
511
  * // netlify/functions/api.mjs
483
- * export default (request) => handler.fetch(request)
512
+ * export default (request, context) => handler.fetch(request, context)
484
513
  * export const config = { path: '/api/*' }
485
514
  * ```
486
515
  */
@@ -970,6 +999,13 @@ interface ShutdownOptions {
970
999
  */
971
1000
  closeServer?: boolean;
972
1001
  }
1002
+ /** See {@link ApplicationOptions.server}. */
1003
+ interface ServerOptions {
1004
+ /** TLS credentials and options (`key`, `cert`, `ca`, `pfx`, `passphrase`, …). */
1005
+ tls?: tls.SecureContextOptions & tls.TlsOptions;
1006
+ /** Serve HTTP/2 with HTTP/1.1 fallback. Requires `tls` and an HTTP/2-capable runtime. */
1007
+ http2?: boolean;
1008
+ }
973
1009
  interface ApplicationOptions {
974
1010
  /**
975
1011
  * Feature modules to load. Accepts both class form
@@ -1004,6 +1040,31 @@ interface ApplicationOptions {
1004
1040
  adapters?: AppAdapter[];
1005
1041
  /** Server port (falls back to PORT env var, then 3000) */
1006
1042
  port?: number;
1043
+ /**
1044
+ * The Node server `start()` creates in production. Omit for plain HTTP.
1045
+ *
1046
+ * - `{ tls }` — HTTPS on every runtime.
1047
+ * - `{ tls, http2: true }` — HTTP/2 (ALPN `h2`) with HTTP/1.1 fallback, so
1048
+ * HTTP/1.1 clients and WebSocket upgrades keep working. Fastify and h3
1049
+ * only; Express fails at boot with KICK007, and `http2` without `tls`
1050
+ * with KICK008.
1051
+ *
1052
+ * Ignored in dev mode, where Vite owns the server. Most deploys terminate
1053
+ * TLS / HTTP/2 at a proxy and need none of this.
1054
+ *
1055
+ * @example
1056
+ * ```ts
1057
+ * bootstrap({
1058
+ * modules,
1059
+ * runtime: fastifyRuntime(),
1060
+ * server: {
1061
+ * tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
1062
+ * http2: true,
1063
+ * },
1064
+ * })
1065
+ * ```
1066
+ */
1067
+ server?: ServerOptions;
1007
1068
  /** Global API prefix (default: '/api'). Pass `''` to mount at the root. */
1008
1069
  apiPrefix?: string;
1009
1070
  /**
@@ -1269,6 +1330,16 @@ declare class Application {
1269
1330
  private readonly runtime;
1270
1331
  private container;
1271
1332
  private httpServer;
1333
+ /** Set by startWithoutServer() — the serverless path, where cron runs over HTTP. */
1334
+ private handlerMode;
1335
+ /** The observer set this app installed — released on shutdown only if still current. */
1336
+ private observers;
1337
+ /**
1338
+ * Open HTTP/2 sessions. `server.close()` stops new sessions, but on older
1339
+ * Node (22 and earlier) existing ones keep accepting new streams — so
1340
+ * shutdown closes them itself.
1341
+ */
1342
+ private readonly http2Sessions;
1272
1343
  /** Forwarding server behind {@link fetch} on Node-based runtimes. */
1273
1344
  private loopback?;
1274
1345
  private readonly adapters;
@@ -1382,6 +1453,8 @@ declare class Application {
1382
1453
  * In **production**: creates its own `http.Server` and binds to the port.
1383
1454
  */
1384
1455
  start(): Promise<void>;
1456
+ /** The production server for {@link ApplicationOptions.server}. */
1457
+ private createNodeServer;
1385
1458
  /** HMR rebuild: swap Express handler without restarting the server */
1386
1459
  rebuild(): Promise<void>;
1387
1460
  /**
@@ -1447,7 +1520,7 @@ declare class Application {
1447
1520
  label: string;
1448
1521
  dependsOn: readonly string[];
1449
1522
  }>;
1450
- getHttpServer(): http.Server | null;
1523
+ getHttpServer(): KickServer | null;
1451
1524
  /**
1452
1525
  * Decide whether {@link Application} should auto-mount the
1453
1526
  * {@link requestScopeMiddleware} ALS wrapper.
@@ -1465,9 +1538,17 @@ declare class Application {
1465
1538
  private collectAdapterMiddleware;
1466
1539
  private mountMiddlewareList;
1467
1540
  private mountMiddlewareEntry;
1541
+ /**
1542
+ * `GET /_kick/cron/:scheduleId` — how a serverless platform
1543
+ * (Vercel crons) runs `@Cron` jobs: `kick build:vercel` emits one cron entry
1544
+ * per schedule pointing here. Mounted only in handler mode and only when
1545
+ * `CRON_SECRET` is set; the request must carry `Authorization: Bearer
1546
+ * $CRON_SECRET` (Vercel sends it). Runs every job on that schedule.
1547
+ */
1548
+ private mountCronTrigger;
1468
1549
  /** Middleware that tracks in-flight requests for graceful draining */
1469
1550
  private requestTrackingMiddleware;
1470
1551
  }
1471
1552
  //#endregion
1472
- export { MissingContributorError as $, ClusterOptions as A, GroupAssetKeysOptions as B, getRequestStore as C, expressRuntime as D, buildRoutes as E, RoutePolicyTable as F, MissingMountDepError as G, groupAssetKeys as H, bindRoutePolicy as I, MountSortItem as J, MountCycleError as K, offerRoutePolicy as L, KickHandler as M, createHandler as N, materializeRouter as O, bootstrap as P, MissingContextValueError as Q, AssetKeyPair as R, RequestStore as S, requestStore as T, stripExt as U, GroupAssetKeysResult as V, DuplicateMountNameError as W, ContributorCycleError as X, mountSort as Y, DuplicateContributorError as Z, TraceContext as _, HEALTH_PROBE as a, FormatKickErrorOptions as at, traceContext as b, HealthModuleConfig as c, formatKickError as ct, SpaAdapter as d, registerDisposable as dt, CircuitBreaker as et, SpaAdapterOptions as f, TRACEPARENT_HEADER as g, ViewAdapterOptions as h, ShutdownOptions as i, CircuitOpenError as it, isClusterPrimary as j, defineHttpContextDecorator as k, HealthProbe as l, Disposable as lt, ViewAdapter as m, ApplicationOptions as n, CircuitBreakerState as nt, HealthCheckResult as o, KickError as ot, resolveClientDir as p, MountKind as q, MiddlewareEntry as r, CircuitBreakerStats as rt, HealthController as s, KickErrorInit as st, Application as t, CircuitBreakerOptions as tt, healthModule as u, disposeAll as ut, TraceContextOptions as v, getRequestValue as w, requestScopeMiddleware as x, parseTraceparent as y, AssetKeyStrategy as z };
1473
- //# sourceMappingURL=application-_QOiAVx2.d.mts.map
1553
+ export { MissingMountDepError as $, defineHttpContextDecorator as A, CRON_WORKER_ENV as B, RequestStore as C, buildRoutes as D, requestStore as E, bootstrap as F, offerRoutePolicy as G, KickCronAdapter as H, ERROR_CHANNEL as I, GroupAssetKeysOptions as J, AssetKeyPair as K, HANDLER_CHANNEL as L, isClusterPrimary as M, KickHandler as N, expressRuntime as O, createHandler as P, DuplicateMountNameError as Q, HandlerTraceContext as R, requestScopeMiddleware as S, getRequestValue as T, RoutePolicyTable as U, CronAdapterOptions as V, bindRoutePolicy as W, groupAssetKeys as X, GroupAssetKeysResult as Y, stripExt as Z, TRACEPARENT_HEADER as _, Disposable as _t, ShutdownOptions as a, DuplicateContributorError as at, parseTraceparent as b, HealthController as c, CircuitBreaker as ct, healthModule as d, CircuitBreakerStats as dt, MountCycleError as et, SpaAdapter as f, CircuitOpenError as ft, ViewAdapterOptions as g, formatKickError as gt, ViewAdapter as h, KickErrorInit as ht, ServerOptions as i, ContributorCycleError as it, ClusterOptions as j, materializeRouter as k, HealthModuleConfig as l, CircuitBreakerOptions as lt, resolveClientDir as m, KickError as mt, ApplicationOptions as n, MountSortItem as nt, HEALTH_PROBE as o, MissingContextValueError as ot, SpaAdapterOptions as p, FormatKickErrorOptions as pt, AssetKeyStrategy as q, MiddlewareEntry as r, mountSort as rt, HealthCheckResult as s, MissingContributorError as st, Application as t, MountKind as tt, HealthProbe as u, CircuitBreakerState as ut, TraceContext as v, disposeAll as vt, getRequestStore as w, traceContext as x, TraceContextOptions as y, registerDisposable as yt, RESPONSE_CHANNEL as z };
1554
+ //# sourceMappingURL=application-B6Gp1nqK.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-B6Gp1nqK.d.mts","names":[],"sources":["../src/core/disposables.ts","../src/core/kick-error.ts","../src/core/circuit-breaker.ts","../src/core/context-errors.ts","../src/core/mount-sort.ts","../src/core/asset-keys.ts","../src/core/route-policy.ts","../src/http/cron-adapter.ts","../src/http/tracing.ts","../src/http/bootstrap.ts","../src/http/handler.ts","../src/http/cluster.ts","../src/http/define-http-context-decorator.ts","../src/http/runtimes/express.ts","../src/http/request-store.ts","../src/http/middleware/request-scope.ts","../src/http/middleware/trace-context.ts","../src/http/middleware/views.ts","../src/http/middleware/spa.ts","../src/http/health-module.ts","../src/http/application.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAaY,0BAA0B;;iBAKtB,mBAAmB,IAAI;;iBA6BjB,cAAc;;;;;;;;;;;;;;;;;;;;UC9BnB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;cAGC,kBAAkB;WACb;WACA;WACA;WACA;WACA;WACA,UAAU;EAE1B,YAAY,MAAM;;UAiDH;;;;;;EAMf;;;;;;;iBAQc,gBACd,KAAK,gBAAgB,WACrB,UAAS;;;;;;;;;;;;;;;;;;;;KCvFC;UAEK;;EAEf;;EAEA;;EAEA;;UAGe;EACf;EACA;EACA,OAAO;EACP,cAAc;;;;;cAMH,yBAAyB;WACR;EAA5B,YAA4B;;cAMjB;WAaO;UAZV;UACA;UACA;UACA;UACA;UACA;mBAES;mBACA;mBACA;EAEjB,YACkB,cAChB,SAAS;;;;;EAWL,QAAQ,GAAG,UAAU,QAAQ,KAAK,QAAQ;;EA0BhD,YAAY;;EAMZ,YAAY;;EAWZ;UASQ;UAWA;UAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cC1HG,gCAAgC;WAClC;WACA;WACA;WACA;EAET,YAAY,aAAa,mBAAmB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0CjD,iCAAiC;WACnC;WACA;EAET,YAAY,aAAa;;;;;;;;;;;;cA6Cd,8BAA8B;WAChC;WACA;EAET,YAAY,0BAA0B;;;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MAKA;;EAKJ,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BhB,MAAM,SAAS,UAAU,QAAQ;EASjC,OAAO,KAAK,KAAK,iBAAiB,KAAK,KAAK,gBAAgB,QAAQ;;;;;;;;;;;;;;;;UAwB5D;;;;;;UAkBA;;UA0BM;EAeR,SAAS;;EAkaT,gBAAgB;;;;;;;;;EAYhB,sBAAsB;;;;;;;;;;EA6BtB,SAAS;;UAyFP;;EAkBF,WAAW;;;;;;;;;;;EA8CX,SAAS,UAAS,kBAAuB;;;;;;;EAgL/C,iBAAiB;;;;;;;;EAWjB;IAAsB;IAAc,cAAc;;;EAKlD,iBAAiB;;EAKjB,eAAe;;;;;;EASf,uBAAuB;;;;;;;;;;;;;;;;;;;EAsBvB,mBAAmB;IACjB;IACA;IACA;IACA;;EA6CF,iBAAiB;;;;;;;;;;;;;;UAmBT;UAWA;UAmBA;UAUA;;;;;;;;UAeA;;UAoBA"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs v8.7.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";import{c as http2UnsupportedRuntimeError,i as createToken,l as moduleRouteMissingControllerError,n as tokenName,s as http2RequiresTlsError,t as Container,u as tlsCredentialsError}from"./container-Cqow_bOU.mjs";import{Logger,createLogger}from"./core/logger.mjs";import{t as getClassMeta}from"./metadata-BClL-Eb0.mjs";import{Controller,Get}from"./core/decorators.mjs";import{t as MutableModuleRegistry}from"./module-registry-kVXS3peW.mjs";import{a as setObserverPublisher,i as reportResponse,n as releaseObservers,o as setObservers,r as reportError,t as hasResponseObservers}from"./observers-C5Jid4FV.mjs";import{runCronJobs}from"./core/cron.mjs";import{i as runDisposables,n as drainDisposables,r as registerDisposable,t as disposeAll}from"./disposables-BFIEp5VA.mjs";import{HttpException}from"./core/errors.mjs";import{buildMountPath,joinPaths}from"./core/path.mjs";import{t as ROUTE_SLOT}from"./route-flag-BCBTtP_4.mjs";import"./core-Chc61ahe.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-Brup4e82.mjs";import{r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-FeJHstvF.mjs";import{c as requestScopeMiddleware,d as rejectUnsupportedBody,i as reply,l as EXPRESS_JSON_TYPES,n as applyHandlerResult,s as isRequestScopeMiddleware,t as publishMatchedRoute}from"./runtime-CV0SS-X5.mjs";import{requestId}from"./http/middleware/request-id.mjs";import{c as requestStore,i as settleBackgroundWork,r as pendingBackgroundWork,t as RequestContext}from"./context-CHuuc9r6.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{t as __decorate}from"./decorate-D9n58F0b.mjs";import{validate}from"./http/middleware/validate.mjs";import{buildUploadMiddleware}from"./http/middleware/upload.mjs";import http from"node:http";import{timingSafeEqual}from"node:crypto";import https from"node:https";import http2 from"node:http2";import tls from"node:tls";import express,{Router}from"express";import diagnostics from"node:diagnostics_channel";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}var DuplicateMountNameError=class extends Error{kind;mountName;constructor(kind,mountName){super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`),this.name=`DuplicateMountNameError`,this.kind=kind,this.mountName=mountName}},MissingMountDepError=class extends Error{kind;missing;dependent;constructor(kind,missing,dependent){super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`),this.name=`MissingMountDepError`,this.kind=kind,this.missing=missing,this.dependent=dependent}},MountCycleError=class extends Error{kind;cycle;constructor(kind,cycle){super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(` → `)}`),this.name=`MountCycleError`,this.kind=kind,this.cycle=Object.freeze([...cycle])}};function mountSort(items,kind){let byName=new Map;for(let item of items){if(byName.has(item.name))throw new DuplicateMountNameError(kind,item.name);byName.set(item.name,item)}let indegree=new Map,dependents=new Map;for(let item of items)indegree.set(item.name,item.dependsOn?.length??0);for(let item of items)for(let dep of item.dependsOn??[]){if(!byName.has(dep))throw new MissingMountDepError(kind,dep,item.name);let list=dependents.get(dep)??[];list.push(item),dependents.set(dep,list)}let queue=[];for(let item of items)indegree.get(item.name)===0&&queue.push(item);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.name)??[]){let next=(indegree.get(dependent.name)??0)-1;indegree.set(dependent.name,next),next===0&&queue.push(dependent)}}if(sorted.length!==items.length)throw new MountCycleError(kind,reconstructCycle(items.filter(it=>(indegree.get(it.name)??0)>0),byName));return sorted}function reconstructCycle(residual,byName){let residualNames=new Set(residual.map(r=>r.name)),start=residual[0].name,path=[start],seen=new Set([start]),cursor=start;for(;;){let nextDep=byName.get(cursor).dependsOn?.find(d=>residualNames.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}const HANDLER_CHANNEL=`kickjs:handler`,ERROR_CHANNEL=`kickjs:error`,RESPONSE_CHANNEL=`kickjs:response`,handlerChannel=diagnostics.tracingChannel(HANDLER_CHANNEL),errorChannel=diagnostics.channel(ERROR_CHANNEL),responseChannel=diagnostics.channel(RESPONSE_CHANNEL);function installChannelPublisher(){setObserverPublisher({name:`diagnostics_channel`,onError(error,info){errorChannel.hasSubscribers&&errorChannel.publish({error,...info})},onResponse(info){responseChannel.hasSubscribers&&responseChannel.publish(info)}},()=>responseChannel.hasSubscribers)}function traceHandler(handler,meta){return ctx=>handlerChannel.hasSubscribers?handlerChannel.tracePromise(async()=>handler(ctx),{...meta,requestId:ctx.requestId,ctx}):handler(ctx)}function __decorateMetadata(k,v){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(k,v)}const HEALTH_PROBE=createToken(`kick/Health/probe`);let HealthController=class{probe;constructor(probe){this.probe=probe}live(){return this.probe.isDraining()?reply(503,{status:`draining`,uptime:process.uptime()}):reply(200,{status:`ok`,uptime:process.uptime()})}async ready(){if(this.probe.isDraining())return reply(503,{status:`draining`,checks:[]});let checks=await this.probe.checks(),healthy=checks.every(c=>c.status===`up`);return reply(healthy?200:503,{status:healthy?`ready`:`degraded`,checks})}};__decorate([Get(`/live`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,void 0)],HealthController.prototype,`live`,null),__decorate([Get(`/ready`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,Promise)],HealthController.prototype,`ready`,null),HealthController=__decorate([Controller(),__decorateMetadata(`design:paramtypes`,[Object])],HealthController);const healthModule=defineModule({name:`HealthModule`,build:config=>({register(container){container.registerFactory(HealthController,()=>{let probe=container.resolve(HEALTH_PROBE);return new HealthController(probe)})},routes(){return{path:`/health`,controller:HealthController,version:!1,prefix:!1,flags:config.flags}}})});function materializeRouter(entries){let router=Router();for(let entry of entries){let method=entry.method.toLowerCase(),handlers=[];handlers.push((req,_res,next)=>{publishMatchedRoute(req,entry),next()});let contributorStep=run=>async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{await run(ctx),res.headersSent||next()}catch(err){next(err)}};entry.earlyContributorRunner&&handlers.push(contributorStep(entry.earlyContributorRunner)),entry.meta.validation&&handlers.push(validate(entry.meta.validation)),entry.meta.upload&&handlers.push(buildUploadMiddleware(entry.meta.upload));for(let mw of entry.middlewares)handlers.push((req,res,next)=>{let ctx=new RequestContext(req,res,next);Promise.resolve(mw(ctx,next)).catch(next)});entry.contributorRunner&&handlers.push(contributorStep(entry.contributorRunner)),handlers.push(async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{let result=await entry.handler(ctx);res.headersSent||applyHandlerResult(ctx,result)}catch(err){next(err)}}),router[method](entry.path,...handlers)}return router}function buildRoutes(controllerClass,options={}){return materializeRouter(buildRouteTable(controllerClass,options))}function expressRuntime(){return{name:`express`,createApp(options={}){let app=express();return app.disable(`x-powered-by`),app.set(`trust proxy`,options.trustProxy??!1),app},nodeHandler(app){return(req,res,next)=>{next?app(req,res,next):app(req,res)}},mountRoutes(app,table){for(let{mountPath,routes}of table)app.use(mountPath,materializeRouter(routes))},useConnect(app,mw,opts={}){opts.path===void 0?app.use(mw):app.use(opts.path,mw)},serveStatic(app,prefix,dir){app.use(prefix,express.static(dir))},setNotFound(app,mw){app.use(mw)},setErrorHandler(app,mw){app.use(mw)},capabilities:{render:!0,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!1,http2:!1}}}const HOP_BY_HOP_REQUEST=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`host`,`content-length`],HOP_BY_HOP_RESPONSE=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`trailer`,`content-encoding`,`content-length`];async function streamedBody(request){if(!request.body||request.method===`GET`||request.method===`HEAD`)return;let reader=request.body.getReader(),first=await reader.read();if(!first.done)return new ReadableStream({start(controller){controller.enqueue(first.value)},async pull(controller){let{done,value}=await reader.read();done?controller.close():controller.enqueue(value)},cancel(reason){return reader.cancel(reason)}})}function createLoopback(handle){let started,server=()=>(started??=new Promise((resolve,reject)=>{let instance=http.createServer((req,res)=>handle(req,res));instance.once(`error`,reject),instance.listen(0,`127.0.0.1`,()=>{instance.unref(),resolve({origin:`http://127.0.0.1:${instance.address().port}`,server:instance})})}).catch(err=>{throw started=void 0,err}),started);return{async fetch(request){let{origin}=await server(),url=new URL(request.url),headers=new Headers(request.headers);for(let name of HOP_BY_HOP_REQUEST)headers.delete(name);headers.set(`x-forwarded-host`,url.host),headers.set(`x-forwarded-proto`,url.protocol.slice(0,-1));let body=await streamedBody(request),upstream=await fetch(origin+url.pathname+url.search,{method:request.method,headers,body,...body?{duplex:`half`}:{},redirect:`manual`,signal:request.signal}),responseHeaders=new Headers(upstream.headers),named=responseHeaders.get(`connection`)?.split(`,`)??[];for(let name of[...HOP_BY_HOP_RESPONSE,...named])responseHeaders.delete(name.trim());return new Response(upstream.body,{status:upstream.status,statusText:upstream.statusText,headers:responseHeaders})},async close(){let running=await started?.catch(()=>void 0);if(started=void 0,!running)return;let closed=new Promise(resolve=>running.server.close(()=>resolve()));running.server.closeAllConnections(),await closed}}}const log=createLogger(`Application`);function assertUsableTls(options){let{key,cert,pfx,SNICallback,pskCallback}=options;if(!pfx&&!SNICallback&&!pskCallback){if(!key&&!cert)throw tlsCredentialsError(`no key/cert, pfx, SNICallback, or pskCallback`);if(!key)throw tlsCredentialsError(`cert is set but key is missing`);if(!cert)throw tlsCredentialsError(`key is set but cert is missing`)}try{tls.createSecureContext(options)}catch(err){throw tlsCredentialsError(err.message)}}function isModuleFactory(entry){return typeof entry==`function`&&`definition`in entry&&typeof entry.scoped==`function`}function isConfigurable(factory){return factory.definition?.defaults!=null}function toAppModule(entry){if(typeof entry!=`function`)return entry;if(isModuleFactory(entry)){if(isConfigurable(entry)){let name=entry.definition?.name||entry.name||`<anonymous>`;throw TypeError(`bootstrap: module \`${name}\` takes configuration, so it must be invoked.\n Write \`${name}()\` for its defaults, or \`${name}({ … })\` to configure it.\n Passing it bare would have silently selected the defaults.`)}return entry()}let name=entry.name||`<anonymous>`;if(!isConstructible(entry))throw TypeError(`bootstrap: module entry \`${name}\` is a function, but not a module class and not a defineModule() factory (no \`definition\`).\n A defineModule() module is passed as \`${name}\` or \`${name}()\`; a class must implement AppModule.`);let mod=new entry;if(typeof mod?.routes!=`function`)throw TypeError(`bootstrap: module entry \`${name}\` constructed, but the result does not implement AppModule — \`routes()\` is missing.\n A module class needs \`routes()\`; a defineModule() module is passed as \`${name}\` or \`${name}()\`.`);return mod}function isConstructible(fn){try{return Reflect.construct(String,[],fn),!0}catch{return!1}}var Application=class{options;app;runtime;container;httpServer=null;handlerMode=!1;observers=[];http2Sessions=new Set;loopback;adapters;routePolicy=new RoutePolicyTable;plugins;_moduleContributors=[];_inFlightRequests=0;_draining=!1;_shutdownInitiated=!1;_drainResolvers=[];constructor(options){this.options=options,this.runtime=options.runtime??expressRuntime(),this.app=this.runtime.createApp({trustProxy:options.trustProxy}),this.container=Container.getInstance(),this.plugins=mountSort(options.plugins??[],`plugin`);let allAdapters=[...this.plugins.flatMap(p=>p.adapters?.()??[]),...options.adapters??[]],anonAdapterCount=0,namedAdapters=allAdapters.map(adapter=>{if(!adapter.name){let ctorName=adapter.constructor?.name,fallback=ctorName&&ctorName!==`Object`?ctorName:`AnonymousAdapter#${anonAdapterCount++}`;return Object.assign(adapter,{name:fallback})}return adapter});this.adapters=mountSort(namedAdapters,`adapter`),this.observers=setObservers([...this.adapters,...this.plugins]),installChannelPublisher(),Container._requestStoreProvider=()=>requestStore.getStore()??null}get isDraining(){return this._draining}get inFlightRequests(){return this._inFlightRequests}getContainer(){return this.container}fetch(request){let runtimeApp=this.app;return typeof runtimeApp?.fetch==`function`?Promise.resolve(runtimeApp.fetch(request)):(this.loopback??=createLoopback((req,res)=>this.handle(req,res)),this.loopback.fetch(request))}handle(req,res,next){let handler=this.runtime.nodeHandler(this.app);next?handler(req,res,next):handler(req,res)}adapterCtx(server){let env=process.env.NODE_ENV??`development`;return{http:this.adapterHttp(),app:this.app,fetch:request=>this.fetch(request),container:this.container,server,env,isProduction:env===`production`}}adapterHttp(){return{route:(method,path,handler)=>{let entry={method,path,middlewares:[],contributorRunner:null,handler,meta:{}};this.runtime.mountRoutes(this.app,[{mountPath:`/`,routes:[entry]}])},mount:(prefix,routes)=>{this.runtime.mountRoutes(this.app,[{mountPath:prefix,routes}])},serveStatic:(prefix,dir)=>{this.runtime.serveStatic(this.app,prefix,dir)},use:(mw,opts)=>{this.runtime.useConnect(this.app,mw,opts)}}}async callHook(hook,ctx){if(hook)try{let result=hook(ctx);result&&typeof result.then==`function`&&await result}catch(err){log.error(err,`Adapter hook failed`)}}async setup(){log.debug(`Bootstrapping application...`),this._moduleContributors=[];let adapterMw=this.collectAdapterMiddleware();this.app.__kickApp=this;let ctx=this.adapterCtx();for(let adapter of this.adapters)await this.callHook(adapter.beforeMount?.bind(adapter),ctx);this.handlerMode&&this.mountCronTrigger(),this.runtime.useConnect(this.app,this.requestTrackingMiddleware()),this.shouldAutoMountRequestScope()&&this.runtime.useConnect(this.app,requestScopeMiddleware()),this.mountMiddlewareList(adapterMw.beforeGlobal);for(let plugin of this.plugins)plugin.register?.(this.container);for(let plugin of this.plugins)try{let mw=plugin.middleware?.()??[];for(let handler of mw)this.runtime.useConnect(this.app,handler)}catch(err){log.error(err,`Plugin middleware failed: ${plugin.name??`unknown`}`)}let declaredHelmet=(this.options.middlewares??[]).some(entry=>typeof entry==`function`&&Symbol.for(`kick/http/helmet`)in entry);if(this.options.security?.helmet!==!1&&!declaredHelmet)try{let{helmet:helmetFn}=await import(`./http/middleware/helmet.mjs`);this.runtime.useConnect(this.app,helmetFn())}catch{}let userMiddlewares=this.options.middlewares;if(userMiddlewares)for(let entry of userMiddlewares)this.mountMiddlewareEntry(entry);else if(this.runtime.useConnect(this.app,requestId()),!this.runtime.capabilities.nativeBodyParsing){let limit=this.options.jsonLimit??`1mb`;this.runtime.useConnect(this.app,express.json({limit,type:[...EXPRESS_JSON_TYPES]})),this.runtime.useConnect(this.app,express.urlencoded({extended:!0,limit})),this.runtime.useConnect(this.app,express.text({limit,type:`text/*`})),this.runtime.useConnect(this.app,rejectUnsupportedBody())}this.mountMiddlewareList(adapterMw.afterGlobal);let moduleRegistry=new MutableModuleRegistry;for(let plugin of this.plugins){for(let m of plugin.modules?.()??[])moduleRegistry.mount(m);plugin.setup?.(moduleRegistry)}for(let m of this.options.modules)moduleRegistry.mount(m);this.options.setup?.(moduleRegistry),this.options.health!==!1&&(this.container.registerInstance(HEALTH_PROBE,{isDraining:()=>this._draining,checks:async()=>{let withCheck=this.adapters.filter(a=>a.onHealthCheck);return(await Promise.allSettled(withCheck.map(a=>a.onHealthCheck()))).map((c,i)=>c.status===`fulfilled`?c.value:{name:withCheck[i].name??`unknown`,status:`down`})}}),moduleRegistry.mount(healthModule(this.options.health===!0?{}:this.options.health)));let modules=moduleRegistry.entries.map(entry=>{let mod=toAppModule(entry);return mod.register?.(this.container),mod});this.container.bootstrap(),this.container.has(Logger)||this.container.registerInstance(Logger,new Logger),this.mountMiddlewareList(adapterMw.beforeRoutes);let apiPrefix=this.options.apiPrefix??`/api`,defaultVersion=this.options.defaultVersion??1,shouldLogRoutes=this.options.logRouteTable??this.options.logRoutesTable??!1,mountedRoutes=[],adapterSources=[];for(let adapter of this.adapters){let adapterContribs=adapter.contributors?.()??[],adapterLabel=adapter.name??adapter.constructor.name??`adapter`;for(let registration of adapterContribs)adapterSources.push({source:`adapter`,registration,label:adapterLabel})}for(let plugin of this.plugins){let pluginContribs=plugin.contributors?.()??[],pluginLabel=plugin.name??plugin.constructor?.name??`plugin`;for(let registration of pluginContribs)adapterSources.push({source:`adapter`,registration,label:pluginLabel})}let globalSources=(this.options.contributors??[]).map(registration=>({source:`global`,registration,label:`bootstrap`}));this._moduleContributors=[];let seenRoutes=new Map,mountedPaths=[];for(let mod of modules){let declaredName=mod.name,ctorName=mod.constructor?.name,moduleLabel=typeof declaredName==`string`&&declaredName.length>0?declaredName:ctorName&&ctorName!==`Object`?ctorName:`module`,moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));for(let src of moduleSources)this._moduleContributors.push({registration:src.registration,label:moduleLabel});_setExternalContributorSources([...moduleSources,...adapterSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);if(route.router)this.runtime.useConnect(this.app,route.router,{path:mountPath});else if(route.controller){let routeTable=buildRouteTable(route.controller,{mountFlags:route.flags}),ctrl=route.controller.name??`controller`;for(let entry of routeTable){let owner=`${ctrl}.${String(entry.meta.handlerName??`?`)}`,fullPath=joinPaths(mountPath,entry.path);assertRouteUnique(seenRoutes,entry.method,fullPath,owner),mountedPaths.push({method:entry.method,path:fullPath}),this.routePolicy.add(entry.method,fullPath,entry.meta.flags)}let traced=routeTable.map(entry=>{let pattern=joinPaths(mountPath,entry.path);return{...entry,handler:traceHandler(entry.handler,{method:entry.method,route:pattern,controller:route.controller?.name,handler:entry.meta.handlerName}),meta:{...entry.meta,pattern}}});this.runtime.mountRoutes(this.app,[{mountPath,routes:traced}])}else throw moduleRouteMissingControllerError(mountPath);if(route.controller){for(let adapter of this.adapters)try{adapter.onRouteMount?.(route.controller,mountPath)}catch(err){log.error(err,`adapter.onRouteMount() failed for ${mountPath}`)}shouldLogRoutes&&mountedRoutes.push({controller:route.controller,mountPath})}}}finally{_setExternalContributorSources([])}}if(shouldLogRoutes&&mountedRoutes.length>0){let methodOrder=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`],methodRank=m=>{let i=methodOrder.indexOf(m);return i===-1?99:i},totalRoutes=0;log.info(`Routes:`);for(let{controller,mountPath}of mountedRoutes){let defs=getClassMeta(METADATA.ROUTES,controller,[]);if(defs.length===0)continue;let counts={};for(let def of defs){let m=def.method.toUpperCase();counts[m]=(counts[m]||0)+1}totalRoutes+=defs.length;let methods=Object.entries(counts).toSorted(([a],[b])=>methodRank(a)-methodRank(b)).map(([m,n])=>`${n} ${m}`).join(`, `),name=controller.name||`Controller`;log.info(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})`)}log.info(` Total: ${totalRoutes} routes`)}this.mountMiddlewareList(adapterMw.afterRoutes);for(let adapter of this.adapters)await this.callHook(adapter.beforeStart?.bind(adapter),ctx);for(let entry of this.options.middlewares??[])offerRoutePolicy(typeof entry==`function`?entry:entry.handler,this.routePolicy);for(let adapter of this.adapters)for(let mw of adapter.middleware?.()??[])offerRoutePolicy(mw.handler,this.routePolicy);this.runtime.setNotFound(this.app,this.options.onNotFound??notFoundHandler(mountedPaths)),this.runtime.setErrorHandler(this.app,observeErrors(this.options.onError??errorHandler()))}async registerOnly(){await this.setup()}async startWithoutServer(){this.handlerMode=!0,await this.setup();let needServer=this.adapters.filter(adapter=>adapter.afterStart);needServer.length>0&&log.warn(`No HTTP server in handler mode, so afterStart does not run for: ${needServer.map(adapter=>adapter.name).join(`, `)}. Anything they attach to the server (WebSockets, upgrade handlers) is unavailable.`);for(let plugin of this.plugins)await plugin.onReady?.(this.container)}async start(){let g=globalThis,serverOptions=this.options.server;if(serverOptions&&g.__kickjs_httpServer)log.warn(`server options (tls / http2) are ignored in dev mode — Vite owns the server`);else if(serverOptions){if(serverOptions.http2&&!serverOptions.tls)throw http2RequiresTlsError();if(serverOptions.http2&&!this.runtime.capabilities.http2)throw http2UnsupportedRuntimeError(this.runtime.name);serverOptions.tls&&assertUsableTls(serverOptions.tls)}if(await this.setup(),g.__kickjs_httpServer){this.httpServer=g.__kickjs_httpServer,log.debug(`Attached to Vite dev server`),g.__kickjs_app_shutdown=()=>this.shutdown();for(let adapter of this.adapters){let ctx=this.adapterCtx(this.httpServer);await this.callHook(adapter.afterStart?.bind(adapter),ctx)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);return}let port=this.options.port??parseInt(process.env.PORT||`3000`,10);this.httpServer=this.createNodeServer(),this.httpServer.on(`error`,err=>{throw err.code===`EADDRINUSE`&&(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`),process.exit(1)),err}),await new Promise((resolve,reject)=>{this.httpServer.listen(port,async()=>{try{let scheme=serverOptions?.tls?`https`:`http`,protocol=serverOptions?.http2?` (HTTP/2)`:``;log.info(`Server running on ${scheme}://localhost:${port}${protocol}`);for(let adapter of this.adapters){let afterCtx=this.adapterCtx(this.httpServer);await this.callHook(adapter.afterStart?.bind(adapter),afterCtx)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);resolve()}catch(err){reject(err)}})})}createNodeServer(){let handler=this.runtime.nodeHandler(this.app),{tls,http2:useHttp2}=this.options.server??{};if(useHttp2){let server=http2.createSecureServer({...tls,allowHTTP1:!0},handler);return server.on(`session`,session=>{this.http2Sessions.add(session),session.once(`close`,()=>this.http2Sessions.delete(session))}),server}return tls?https.createServer(tls,handler):http.createServer(handler)}async rebuild(){let prevApp=this.app,prevContainer=this.container,staleDisposables=drainDisposables();try{Container.reset(),this.container=Container.getInstance(),this.app=this.runtime.createApp({trustProxy:this.options.trustProxy}),await this.setup()}catch(err){log.error(err,`HMR rebuild failed, keeping previous app`),await runDisposables(drainDisposables());for(let d of staleDisposables)registerDisposable(d);this.app=prevApp,this.container=prevContainer;return}await runDisposables(staleDisposables),this.httpServer&&(this.httpServer.removeAllListeners(`request`),this.httpServer.on(`request`,this.runtime.nodeHandler(this.app)),log.debug(`HMR: app rebuilt and swapped`))}async shutdown(options={}){let closeServer=options.closeServer??!0;if(this._shutdownInitiated){log.debug(`Shutdown already in progress, skipping duplicate call`);return}this._shutdownInitiated=!0,this._draining=!0,log.debug(`Shutting down — draining in-flight requests...`);let timeoutMs=this.options.shutdownTimeout??3e4,timer,forceExitPromise=timeoutMs>0?new Promise(resolve=>{timer=setTimeout(()=>resolve(`timeout`),timeoutMs),timer.unref()}):new Promise(()=>{});try{if(closeServer&&this.httpServer){this.httpServer.close(()=>{});for(let session of this.http2Sessions)session.close()}if(closeServer&&this._inFlightRequests>0){log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`);let drainPromise=new Promise(resolve=>{this._drainResolvers.push(()=>resolve(`drained`))});if(await Promise.race([drainPromise,forceExitPromise])===`timeout`){log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`);for(let session of this.http2Sessions)session.destroy()}else log.debug(`All in-flight requests completed`)}closeServer&&pendingBackgroundWork()>0&&(log.debug(`Waiting for ${pendingBackgroundWork()} waitUntil() task(s) to settle...`),await Promise.race([settleBackgroundWork().then(()=>`settled`),forceExitPromise])===`timeout`&&log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${pendingBackgroundWork()} waitUntil() task(s) still running`));let hookTimeoutMs=closeServer?timeoutMs:Math.min(timeoutMs,5e3),timeBoxed=(label,run)=>{let hook=(async()=>run())();return hookTimeoutMs<=0?hook:new Promise((resolve,reject)=>{let t=setTimeout(()=>{log.warn(`${label} did not finish shutting down within ${hookTimeoutMs}ms — continuing without it. Its resources may still be held.`),resolve(void 0)},hookTimeoutMs);t.unref(),hook.then(value=>{clearTimeout(t),resolve(value)},err=>{clearTimeout(t),reject(err)})})},wasListening=this.httpServer?.listening===!0,results=await Promise.allSettled([...this.plugins.map(plugin=>timeBoxed(`Plugin '${plugin.name}'`,()=>plugin.shutdown?.())),...this.adapters.map(adapter=>timeBoxed(`Adapter '${adapter.name}'`,()=>adapter.shutdown?.()))]);!closeServer&&wasListening&&this.httpServer?.listening===!1&&log.error("An adapter or plugin closed the shared HTTP server during an HMR reload. The dev server is now unreachable and will not rebind until you restart it. Close only what you own: socket.io's `io.close()` closes the HTTP server passed to its constructor — on a reload, disconnect the sockets instead.");for(let result of results)result.status===`rejected`&&log.error({err:result.reason},`Adapter shutdown failed`);await disposeAll(),this.container.flushChanges(),await this.loopback?.close(),this.loopback=void 0,closeServer&&releaseObservers(this.observers)}finally{timer&&clearTimeout(timer)}}getRuntimeApp(){return this.app}getActiveRuntime(){return{name:this.runtime.name,capabilities:this.runtime.capabilities}}getExpressApp(){return this.app}getAdapters(){return this.adapters}getPlugins(){return this.plugins}getContributors(){let out=[],ingest=(list,source,label)=>{if(list)for(let reg of list){let r=reg;if(r.key===void 0||r.key===null)continue;let key=typeof r.key==`string`?r.key:tokenName(r.key);out.push({key,source,label,dependsOn:Array.isArray(r.dependsOn)?r.dependsOn:[]})}};for(let adapter of this.adapters)ingest(adapter.contributors?.(),`adapter`,adapter.name??`adapter`);for(let plugin of this.plugins)ingest(plugin.contributors?.(),`plugin`,plugin.name??`plugin`);for(let{registration,label}of this._moduleContributors)ingest([registration],`module`,label);return ingest(this.options.contributors,`global`,`bootstrap`),out}getHttpServer(){return this.httpServer}shouldAutoMountRequestScope(){if(this.options.contextStore===`manual`)return!1;let userEntries=this.options.middlewares??[];for(let entry of userEntries){let handler=typeof entry==`function`?entry:entry.handler;if(isRequestScopeMiddleware(handler))return!1}return!0}collectAdapterMiddleware(){let result={beforeGlobal:[],afterGlobal:[],beforeRoutes:[],afterRoutes:[]};for(let adapter of this.adapters){let entries=adapter.middleware?.()??[];for(let entry of entries)result[entry.phase??`afterGlobal`].push(entry)}return result}mountMiddlewareList(entries){for(let entry of entries){if(entry.path===void 0){this.runtime.useConnect(this.app,entry.handler);continue}this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}}mountMiddlewareEntry(entry){typeof entry==`function`?this.runtime.useConnect(this.app,entry):this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}mountCronTrigger(){let secret=process.env.CRON_SECRET;secret&&this.adapterHttp().route(`GET`,`/_kick/cron/:scheduleId`,async ctx=>{if(!matchesBearer(ctx.headers.authorization,secret))throw new HttpException(401,`Missing or invalid CRON_SECRET bearer token`);let result=await runCronJobs(this.container,{scheduleId:ctx.params.scheduleId},`http`);ctx.json(result,result.failed>0?500:200)})}requestTrackingMiddleware(){return(req,res,next)=>{this._inFlightRequests++;let started=hasResponseObservers()?performance.now():void 0,onFinish=()=>settle(!0),onClose=()=>settle(!1),settle=finished=>{if(res.removeListener(`finish`,onFinish),res.removeListener(`close`,onClose),finished&&started!==void 0){let matched=req[ROUTE_SLOT];reportResponse({method:req.method,path:requestPath(req),route:matched?.pattern,status:res.statusCode,durationMs:performance.now()-started,requestId:requestIdOf(req)})}if(this._inFlightRequests--,this._draining&&this._inFlightRequests===0){for(let resolve of this._drainResolvers)resolve();this._drainResolvers=[]}};res.on(`finish`,onFinish),res.on(`close`,onClose),next()}}};function requestPath(req){return(req.originalUrl??req.url??``).split(`?`)[0]}function requestIdOf(req){let header=req.headers?.[`x-request-id`];return req.requestId??(typeof header==`string`?header:void 0)}function errorStatus(err){return typeof err?.problem?.status==`number`?err.problem.status:typeof err?.status==`number`?err.status:typeof err?.statusCode==`number`?err.statusCode:err?.name===`ZodError`?422:500}function observeErrors(handler){return((err,req,res,next)=>{let matched=req?.[ROUTE_SLOT];return reportError(err,{source:`request`,requestId:requestIdOf(req??{}),method:req?.method,path:requestPath(req??{}),route:matched?.pattern,status:errorStatus(err)}),handler(err,req,res,next)})}function matchesBearer(header,secret){if(typeof header!=`string`)return!1;let given=Buffer.from(header),expected=Buffer.from(`Bearer ${secret}`);return given.length===expected.length&&timingSafeEqual(given,expected)}export{HEALTH_PROBE as a,ERROR_CHANNEL as c,DuplicateMountNameError as d,MissingMountDepError as f,defineModule as h,materializeRouter as i,HANDLER_CHANNEL as l,mountSort as m,buildRoutes as n,HealthController as o,MountCycleError as p,expressRuntime as r,healthModule as s,Application as t,RESPONSE_CHANNEL as u};
12
+ //# sourceMappingURL=application-D2scwBz-.mjs.map