@forinda/kickjs 10.6.0 → 10.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 (121) hide show
  1. package/dist/application-BSzwuTQ6.mjs +14 -0
  2. package/dist/application-BSzwuTQ6.mjs.map +1 -0
  3. package/dist/{application-BD9LQ2s4.d.mts → application-BZjDmsWb.d.mts} +39 -6
  4. package/dist/application-BZjDmsWb.d.mts.map +1 -0
  5. package/dist/{background-DSztbyc4.mjs → background-BJjLKrnK.mjs} +3 -3
  6. package/dist/{background-DSztbyc4.mjs.map → background-BJjLKrnK.mjs.map} +1 -1
  7. package/dist/{bootstrap-DdTHtS8P.mjs → bootstrap-Dxax6Mcp.mjs} +3 -3
  8. package/dist/{bootstrap-DdTHtS8P.mjs.map → bootstrap-Dxax6Mcp.mjs.map} +1 -1
  9. package/dist/{bounded-counters-Bd7X3eI5.mjs → bounded-counters-_6sdDRhT.mjs} +2 -2
  10. package/dist/{bounded-counters-Bd7X3eI5.mjs.map → bounded-counters-_6sdDRhT.mjs.map} +1 -1
  11. package/dist/{client-ip-DxEVqZP-.mjs → client-ip-CrO5ktYs.mjs} +2 -2
  12. package/dist/{client-ip-DxEVqZP-.mjs.map → client-ip-CrO5ktYs.mjs.map} +1 -1
  13. package/dist/config/index.mjs +2 -2
  14. package/dist/{config-_YTqZtnE.mjs → config-CWKj0Z66.mjs} +3 -3
  15. package/dist/{config-_YTqZtnE.mjs.map → config-CWKj0Z66.mjs.map} +1 -1
  16. package/dist/{context-UaQ6cv0K.mjs → context-BlJRkMyq.mjs} +3 -3
  17. package/dist/{context-UaQ6cv0K.mjs.map → context-BlJRkMyq.mjs.map} +1 -1
  18. package/dist/{context-errors-DcPmDybm.mjs → context-errors-ykpXYECS.mjs} +2 -2
  19. package/dist/{context-errors-DcPmDybm.mjs.map → context-errors-ykpXYECS.mjs.map} +1 -1
  20. package/dist/{contributor-runner-BHjr6qSE.mjs → contributor-runner-BM-5Wr19.mjs} +3 -3
  21. package/dist/{contributor-runner-BHjr6qSE.mjs.map → contributor-runner-BM-5Wr19.mjs.map} +1 -1
  22. package/dist/core/adapter.mjs +1 -1
  23. package/dist/core/app-module.mjs +1 -1
  24. package/dist/core/cache.mjs +1 -1
  25. package/dist/core/container.mjs +2 -2
  26. package/dist/core/cron.mjs +2 -2
  27. package/dist/core/decorators.mjs +2 -2
  28. package/dist/core/errors.mjs +1 -1
  29. package/dist/core/interfaces.mjs +1 -1
  30. package/dist/core/logger.mjs +1 -1
  31. package/dist/core/path.mjs +1 -1
  32. package/dist/core/plugin.mjs +1 -1
  33. package/dist/core/reactivity.mjs +1 -1
  34. package/dist/{core-Ddq8b9hi.mjs → core-DlrlhjF4.mjs} +3 -3
  35. package/dist/{core-Ddq8b9hi.mjs.map → core-DlrlhjF4.mjs.map} +1 -1
  36. package/dist/{decorate-wrAUzCjW.mjs → decorate-BHhpOfEF.mjs} +3 -3
  37. package/dist/{decorate-wrAUzCjW.mjs.map → decorate-BHhpOfEF.mjs.map} +1 -1
  38. package/dist/{define-adapter-Ce1FDvEo.mjs → define-adapter-CF-DJRq9.mjs} +2 -2
  39. package/dist/{define-adapter-Ce1FDvEo.mjs.map → define-adapter-CF-DJRq9.mjs.map} +1 -1
  40. package/dist/{di-hooks-MFthA-Fs.mjs → di-hooks-CCKeiLT-.mjs} +2 -2
  41. package/dist/{di-hooks-MFthA-Fs.mjs.map → di-hooks-CCKeiLT-.mjs.map} +1 -1
  42. package/dist/{disposables-BgUIg4s1.mjs → disposables-bnkL4rG7.mjs} +1 -1
  43. package/dist/{express-BcfJgvBP.mjs → express-4fvuMB5q.mjs} +3 -3
  44. package/dist/{express-BcfJgvBP.mjs.map → express-4fvuMB5q.mjs.map} +1 -1
  45. package/dist/{express-lazy-DCYWtKZx.mjs → express-lazy-D9MZnma8.mjs} +3 -3
  46. package/dist/{express-lazy-DCYWtKZx.mjs.map → express-lazy-D9MZnma8.mjs.map} +1 -1
  47. package/dist/{handler-CS1BhG0C.mjs → handler-TzaD8jPN.mjs} +3 -3
  48. package/dist/{handler-CS1BhG0C.mjs.map → handler-TzaD8jPN.mjs.map} +1 -1
  49. package/dist/{host-lMSIGnh7.mjs → host-CtpcIKcA.mjs} +2 -2
  50. package/dist/{host-lMSIGnh7.mjs.map → host-CtpcIKcA.mjs.map} +1 -1
  51. package/dist/http/application.d.mts +2 -2
  52. package/dist/http/application.mjs +2 -2
  53. package/dist/http/bootstrap.d.mts +1 -1
  54. package/dist/http/bootstrap.mjs +2 -2
  55. package/dist/http/context.mjs +2 -2
  56. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  57. package/dist/http/middleware/breach-padding.mjs +1 -1
  58. package/dist/http/middleware/cors.mjs +1 -1
  59. package/dist/http/middleware/csrf.mjs +2 -2
  60. package/dist/http/middleware/error-handler.mjs +2 -2
  61. package/dist/http/middleware/helmet.mjs +1 -1
  62. package/dist/http/middleware/rate-limit.mjs +2 -2
  63. package/dist/http/middleware/request-id.mjs +1 -1
  64. package/dist/http/middleware/request-logger.mjs +2 -2
  65. package/dist/http/middleware/session.mjs +2 -2
  66. package/dist/http/middleware/spa.d.mts +1 -1
  67. package/dist/http/middleware/spa.mjs +2 -2
  68. package/dist/http/middleware/upload.mjs +2 -2
  69. package/dist/http/middleware/validate.mjs +1 -1
  70. package/dist/http/middleware/views.d.mts +1 -1
  71. package/dist/http/middleware/views.mjs +2 -2
  72. package/dist/http/query/index.mjs +2 -2
  73. package/dist/http/router-builder.mjs +2 -2
  74. package/dist/http/runtimes/express.mjs +2 -2
  75. package/dist/http/runtimes/fastify.mjs +2 -2
  76. package/dist/http/runtimes/h3-web.mjs +1 -1
  77. package/dist/http/runtimes/h3.mjs +2 -2
  78. package/dist/index.d.mts +2 -2
  79. package/dist/index.mjs +2 -2
  80. package/dist/{is-production-MYGnN2Nv.mjs → is-production-BfIKY2Sw.mjs} +2 -2
  81. package/dist/{is-production-MYGnN2Nv.mjs.map → is-production-BfIKY2Sw.mjs.map} +1 -1
  82. package/dist/{jobs-ANHUk_Ht.mjs → jobs-BJfIOWUT.mjs} +3 -3
  83. package/dist/{jobs-ANHUk_Ht.mjs.map → jobs-BJfIOWUT.mjs.map} +1 -1
  84. package/dist/{kv-stores-Cro8JwAF.mjs → kv-stores-BeDHfiyW.mjs} +3 -3
  85. package/dist/{kv-stores-Cro8JwAF.mjs.map → kv-stores-BeDHfiyW.mjs.map} +1 -1
  86. package/dist/{lazy-serve-static-Zge6_pKo.mjs → lazy-serve-static-BUMcYDMn.mjs} +3 -3
  87. package/dist/{lazy-serve-static-Zge6_pKo.mjs.map → lazy-serve-static-BUMcYDMn.mjs.map} +1 -1
  88. package/dist/{metadata-_LqQme8p.mjs → metadata-x0eCJRTl.mjs} +1 -1
  89. package/dist/{observers-Oedvuzit.mjs → observers-Ss6-7Si7.mjs} +2 -2
  90. package/dist/{observers-Oedvuzit.mjs.map → observers-Ss6-7Si7.mjs.map} +1 -1
  91. package/dist/{precompressed-B6wz_5tz.mjs → precompressed-BBXQUDXp.mjs} +2 -2
  92. package/dist/{precompressed-B6wz_5tz.mjs.map → precompressed-BBXQUDXp.mjs.map} +1 -1
  93. package/dist/{query-KMR84Kwu.mjs → query-DIS_2QiJ.mjs} +2 -2
  94. package/dist/{query-KMR84Kwu.mjs.map → query-DIS_2QiJ.mjs.map} +1 -1
  95. package/dist/{reply-BQTif5Iu.mjs → reply-BVdki3Z4.mjs} +2 -2
  96. package/dist/{reply-BQTif5Iu.mjs.map → reply-BVdki3Z4.mjs.map} +1 -1
  97. package/dist/{request-scope-L71-nmRe.mjs → request-scope-BTdpkAqv.mjs} +3 -3
  98. package/dist/{request-scope-L71-nmRe.mjs.map → request-scope-BTdpkAqv.mjs.map} +1 -1
  99. package/dist/{respond-DR7zkOUf.mjs → respond-BUWP_L0Y.mjs} +2 -2
  100. package/dist/{respond-DR7zkOUf.mjs.map → respond-BUWP_L0Y.mjs.map} +1 -1
  101. package/dist/{rolldown-runtime-DouoOEDq.mjs → rolldown-runtime-Dp0gGuQG.mjs} +1 -1
  102. package/dist/{route-flag-DCOS_F5A.mjs → route-flag-p89Wzt0D.mjs} +3 -3
  103. package/dist/{route-flag-DCOS_F5A.mjs.map → route-flag-p89Wzt0D.mjs.map} +1 -1
  104. package/dist/{route-policy-Cy-oSUro.mjs → route-policy-DJMiiTrD.mjs} +2 -2
  105. package/dist/{route-policy-Cy-oSUro.mjs.map → route-policy-DJMiiTrD.mjs.map} +1 -1
  106. package/dist/{router-builder-U-kiHlqo.mjs → router-builder-dCWA4pdK.mjs} +3 -3
  107. package/dist/{router-builder-U-kiHlqo.mjs.map → router-builder-dCWA4pdK.mjs.map} +1 -1
  108. package/dist/{settings-CrEgdXc0.mjs → settings-BHYpcj_p.mjs} +3 -3
  109. package/dist/{settings-CrEgdXc0.mjs.map → settings-BHYpcj_p.mjs.map} +1 -1
  110. package/dist/{token-B1FRPTVt.mjs → token-Cz4YKuL-.mjs} +1 -1
  111. package/dist/{upload-config-DEnNEwL4.mjs → upload-config-CkMQ5bW5.mjs} +2 -2
  112. package/dist/{upload-config-DEnNEwL4.mjs.map → upload-config-CkMQ5bW5.mjs.map} +1 -1
  113. package/dist/{url-for-CLtZIeYd.mjs → url-for-CDxa8ik-.mjs} +3 -3
  114. package/dist/{url-for-CLtZIeYd.mjs.map → url-for-CDxa8ik-.mjs.map} +1 -1
  115. package/dist/{web-crypto-B6iM0yYx.mjs → web-crypto-Bijc63tB.mjs} +2 -2
  116. package/dist/{web-crypto-B6iM0yYx.mjs.map → web-crypto-Bijc63tB.mjs.map} +1 -1
  117. package/dist/web.mjs +2 -2
  118. package/package.json +1 -1
  119. package/dist/application-BD9LQ2s4.d.mts.map +0 -1
  120. package/dist/application-DwYTFctU.mjs +0 -14
  121. package/dist/application-DwYTFctU.mjs.map +0 -1
@@ -7,6 +7,7 @@ import { t as Container } from "./container-4iJdDkRH.mjs";
7
7
  import { p as RouteFlags, s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
8
8
  import { C as MetaValue, c as ContextDecorator, h as DepValue, m as ContributorRegistrations, r as AppModuleEntry, u as ContextDecoratorSpec, x as ContextMetaKey } from "./app-module-Cuu-Ma_E.mjs";
9
9
  import { l as PlatformContext, m as Reply } from "./kv-stores-C1sQs2Rb.mjs";
10
+ import { t as ComputedRef } from "./reactivity-BkMNA0kp.mjs";
10
11
  import { t as ValidationErrorFactory } from "./validate-D4Poe2EE.mjs";
11
12
  import { t as AllowedHostsOptions } from "./allowed-hosts-BpKwviq5.mjs";
12
13
  import { t as BuildRoutesOptions } from "./router-builder-BfbEdxew.mjs";
@@ -14,6 +15,7 @@ import "./error-handler-CH4PPZCK.mjs";
14
15
  import "./csrf-ZFOrJZhJ.mjs";
15
16
  import "./upload-Jgs9BFC4.mjs";
16
17
  import http, { IncomingMessage, ServerResponse } from "node:http";
18
+ import https from "node:https";
17
19
  import tls from "node:tls";
18
20
  import { AsyncLocalStorage } from "node:async_hooks";
19
21
  //#region src/core/kick-error.d.ts
@@ -1234,12 +1236,17 @@ interface ServerOptions {
1234
1236
  /** A mounted controller route, as `app.getRoutes()` lists it. */
1235
1237
  interface MountedRouteInfo {
1236
1238
  method: string;
1237
- /** Full pattern, prefix and version included: `/api/v1/users/:id`. */
1239
+ /** Full pattern, prefix and version included: `/api/v1/users/:id`. Static files: `/assets/*`. */
1238
1240
  pattern: string;
1241
+ /** The controller — or, for a route an adapter added, the adapter's name. */
1239
1242
  controller: string;
1240
1243
  handler: string;
1241
1244
  /** Context contributors in execution order, with where each was registered. */
1242
1245
  contributors: readonly RouteContributor[];
1246
+ /** A module's controller, or an adapter through `ctx.http` / `ctx.management.http`. */
1247
+ source: 'module' | 'adapter';
1248
+ /** Which listener serves it: the app's port, or the management port. */
1249
+ port: 'app' | 'management';
1243
1250
  }
1244
1251
  /** What `app.describeConfig()` returns. */
1245
1252
  interface ConfigDescription {
@@ -1692,6 +1699,8 @@ interface ApplicationOptions {
1692
1699
  * ```
1693
1700
  */
1694
1701
  declare const APPLICATION: import("@forinda/kickjs-di").InjectionToken<Application>;
1702
+ /** {@link Application.status}. */
1703
+ type AppStatus = 'idle' | 'starting' | 'ready' | 'draining' | 'stopped';
1695
1704
  /** {@link ApplicationOptions.management}. */
1696
1705
  interface ManagementOptions {
1697
1706
  /** Port for the management listener. */
@@ -1770,9 +1779,15 @@ declare class Application {
1770
1779
  /** Number of HTTP requests currently being processed */
1771
1780
  private _inFlightRequests;
1772
1781
  /** Whether the application is draining (shutting down gracefully) */
1773
- private _draining;
1774
- /** True while start() runs — readiness answers 503 until the app serves. */
1775
- private _starting;
1782
+ private readonly _status;
1783
+ /**
1784
+ * Where the app is in its lifecycle, as a read-only reactive value: read
1785
+ * `status.value`, or `watch(app.status, fn)` to act on a change —
1786
+ * `'starting'` while `start()` runs, `'ready'` once it serves, `'draining'`
1787
+ * from `shutdown()`, `'stopped'` after. An app that is only set up (tests)
1788
+ * stays `'idle'`.
1789
+ */
1790
+ readonly status: ComputedRef<AppStatus>;
1776
1791
  /** Whether shutdown has already been initiated (prevents double-shutdown) */
1777
1792
  private _shutdownInitiated;
1778
1793
  /** Resolvers waiting for in-flight requests to reach zero */
@@ -1913,6 +1928,12 @@ declare class Application {
1913
1928
  * (it receives the `http.Server`), and no process signal handlers.
1914
1929
  */
1915
1930
  startWithoutServer(): Promise<void>;
1931
+ /**
1932
+ * Run a startup, leaving the status at `'stopped'` if it fails — a failed
1933
+ * startup is not still starting.
1934
+ */
1935
+ private untilStartedOrStopped;
1936
+ private startWithoutServerSteps;
1916
1937
  /**
1917
1938
  * Start the HTTP server.
1918
1939
  *
@@ -1923,6 +1944,7 @@ declare class Application {
1923
1944
  * In **production**: creates its own `http.Server` and binds to the port.
1924
1945
  */
1925
1946
  start(): Promise<void>;
1947
+ private startSteps;
1926
1948
  /** Listen on the public port, then run afterStart and onReady. */
1927
1949
  private listenAndFinishStartup;
1928
1950
  private closeManagementServer;
@@ -2003,6 +2025,12 @@ declare class Application {
2003
2025
  dependsOn: readonly string[];
2004
2026
  }>;
2005
2027
  getHttpServer(): KickServer | null;
2028
+ /**
2029
+ * The management listener (`bootstrap({ management })`) — its address, or
2030
+ * something to attach to it. `null` without a management port, in dev mode,
2031
+ * before `start()` has opened it, and after shutdown has closed it.
2032
+ */
2033
+ getManagementServer(): http.Server | https.Server | null;
2006
2034
  /**
2007
2035
  * Decide whether {@link Application} should auto-mount the
2008
2036
  * {@link requestScopeMiddleware} ALS wrapper.
@@ -2031,6 +2059,11 @@ declare class Application {
2031
2059
  /** Middleware that tracks in-flight requests for graceful draining */
2032
2060
  private requestTrackingMiddleware;
2033
2061
  }
2062
+ /**
2063
+ * One line per owner (controller or adapter): its routes, or — past a few —
2064
+ * how many there are under their common prefix, so `/_debug`'s dozens stay one line.
2065
+ */
2066
+ declare function describeRoutes(routes: readonly MountedRouteInfo[]): string[];
2034
2067
  //#endregion
2035
- export { ERROR_CHANNEL as $, getRequestStore as A, MountSortItem as At, createSigner as B, CircuitOpenError as Bt, TRACEPARENT_HEADER as C, GroupAssetKeysResult as Ct, traceContext as D, MissingMountDepError as Dt, parseTraceparent as E, DuplicateMountNameError as Et, materializeRouter as F, MissingContributorError as Ft, hashPassword as G, PasswordCheck as H, KickError as Ht, SignedCheck as I, CircuitBreaker as It, ClusterOptions as J, verifyPassword as K, Signer as L, CircuitBreakerOptions as Lt, requestStore as M, ContributorCycleError as Mt, buildRoutes as N, DuplicateContributorError as Nt, requestScopeMiddleware as O, MountCycleError as Ot, expressRuntime as P, MissingContextValueError as Pt, bootstrap as Q, SignerOptions as R, CircuitBreakerState as Rt, viewDirs as S, GroupAssetKeysOptions as St, TraceContextOptions as T, stripExt as Tt, PasswordHashOptions as U, KickErrorInit as Ut, LegacyHasher as V, FormatKickErrorOptions as Vt, VerifyPasswordOptions as W, formatKickError as Wt, KickHandler as X, isClusterPrimary as Y, createHandler as Z, SpaAdapter as _, RoutePolicyTable as _t, ConfigOrigins as a, KickCronAdapter as at, ViewAdapter as b, AssetKeyPair as bt, MountedRouteInfo as c, RequestHistogram as ct, HEALTH_PROBE as d, CheckMessage as dt, HANDLER_CHANNEL as et, HealthCheckResult as f, StartupCheck as ft, healthModule as g, StartupTimelineSnapshot as gt, HealthProbe as h, StartupStep as ht, ConfigDescription as i, CronAdapterOptions as it, getRequestValue as j, mountSort as jt, RequestStore as k, MountKind as kt, ServerOptions as l, metricsAdapter as lt, HealthModuleConfig as m, defineCheck as mt, Application as n, RESPONSE_CHANNEL as nt, ManagementOptions as o, RAW_BODY as ot, HealthController as p, StartupCheckError as pt, defineHttpContextDecorator as q, ApplicationOptions as r, CRON_WORKER_ENV as rt, MiddlewareEntry as s, MetricsOptions as st, APPLICATION as t, HandlerTraceContext as tt, ShutdownOptions as u, CheckContext as ut, SpaAdapterOptions as v, bindRoutePolicy as vt, TraceContext as w, groupAssetKeys as wt, ViewAdapterOptions as x, AssetKeyStrategy as xt, resolveClientDir as y, offerRoutePolicy as yt, VerifyOptions as z, CircuitBreakerStats as zt };
2036
- //# sourceMappingURL=application-BD9LQ2s4.d.mts.map
2068
+ export { createHandler as $, requestScopeMiddleware as A, MountCycleError as At, SignerOptions as B, CircuitBreakerState as Bt, ViewAdapterOptions as C, AssetKeyStrategy as Ct, TraceContextOptions as D, stripExt as Dt, TraceContext as E, groupAssetKeys as Et, buildRoutes as F, DuplicateContributorError as Ft, PasswordHashOptions as G, KickErrorInit as Gt, createSigner as H, CircuitOpenError as Ht, expressRuntime as I, MissingContextValueError as It, verifyPassword as J, VerifyPasswordOptions as K, formatKickError as Kt, materializeRouter as L, MissingContributorError as Lt, getRequestStore as M, MountSortItem as Mt, getRequestValue as N, mountSort as Nt, parseTraceparent as O, DuplicateMountNameError as Ot, requestStore as P, ContributorCycleError as Pt, KickHandler as Q, SignedCheck as R, CircuitBreaker as Rt, ViewAdapter as S, AssetKeyPair as St, TRACEPARENT_HEADER as T, GroupAssetKeysResult as Tt, LegacyHasher as U, FormatKickErrorOptions as Ut, VerifyOptions as V, CircuitBreakerStats as Vt, PasswordCheck as W, KickError as Wt, ClusterOptions as X, defineHttpContextDecorator as Y, isClusterPrimary as Z, HealthProbe as _, StartupStep as _t, ConfigDescription as a, CRON_WORKER_ENV as at, SpaAdapterOptions as b, bindRoutePolicy as bt, MiddlewareEntry as c, RAW_BODY as ct, ShutdownOptions as d, metricsAdapter as dt, bootstrap as et, describeRoutes as f, CheckContext as ft, HealthModuleConfig as g, defineCheck as gt, HealthController as h, StartupCheckError as ht, ApplicationOptions as i, RESPONSE_CHANNEL as it, RequestStore as j, MountKind as jt, traceContext as k, MissingMountDepError as kt, MountedRouteInfo as l, MetricsOptions as lt, HealthCheckResult as m, StartupCheck as mt, AppStatus as n, HANDLER_CHANNEL as nt, ConfigOrigins as o, CronAdapterOptions as ot, HEALTH_PROBE as p, CheckMessage as pt, hashPassword as q, Application as r, HandlerTraceContext as rt, ManagementOptions as s, KickCronAdapter as st, APPLICATION as t, ERROR_CHANNEL as tt, ServerOptions as u, RequestHistogram as ut, healthModule as v, StartupTimelineSnapshot as vt, viewDirs as w, GroupAssetKeysOptions as wt, resolveClientDir as x, offerRoutePolicy as xt, SpaAdapter as y, RoutePolicyTable as yt, Signer as z, CircuitBreakerOptions as zt };
2069
+ //# sourceMappingURL=application-BZjDmsWb.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-BZjDmsWb.d.mts","names":["_$__0.AdapterFactory","Request","Response","NextFunction","Request","Response","NextFunction","_$_____0.AdapterFactory","_$_____0.AdapterFactory","_$__reply0.Reply","_$__0.ModuleFactory"],"sources":["../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/startup-timeline.ts","../src/http/startup-checks.ts","../src/http/metrics.ts","../src/http/body-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/core/password.ts","../src/core/signing.ts","../src/http/runtimes/express-lazy.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAiBiB;;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;;;;;;;;;;;;;;;;;;;cA0B3B,kCAAkC;WACpC;WACA;EAET,YAAY,aAAa;;;;;;;;;;;;;;;;;;;;;UC5IV;;EAEf;;;;;;EAMA;;;KAIU;;;;;cAMC,gCAAgC;WAClC,MAAM;WACN;EAET,YAAY,MAAM,WAAW;;;;;;;;cAclB,6BAA6B;WAC/B,MAAM;WACN;WACA;EAET,YAAY,MAAM,WAAW,iBAAiB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*
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-Oedvuzit.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const log=createLogger(`waitUntil`),pending=/* @__PURE__ */ new Set;function waitUntil(promise){let requestId=requestStore.getStore()?.requestId,tracked=Promise.resolve(promise).then(()=>{},err=>{log.error({err,requestId},`Background work passed to waitUntil() failed`),reportError(err,{source:`background`,requestId})});pending.add(tracked),tracked.finally(()=>pending.delete(tracked))}async function settleBackgroundWork(){for(;pending.size>0;)await Promise.all(pending)}function pendingBackgroundWork(){return pending.size}function forwardBackgroundWork(platform){platform?.waitUntil?.(settleBackgroundWork())}export{getRequestStore as a,waitUntil as i,pendingBackgroundWork as n,getRequestValue as o,settleBackgroundWork as r,requestStore as s,forwardBackgroundWork as t};
12
- //# sourceMappingURL=background-DSztbyc4.mjs.map
11
+ import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-Ss6-7Si7.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const log=createLogger(`waitUntil`),pending=/* @__PURE__ */ new Set;function waitUntil(promise){let requestId=requestStore.getStore()?.requestId,tracked=Promise.resolve(promise).then(()=>{},err=>{log.error({err,requestId},`Background work passed to waitUntil() failed`),reportError(err,{source:`background`,requestId})});pending.add(tracked),tracked.finally(()=>pending.delete(tracked))}async function settleBackgroundWork(){for(;pending.size>0;)await Promise.all(pending)}function pendingBackgroundWork(){return pending.size}function forwardBackgroundWork(platform){platform?.waitUntil?.(settleBackgroundWork())}export{getRequestStore as a,waitUntil as i,pendingBackgroundWork as n,getRequestValue as o,settleBackgroundWork as r,requestStore as s,forwardBackgroundWork as t};
12
+ //# sourceMappingURL=background-BJjLKrnK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"background-DSztbyc4.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n"],"mappings":";;;;;;;;;;mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C"}
1
+ {"version":3,"file":"background-BJjLKrnK.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n"],"mappings":";;;;;;;;;;mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.6.0
2
+ * @forinda/kickjs v10.7.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger}from"./core/logger.mjs";import{Container}from"./core/container.mjs";import{r as reportError}from"./observers-Oedvuzit.mjs";import{listCronJobs,runCronJob}from"./core/cron.mjs";import{reactive,ref}from"./core/reactivity.mjs";import"./core-Ddq8b9hi.mjs";import{n as Application}from"./application-DwYTFctU.mjs";import{t as defineAdapter}from"./define-adapter-Ce1FDvEo.mjs";import{r as settleBackgroundWork,t as forwardBackgroundWork}from"./background-DSztbyc4.mjs";import{c as reloadEnv}from"./decorate-wrAUzCjW.mjs";import{createRequire}from"node:module";import cluster from"node:cluster";import os from"node:os";const log$2=createLogger(`KickCronAdapter`),peerRequire=createRequire(import.meta.url),CRON_WORKER_ENV=`KICK_CRON_WORKER`;function loadCroner(){try{return peerRequire(`croner`).Cron}catch{return}}function isCronProcess(){return!cluster.isWorker||process.env.KICK_CRON_WORKER===`1`}const KickCronAdapter=defineAdapter({name:`KickCronAdapter`,defaults:{enabled:!0},build(options){let schedules=[],inFlight=/* @__PURE__ */ new Set,jobs=[];return{afterStart({container}){if(options.enabled===!1||!isCronProcess()||(jobs=listCronJobs(container),jobs.length===0))return;let Croner=loadCroner();if(!Croner){log$2.warn(`${jobs.length} @Cron job(s) found but "croner" is not installed, so none will run. Install it: pnpm add croner`);return}let run=(job,trigger)=>{let p=runCronJob(job,container,trigger).catch(()=>{});inFlight.add(p),p.finally(()=>inFlight.delete(p))};for(let job of jobs)schedules.push(new Croner(job.expression,job.timezone?{timezone:job.timezone}:{},()=>run(job,`schedule`))),job.runOnInit&&run(job,`init`);log$2.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map(j=>j.name).join(`, `)}`)},async shutdown(){for(let schedule of schedules.splice(0))schedule.stop();await Promise.all(inFlight)},introspect(){return{protocolVersion:1,name:`KickCronAdapter`,kind:`adapter`,state:{jobs:jobs.map(j=>({name:j.name,expression:j.expression,timezone:j.timezone,description:j.description}))}}}}}}),log$1=createLogger(`Cluster`);function isClusterPrimary(){return cluster.isPrimary}function setupClusterPrimary(opts){let numWorkers=opts.workers??os.cpus().length,gracefulTimeout=opts.gracefulShutdownTimeout??5e3,restartDelay=opts.restartDelay??1e3,maxFailures=opts.maxFailures??5,restartWindow=opts.restartWindow??3e4,startupTimeouts=/* @__PURE__ */ new Map,state=reactive({failureTimestamps:[],shuttingDown:!1}),activeWorkers=ref(0);log$1.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`);let cronWorkerId,forkWorker=()=>{let takesCron=cronWorkerId===void 0,worker=cluster.fork(takesCron?{[CRON_WORKER_ENV]:`1`}:void 0);takesCron&&(cronWorkerId=worker.id)};for(let i=0;i<numWorkers;i++)forkWorker();cluster.on(`fork`,worker=>{let timeout=setTimeout(()=>{log$1.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`),worker.kill()},1e4);startupTimeouts.set(worker.id,timeout),activeWorkers.value++,log$1.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)}),cluster.on(`listening`,(worker,address)=>{let timeout=startupTimeouts.get(worker.id);timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),log$1.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)}),cluster.on(`online`,worker=>{log$1.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)}),cluster.on(`exit`,(worker,code,signal)=>{let timeout=startupTimeouts.get(worker.id);if(timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),activeWorkers.value--,worker.id===cronWorkerId&&(cronWorkerId=void 0),worker.exitedAfterDisconnect){log$1.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`);return}let now=Date.now();for(;state.failureTimestamps.length>0&&now-state.failureTimestamps[0]>=restartWindow;)state.failureTimestamps.shift();state.failureTimestamps.push(now),state.failureTimestamps.length>maxFailures?(log$1.error(`${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`),activeWorkers.value===0&&(log$1.error(`All workers have crashed, exiting primary`),process.exit(1))):(log$1.warn(`Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`),setTimeout(()=>{activeWorkers.value<numWorkers&&forkWorker()},restartDelay))}),cluster.on(`disconnect`,worker=>{log$1.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)});for(let signal of[`SIGTERM`,`SIGINT`])process.on(signal,()=>{state.shuttingDown||(state.shuttingDown=!0,log$1.info(`Primary received ${signal}, disconnecting workers...`),cluster.disconnect(()=>{log$1.info(`All workers disconnected, exiting primary`),process.exit(0)}),setTimeout(()=>{log$1.warn(`Graceful shutdown timed out, forcing exit`),process.exit(1)},gracefulTimeout).unref())})}const ENTRY_CAPTURE=Symbol.for(`kickjs.handler.entryCapture`);function captureEntry(load){let pending;return()=>pending??=(async()=>{let captured,g=globalThis,capture=(first,options)=>{captured??={first,options}};g[ENTRY_CAPTURE]=capture;try{await load()}finally{g[ENTRY_CAPTURE]===capture&&delete g[ENTRY_CAPTURE]}if(!captured)throw Error(`createHandler(): the entry finished loading without calling bootstrap(). Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.`);return captured})().catch(err=>{throw pending=void 0,err})}function createHandler(options){let app,entry=typeof options==`function`?captureEntry(options):async()=>({first:void 0,options}),firstUsed=!1,ready=()=>(app??=(async()=>{let loaded;try{loaded=await entry()}catch(err){throw app=void 0,err}let instance=loaded.first&&!firstUsed?loaded.first:new Application(loaded.options);firstUsed=!0;try{await instance.startWithoutServer()}catch(err){throw app=void 0,await instance.shutdown().catch(()=>{}),err}return instance})(),app);return{ready,async fetch(request,platform){let response=await(await ready()).fetch(request);return forwardBackgroundWork(platform),response},async node(req,res,platform){if((await ready()).handle(req,res),platform?.waitUntil){let sent=new Promise(resolve=>res.once(`close`,()=>resolve()));platform.waitUntil(sent.then(settleBackgroundWork))}},async close(){let current=app;app=void 0,current&&await(await current).shutdown()}}}function tryReloadEnv(){try{reloadEnv()}catch{}}const log=createLogger(`Process`);async function bootstrap(options){let capture=globalThis[ENTRY_CAPTURE];if(typeof capture==`function`){let app=new Application(options);return capture(app,options),app}let isViteDev=!!globalThis.__kickjs_httpServer;if(options.cluster&&isViteDev&&log.warn(`Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).`),options.cluster&&cluster.isPrimary&&!isViteDev)return setupClusterPrimary(typeof options.cluster==`object`?options.cluster:{}),new Application(options);let g=globalThis,processHooks=options.processHooks??`auto`;if(!g.__kickBootstrapped){if(processHooks!==`manual`&&(process.on(`uncaughtException`,err=>{log.error(err,`Uncaught exception`),reportError(err,{source:`uncaught`}),process.exitCode=1}),process.on(`unhandledRejection`,reason=>{log.error(reason,`Unhandled rejection`),reportError(reason,{source:`unhandled-rejection`}),process.exitCode=1})),processHooks===`auto`&&!g.__kickjs_httpServer)for(let signal of[`SIGINT`,`SIGTERM`])process.on(signal,async()=>{log.info(`Received ${signal}, shutting down...`),g.__app&&await g.__app.shutdown(),process.exit(0)});g.__kickBootstrapped=!0}if(g.__app){log.debug(`HMR rebuild triggered`);try{await g.__app.shutdown({closeServer:!1})}catch(err){log.error(err,`HMR teardown of the previous app failed`)}tryReloadEnv(),Container.reset();let freshApp=new Application(options);return g.__app=freshApp,g.__kickjs_container=freshApp.getContainer(),await freshApp.start(),log.debug(`HMR rebuild complete`),freshApp}let app=new Application(options);return g.__app=app,g.__kickjs_container=app.getContainer(),process.env.KICK_TINKER?(await app.registerOnly(),app):(await app.start(),app)}export{KickCronAdapter as a,CRON_WORKER_ENV as i,createHandler as n,isClusterPrimary as r,bootstrap as t};
12
- //# sourceMappingURL=bootstrap-DdTHtS8P.mjs.map
11
+ import{createLogger}from"./core/logger.mjs";import{Container}from"./core/container.mjs";import{r as reportError}from"./observers-Ss6-7Si7.mjs";import{listCronJobs,runCronJob}from"./core/cron.mjs";import{reactive,ref}from"./core/reactivity.mjs";import"./core-DlrlhjF4.mjs";import{n as Application}from"./application-BSzwuTQ6.mjs";import{t as defineAdapter}from"./define-adapter-CF-DJRq9.mjs";import{r as settleBackgroundWork,t as forwardBackgroundWork}from"./background-BJjLKrnK.mjs";import{c as reloadEnv}from"./decorate-BHhpOfEF.mjs";import{createRequire}from"node:module";import cluster from"node:cluster";import os from"node:os";const log$2=createLogger(`KickCronAdapter`),peerRequire=createRequire(import.meta.url),CRON_WORKER_ENV=`KICK_CRON_WORKER`;function loadCroner(){try{return peerRequire(`croner`).Cron}catch{return}}function isCronProcess(){return!cluster.isWorker||process.env.KICK_CRON_WORKER===`1`}const KickCronAdapter=defineAdapter({name:`KickCronAdapter`,defaults:{enabled:!0},build(options){let schedules=[],inFlight=/* @__PURE__ */ new Set,jobs=[];return{afterStart({container}){if(options.enabled===!1||!isCronProcess()||(jobs=listCronJobs(container),jobs.length===0))return;let Croner=loadCroner();if(!Croner){log$2.warn(`${jobs.length} @Cron job(s) found but "croner" is not installed, so none will run. Install it: pnpm add croner`);return}let run=(job,trigger)=>{let p=runCronJob(job,container,trigger).catch(()=>{});inFlight.add(p),p.finally(()=>inFlight.delete(p))};for(let job of jobs)schedules.push(new Croner(job.expression,job.timezone?{timezone:job.timezone}:{},()=>run(job,`schedule`))),job.runOnInit&&run(job,`init`);log$2.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map(j=>j.name).join(`, `)}`)},async shutdown(){for(let schedule of schedules.splice(0))schedule.stop();await Promise.all(inFlight)},introspect(){return{protocolVersion:1,name:`KickCronAdapter`,kind:`adapter`,state:{jobs:jobs.map(j=>({name:j.name,expression:j.expression,timezone:j.timezone,description:j.description}))}}}}}}),log$1=createLogger(`Cluster`);function isClusterPrimary(){return cluster.isPrimary}function setupClusterPrimary(opts){let numWorkers=opts.workers??os.cpus().length,gracefulTimeout=opts.gracefulShutdownTimeout??5e3,restartDelay=opts.restartDelay??1e3,maxFailures=opts.maxFailures??5,restartWindow=opts.restartWindow??3e4,startupTimeouts=/* @__PURE__ */ new Map,state=reactive({failureTimestamps:[],shuttingDown:!1}),activeWorkers=ref(0);log$1.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`);let cronWorkerId,forkWorker=()=>{let takesCron=cronWorkerId===void 0,worker=cluster.fork(takesCron?{[CRON_WORKER_ENV]:`1`}:void 0);takesCron&&(cronWorkerId=worker.id)};for(let i=0;i<numWorkers;i++)forkWorker();cluster.on(`fork`,worker=>{let timeout=setTimeout(()=>{log$1.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`),worker.kill()},1e4);startupTimeouts.set(worker.id,timeout),activeWorkers.value++,log$1.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)}),cluster.on(`listening`,(worker,address)=>{let timeout=startupTimeouts.get(worker.id);timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),log$1.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)}),cluster.on(`online`,worker=>{log$1.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)}),cluster.on(`exit`,(worker,code,signal)=>{let timeout=startupTimeouts.get(worker.id);if(timeout&&(clearTimeout(timeout),startupTimeouts.delete(worker.id)),activeWorkers.value--,worker.id===cronWorkerId&&(cronWorkerId=void 0),worker.exitedAfterDisconnect){log$1.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`);return}let now=Date.now();for(;state.failureTimestamps.length>0&&now-state.failureTimestamps[0]>=restartWindow;)state.failureTimestamps.shift();state.failureTimestamps.push(now),state.failureTimestamps.length>maxFailures?(log$1.error(`${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`),activeWorkers.value===0&&(log$1.error(`All workers have crashed, exiting primary`),process.exit(1))):(log$1.warn(`Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`),setTimeout(()=>{activeWorkers.value<numWorkers&&forkWorker()},restartDelay))}),cluster.on(`disconnect`,worker=>{log$1.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)});for(let signal of[`SIGTERM`,`SIGINT`])process.on(signal,()=>{state.shuttingDown||(state.shuttingDown=!0,log$1.info(`Primary received ${signal}, disconnecting workers...`),cluster.disconnect(()=>{log$1.info(`All workers disconnected, exiting primary`),process.exit(0)}),setTimeout(()=>{log$1.warn(`Graceful shutdown timed out, forcing exit`),process.exit(1)},gracefulTimeout).unref())})}const ENTRY_CAPTURE=Symbol.for(`kickjs.handler.entryCapture`);function captureEntry(load){let pending;return()=>pending??=(async()=>{let captured,g=globalThis,capture=(first,options)=>{captured??={first,options}};g[ENTRY_CAPTURE]=capture;try{await load()}finally{g[ENTRY_CAPTURE]===capture&&delete g[ENTRY_CAPTURE]}if(!captured)throw Error(`createHandler(): the entry finished loading without calling bootstrap(). Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.`);return captured})().catch(err=>{throw pending=void 0,err})}function createHandler(options){let app,entry=typeof options==`function`?captureEntry(options):async()=>({first:void 0,options}),firstUsed=!1,ready=()=>(app??=(async()=>{let loaded;try{loaded=await entry()}catch(err){throw app=void 0,err}let instance=loaded.first&&!firstUsed?loaded.first:new Application(loaded.options);firstUsed=!0;try{await instance.startWithoutServer()}catch(err){throw app=void 0,await instance.shutdown().catch(()=>{}),err}return instance})(),app);return{ready,async fetch(request,platform){let response=await(await ready()).fetch(request);return forwardBackgroundWork(platform),response},async node(req,res,platform){if((await ready()).handle(req,res),platform?.waitUntil){let sent=new Promise(resolve=>res.once(`close`,()=>resolve()));platform.waitUntil(sent.then(settleBackgroundWork))}},async close(){let current=app;app=void 0,current&&await(await current).shutdown()}}}function tryReloadEnv(){try{reloadEnv()}catch{}}const log=createLogger(`Process`);async function bootstrap(options){let capture=globalThis[ENTRY_CAPTURE];if(typeof capture==`function`){let app=new Application(options);return capture(app,options),app}let isViteDev=!!globalThis.__kickjs_httpServer;if(options.cluster&&isViteDev&&log.warn(`Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).`),options.cluster&&cluster.isPrimary&&!isViteDev)return setupClusterPrimary(typeof options.cluster==`object`?options.cluster:{}),new Application(options);let g=globalThis,processHooks=options.processHooks??`auto`;if(!g.__kickBootstrapped){if(processHooks!==`manual`&&(process.on(`uncaughtException`,err=>{log.error(err,`Uncaught exception`),reportError(err,{source:`uncaught`}),process.exitCode=1}),process.on(`unhandledRejection`,reason=>{log.error(reason,`Unhandled rejection`),reportError(reason,{source:`unhandled-rejection`}),process.exitCode=1})),processHooks===`auto`&&!g.__kickjs_httpServer)for(let signal of[`SIGINT`,`SIGTERM`])process.on(signal,async()=>{log.info(`Received ${signal}, shutting down...`),g.__app&&await g.__app.shutdown(),process.exit(0)});g.__kickBootstrapped=!0}if(g.__app){log.debug(`HMR rebuild triggered`);try{await g.__app.shutdown({closeServer:!1})}catch(err){log.error(err,`HMR teardown of the previous app failed`)}tryReloadEnv(),Container.reset();let freshApp=new Application(options);return g.__app=freshApp,g.__kickjs_container=freshApp.getContainer(),await freshApp.start(),log.debug(`HMR rebuild complete`),freshApp}let app=new Application(options);return g.__app=app,g.__kickjs_container=app.getContainer(),process.env.KICK_TINKER?(await app.registerOnly(),app):(await app.start(),app)}export{KickCronAdapter as a,CRON_WORKER_ENV as i,createHandler as n,isClusterPrimary as r,bootstrap as t};
12
+ //# sourceMappingURL=bootstrap-Dxax6Mcp.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap-DdTHtS8P.mjs","names":["log","log","\"KICK_CRON_WORKER\""],"sources":["../src/http/cron-adapter.ts","../src/http/cluster.ts","../src/http/handler.ts","../src/http/bootstrap.ts"],"sourcesContent":["/**\n * `KickCronAdapter()` — runs `@Cron` jobs on the Node server.\n *\n * Named with the `Kick` prefix (adapter name and logger too) so it never\n * collides with an app's own `CronAdapter` — which is also why it is opt-in.\n *\n * Opt-in: `@Cron` only records metadata, and apps that schedule jobs with\n * their own adapter keep doing so — adding this one to such an app would run\n * every job twice. Register it once:\n *\n * ```ts\n * bootstrap({ modules, adapters: [KickCronAdapter()] })\n * ```\n *\n * Timing comes from the optional peer `croner` (`pnpm add croner`), loaded\n * only when there is a job to schedule. Each tick resolves the job's class\n * from the container (the same singletons a request gets) and calls\n * `runCronJob`, which applies `enabled` / `overlap` and reports failures to\n * the error observers.\n *\n * Several processes: in `bootstrap({ cluster })`, only the worker the primary\n * marks with `KICK_CRON_WORKER=1` schedules, so a job runs once per cluster.\n * Several separate instances (replicas behind a load balancer) each schedule\n * every job — turn it off on all but one (`KickCronAdapter({ enabled: false })`),\n * or have the job take a lock.\n *\n * @module @forinda/kickjs/http/cron-adapter\n */\nimport cluster from 'node:cluster'\nimport { createRequire } from 'node:module'\nimport { defineAdapter } from '../core/define-adapter'\nimport { createLogger } from '../core/logger'\nimport { listCronJobs, runCronJob, type CronJob } from '../core/cron'\nimport type { Container } from '../core/container'\n\nconst log = createLogger('KickCronAdapter')\nconst peerRequire = createRequire(import.meta.url)\n\n/** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */\nexport const CRON_WORKER_ENV = 'KICK_CRON_WORKER'\n\nexport interface CronAdapterOptions {\n /** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */\n enabled?: boolean\n}\n\ninterface Schedule {\n stop(): void\n}\n\ntype CronerCtor = new (pattern: string, options: { timezone?: string }, fn: () => void) => Schedule\n\nfunction loadCroner(): CronerCtor | undefined {\n try {\n return (peerRequire('croner') as { Cron: CronerCtor }).Cron\n } catch {\n return undefined\n }\n}\n\n/** Whether this process should schedule jobs — one worker per cluster. */\nfunction isCronProcess(): boolean {\n return !cluster.isWorker || process.env[CRON_WORKER_ENV] === '1'\n}\n\nexport const KickCronAdapter = defineAdapter<CronAdapterOptions>({\n name: 'KickCronAdapter',\n defaults: { enabled: true },\n build(options) {\n const schedules: Schedule[] = []\n const inFlight = new Set<Promise<unknown>>()\n let jobs: CronJob[] = []\n\n return {\n afterStart({ container }) {\n if (options.enabled === false || !isCronProcess()) return\n jobs = listCronJobs(container)\n if (jobs.length === 0) return\n\n const Croner = loadCroner()\n if (!Croner) {\n log.warn(\n `${jobs.length} @Cron job(s) found but \"croner\" is not installed, so none will run. ` +\n 'Install it: pnpm add croner',\n )\n return\n }\n\n const run = (job: CronJob, trigger: 'schedule' | 'init') => {\n // Failures are already logged and reported by runCronJob.\n const p = runCronJob(job, container as Container, trigger).catch(() => {})\n inFlight.add(p)\n void p.finally(() => inFlight.delete(p))\n }\n\n for (const job of jobs) {\n schedules.push(\n new Croner(\n job.expression,\n // No croner `name`: croner keeps names in a process-wide registry\n // and throws on a duplicate.\n job.timezone ? { timezone: job.timezone } : {},\n () => run(job, 'schedule'),\n ),\n )\n if (job.runOnInit) run(job, 'init')\n }\n log.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map((j) => j.name).join(', ')}`)\n },\n\n /**\n * Stops the schedules, then waits for running jobs so they don't lose\n * their dependencies mid-run. Also runs on every HMR reload, so a reload\n * never leaves a second copy ticking.\n */\n async shutdown() {\n for (const schedule of schedules.splice(0)) schedule.stop()\n await Promise.all(inFlight)\n },\n\n introspect() {\n return {\n protocolVersion: 1,\n name: 'KickCronAdapter',\n kind: 'adapter',\n state: {\n jobs: jobs.map((j) => ({\n name: j.name,\n expression: j.expression,\n timezone: j.timezone,\n description: j.description,\n })),\n },\n } as never\n },\n }\n },\n})\n","import cluster from 'node:cluster'\nimport { CRON_WORKER_ENV } from './cron-adapter'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Exactly one worker runs `KickCronAdapter` jobs, so a job fires once per\n // cluster rather than once per worker. The primary marks it with\n // KICK_CRON_WORKER=1; when it dies, the next fork inherits the role.\n let cronWorkerId: number | undefined\n const forkWorker = (): void => {\n const takesCron = cronWorkerId === undefined\n const worker = cluster.fork(takesCron ? { [CRON_WORKER_ENV]: '1' } : undefined)\n if (takesCron) cronWorkerId = worker.id\n }\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n forkWorker()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n if (worker.id === cronWorkerId) cronWorkerId = undefined\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n forkWorker()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","/**\n * The app as a request handler, with no listening server of its own — for\n * platforms that hand you requests instead of a port: Netlify Functions,\n * Vercel Functions, and any other serverless or embedding host.\n *\n * @module @forinda/kickjs/http/handler\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { Application, type ApplicationOptions } from './application'\nimport { forwardBackgroundWork, settleBackgroundWork, type PlatformContext } from './background'\n\n/** A KickJS app exposed as request handlers. See {@link createHandler}. */\nexport interface KickHandler {\n /**\n * Web-standard handler: `fetch(Request) → Response`. Netlify Functions,\n * Vercel's fetch export, and anything else that speaks `Request`.\n *\n * Pass the platform context (Netlify's `context`, `{ waitUntil }` from\n * `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after\n * the response instead of being frozen with the instance.\n */\n fetch(request: Request, platform?: PlatformContext): Promise<Response>\n /** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */\n node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>\n /** Set the app up now instead of on the first request (warm-up). */\n ready(): Promise<Application>\n /** Shut adapters down and stop the internal forwarding server, if one started. */\n close(): Promise<void>\n}\n\n/**\n * Set on `globalThis` while `createHandler(() => import('./index'))` loads the\n * app's entry: `bootstrap()` hands its app here instead of starting it.\n * @internal\n */\nexport const ENTRY_CAPTURE = Symbol.for('kickjs.handler.entryCapture')\n\n/** What `bootstrap()` hands to a loading handler. @internal */\nexport type EntryCapture = (app: Application, options: ApplicationOptions) => void\n\n/**\n * Load the app's own entry and keep the app its `bootstrap()` call builds.\n * Retries after a failed setup reuse the captured options.\n */\nfunction captureEntry(\n load: () => Promise<unknown>,\n): () => Promise<{ first: Application; options: ApplicationOptions }> {\n let pending: Promise<{ first: Application; options: ApplicationOptions }> | undefined\n return () =>\n (pending ??= (async () => {\n let captured: { first: Application; options: ApplicationOptions } | undefined\n const g = globalThis as Record<symbol, unknown>\n const capture: EntryCapture = (first, options) => {\n captured ??= { first, options }\n }\n g[ENTRY_CAPTURE] = capture\n try {\n await load()\n } finally {\n if (g[ENTRY_CAPTURE] === capture) delete g[ENTRY_CAPTURE]\n }\n if (!captured) {\n throw new Error(\n 'createHandler(): the entry finished loading without calling bootstrap(). ' +\n \"Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.\",\n )\n }\n return captured\n })().catch((err) => {\n pending = undefined\n throw err\n }))\n}\n\n/**\n * Build a KickJS app as request handlers instead of a listening server.\n *\n * Takes the same options as `bootstrap()`, or a function that imports the\n * app's entry — the file that calls `bootstrap()`. With the entry, the app\n * is built from that one `bootstrap({ ... })` call, so the server and the\n * function never drift apart:\n *\n * ```ts\n * // src/serverless.ts\n * export const handler = createHandler(() => import('./index'))\n * ```\n *\n * While the entry loads, its `bootstrap()` call builds the app without\n * starting it — no port, no process signal handlers, no cluster. The app is set up once per process\n * (per function instance), lazily on the first request, and reused after that.\n * Nothing listens on a port, `afterStart` does not run, and no process signal\n * handlers are registered — the platform owns the process.\n *\n * `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).\n * Runtimes built on Node request/response objects — Express, the default —\n * are served through a server bound to `127.0.0.1` on a random port inside the\n * same process, started on first use: the `Request` is forwarded to it and its\n * response returned. Request bodies are buffered on that path; response bodies\n * stream. Adapters that rewrite the `res` prototype (Express does) make a\n * direct Request→`res` bridge unreliable, which is why this forwards instead.\n *\n * One handler per process: the DI container is process-wide.\n *\n * @example\n * ```ts\n * // server/src/serverless.ts\n * import 'reflect-metadata'\n * import './config'\n * import { createHandler } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const handler = createHandler({ modules })\n *\n * // netlify/functions/api.mjs\n * export default (request, context) => handler.fetch(request, context)\n * export const config = { path: '/api/*' }\n * ```\n */\nexport function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler {\n let app: Promise<Application> | undefined\n const entry =\n typeof options === 'function'\n ? captureEntry(options)\n : async () => ({ first: undefined, options })\n // The app the entry's bootstrap() built is used once; a retry builds anew.\n let firstUsed = false\n\n const ready = (): Promise<Application> => {\n app ??= (async () => {\n let loaded: Awaited<ReturnType<typeof entry>>\n try {\n loaded = await entry()\n } catch (err) {\n // The entry failed to load: try again on the next request.\n app = undefined\n throw err\n }\n const instance = loaded.first && !firstUsed ? loaded.first : new Application(loaded.options)\n firstUsed = true\n try {\n await instance.startWithoutServer()\n } catch (err) {\n // A failed setup (a database that was briefly down, say) is retried on\n // the next request. Shut this attempt down first so its adapters don't\n // stay live next to the retry's.\n app = undefined\n await instance.shutdown().catch(() => {})\n throw err\n }\n return instance\n })()\n return app\n }\n\n return {\n ready,\n\n async fetch(request, platform) {\n const response = await (await ready()).fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n\n async node(req, res, platform) {\n const instance = await ready()\n instance.handle(req, res)\n if (platform?.waitUntil) {\n // The response is written asynchronously: start settling only once it\n // has gone out, so work the handler registered along the way is included.\n const sent = new Promise<void>((resolve) => res.once('close', () => resolve()))\n platform.waitUntil(sent.then(settleBackgroundWork))\n }\n },\n\n async close() {\n const current = app\n app = undefined\n if (current) await (await current).shutdown()\n },\n }\n}\n","import cluster from 'node:cluster'\nimport { reportError } from '../core/observers'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\nimport { ENTRY_CAPTURE, type EntryCapture } from './handler'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Loaded by createHandler(() => import('./index')) ────────────────\n // The serverless entry reuses this call's options: build the app and hand\n // it over without listening, forking or registering process hooks.\n const capture = (globalThis as Record<symbol, unknown>)[ENTRY_CAPTURE]\n if (typeof capture === 'function') {\n const app = new Application(options)\n ;(capture as EntryCapture)(app, options)\n return app\n }\n\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers + signal hooks ─────────────────────────────\n // `processHooks` controls whether KickJS registers its own\n // process-level handlers. Defaults to `'auto'` — register everything.\n // Adopters that bring their own observability stack (OpenTelemetry SDK,\n // Sentry, custom shutdown choreographer) often register their own\n // SIGINT/SIGTERM handlers and need to opt out of ours so the two don't\n // race to call `process.exit(0)`. Three modes:\n // - 'auto' (default): register uncaughtException/unhandledRejection\n // loggers + SIGINT/SIGTERM → `app.shutdown()` → `process.exit(0)`.\n // - 'errors-only': register the error loggers; skip signal handlers.\n // Use this when you have your own shutdown choreographer that calls\n // `app.shutdown()` itself.\n // - 'manual': skip everything. Adopter is responsible for both error\n // logging and signal-driven shutdown.\n const processHooks = options.processHooks ?? 'auto'\n\n if (!g.__kickBootstrapped) {\n if (processHooks !== 'manual') {\n // A listener here replaces Node's own handling, which exits with code\n // 1. Keep the failure in the exit code: a boot that throws — a top-level\n // `await bootstrap()` rejecting — must not end the process with 0, or a\n // deploy reads the crash as success.\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n reportError(err, { source: 'uncaught' })\n process.exitCode = 1\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n reportError(reason, { source: 'unhandled-rejection' })\n process.exitCode = 1\n })\n }\n\n if (processHooks === 'auto' && !g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n\n // Tear the PREVIOUS app down before replacing it. Without this the old\n // Application was dropped on the floor still running: its adapters kept\n // their sockets and consumers open, so every save added another set.\n //\n // Observed in the wild as one process holding several consumer-group\n // members — on a single-partition topic only one can hold the assignment,\n // and it was a leaked consumer no longer wired to anything, so jobs\n // stopped being processed. A second socket.io server on the same HTTP\n // server crashed `handleUpgrade()` the same way.\n //\n // `closeServer: false` is load-bearing: the dev HTTP server is shared\n // across rebuilds, so a full shutdown would close the listening socket and\n // kill HMR on the first save.\n //\n // Failures are logged, not thrown — one broken adapter must not leave the\n // dev server wedged with no app at all.\n try {\n await g.__app.shutdown({ closeServer: false })\n } catch (err) {\n log.error(err as Error, 'HMR teardown of the previous app failed')\n }\n\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;;;;;;wnBAmCA,MAAMA,MAAM,aAAa,iBAAiB,EACpC,YAAc,cAAc,YAAY,GAAG,EAGpC,gBAAkB,mBAa/B,SAAS,YAAqC,CAC5C,GAAI,CACF,OAAQ,YAAY,QAAQ,CAAC,CAA0B,IACzD,MAAQ,CACN,MACF,CACF,CAGA,SAAS,eAAyB,CAChC,MAAO,CAAC,QAAQ,UAAY,QAAQ,IAAAE,mBAAyB,GAC/D,CAEA,MAAa,gBAAkB,cAAkC,CAC/D,KAAM,kBACN,SAAU,CAAE,QAAS,EAAK,EAC1B,MAAM,QAAS,CACb,IAAM,UAAwB,CAAC,EACzB,yBAAW,IAAI,IACjB,KAAkB,CAAC,EAEvB,MAAO,CACL,WAAW,CAAE,WAAa,CAGxB,GAFI,QAAQ,UAAY,IAAS,CAAC,cAAc,IAChD,KAAO,aAAa,SAAS,EACzB,KAAK,SAAW,GAAG,OAEvB,IAAM,OAAS,WAAW,EAC1B,GAAI,CAAC,OAAQ,CACX,MAAI,KACF,GAAG,KAAK,O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U,MAAM,EAEhB,IAAM,SAAW,IAAI,YAAY,OAAO,EAMxC,MALA,GAAE,MAAQ,SACV,EAAE,mBAAqB,SAAS,aAAa,EAE7C,MAAM,SAAS,MAAM,EACrB,IAAI,MAAM,sBAAsB,EACzB,QACT,CAGA,IAAM,IAAM,IAAI,YAAY,OAAO,EAWnC,MAVA,GAAE,MAAQ,IACV,EAAE,mBAAqB,IAAI,aAAa,EAEpC,QAAQ,IAAI,aACd,MAAM,IAAI,aAAa,EAChB,MAGT,MAAM,IAAI,MAAM,EAET,IACT"}
1
+ {"version":3,"file":"bootstrap-Dxax6Mcp.mjs","names":["log","log","\"KICK_CRON_WORKER\""],"sources":["../src/http/cron-adapter.ts","../src/http/cluster.ts","../src/http/handler.ts","../src/http/bootstrap.ts"],"sourcesContent":["/**\n * `KickCronAdapter()` — runs `@Cron` jobs on the Node server.\n *\n * Named with the `Kick` prefix (adapter name and logger too) so it never\n * collides with an app's own `CronAdapter` — which is also why it is opt-in.\n *\n * Opt-in: `@Cron` only records metadata, and apps that schedule jobs with\n * their own adapter keep doing so — adding this one to such an app would run\n * every job twice. Register it once:\n *\n * ```ts\n * bootstrap({ modules, adapters: [KickCronAdapter()] })\n * ```\n *\n * Timing comes from the optional peer `croner` (`pnpm add croner`), loaded\n * only when there is a job to schedule. Each tick resolves the job's class\n * from the container (the same singletons a request gets) and calls\n * `runCronJob`, which applies `enabled` / `overlap` and reports failures to\n * the error observers.\n *\n * Several processes: in `bootstrap({ cluster })`, only the worker the primary\n * marks with `KICK_CRON_WORKER=1` schedules, so a job runs once per cluster.\n * Several separate instances (replicas behind a load balancer) each schedule\n * every job — turn it off on all but one (`KickCronAdapter({ enabled: false })`),\n * or have the job take a lock.\n *\n * @module @forinda/kickjs/http/cron-adapter\n */\nimport cluster from 'node:cluster'\nimport { createRequire } from 'node:module'\nimport { defineAdapter } from '../core/define-adapter'\nimport { createLogger } from '../core/logger'\nimport { listCronJobs, runCronJob, type CronJob } from '../core/cron'\nimport type { Container } from '../core/container'\n\nconst log = createLogger('KickCronAdapter')\nconst peerRequire = createRequire(import.meta.url)\n\n/** Set by the cluster primary on the one worker that runs `KickCronAdapter` jobs. */\nexport const CRON_WORKER_ENV = 'KICK_CRON_WORKER'\n\nexport interface CronAdapterOptions {\n /** Off for processes that should run no jobs (replicas, one-off scripts). Default `true`. */\n enabled?: boolean\n}\n\ninterface Schedule {\n stop(): void\n}\n\ntype CronerCtor = new (pattern: string, options: { timezone?: string }, fn: () => void) => Schedule\n\nfunction loadCroner(): CronerCtor | undefined {\n try {\n return (peerRequire('croner') as { Cron: CronerCtor }).Cron\n } catch {\n return undefined\n }\n}\n\n/** Whether this process should schedule jobs — one worker per cluster. */\nfunction isCronProcess(): boolean {\n return !cluster.isWorker || process.env[CRON_WORKER_ENV] === '1'\n}\n\nexport const KickCronAdapter = defineAdapter<CronAdapterOptions>({\n name: 'KickCronAdapter',\n defaults: { enabled: true },\n build(options) {\n const schedules: Schedule[] = []\n const inFlight = new Set<Promise<unknown>>()\n let jobs: CronJob[] = []\n\n return {\n afterStart({ container }) {\n if (options.enabled === false || !isCronProcess()) return\n jobs = listCronJobs(container)\n if (jobs.length === 0) return\n\n const Croner = loadCroner()\n if (!Croner) {\n log.warn(\n `${jobs.length} @Cron job(s) found but \"croner\" is not installed, so none will run. ` +\n 'Install it: pnpm add croner',\n )\n return\n }\n\n const run = (job: CronJob, trigger: 'schedule' | 'init') => {\n // Failures are already logged and reported by runCronJob.\n const p = runCronJob(job, container as Container, trigger).catch(() => {})\n inFlight.add(p)\n void p.finally(() => inFlight.delete(p))\n }\n\n for (const job of jobs) {\n schedules.push(\n new Croner(\n job.expression,\n // No croner `name`: croner keeps names in a process-wide registry\n // and throws on a duplicate.\n job.timezone ? { timezone: job.timezone } : {},\n () => run(job, 'schedule'),\n ),\n )\n if (job.runOnInit) run(job, 'init')\n }\n log.info(`Scheduled ${jobs.length} @Cron job(s): ${jobs.map((j) => j.name).join(', ')}`)\n },\n\n /**\n * Stops the schedules, then waits for running jobs so they don't lose\n * their dependencies mid-run. Also runs on every HMR reload, so a reload\n * never leaves a second copy ticking.\n */\n async shutdown() {\n for (const schedule of schedules.splice(0)) schedule.stop()\n await Promise.all(inFlight)\n },\n\n introspect() {\n return {\n protocolVersion: 1,\n name: 'KickCronAdapter',\n kind: 'adapter',\n state: {\n jobs: jobs.map((j) => ({\n name: j.name,\n expression: j.expression,\n timezone: j.timezone,\n description: j.description,\n })),\n },\n } as never\n },\n }\n },\n})\n","import cluster from 'node:cluster'\nimport { CRON_WORKER_ENV } from './cron-adapter'\nimport os from 'node:os'\nimport { createLogger } from '../core'\nimport { reactive, ref } from '../core/reactivity'\n\nconst log = createLogger('Cluster')\n\nexport interface ClusterOptions {\n /** Number of worker processes (default: os.cpus().length) */\n workers?: number\n /** Delay before forcefully killing a worker during shutdown (ms), default: 5000 */\n gracefulShutdownTimeout?: number\n /** Delay between worker restarts (ms), default: 1000 */\n restartDelay?: number\n /** Max failures in restartWindow before refusing to restart, default: 5 */\n maxFailures?: number\n /** Time window for counting failures (ms), default: 30000 */\n restartWindow?: number\n}\n\n/** Returns true if the current process is the cluster primary */\nexport function isClusterPrimary(): boolean {\n return cluster.isPrimary\n}\n\n/**\n * Fork worker processes and manage the cluster lifecycle.\n *\n * The primary process forks `workers` child processes. Each worker\n * shares the same port via Node's built-in `cluster` module (OS\n * round-robin load balancing).\n *\n * Features:\n * - Graceful shutdown with timeout fallback to forceful kill\n * - Auto-restart dead workers (respects voluntary disconnects)\n * - Startup timeout detection (stuck workers)\n * - Crash loop prevention (backoff on rapid failures)\n * - Comprehensive lifecycle logging\n */\nexport function setupClusterPrimary(opts: ClusterOptions): void {\n const numWorkers = opts.workers ?? os.cpus().length\n const gracefulTimeout = opts.gracefulShutdownTimeout ?? 5000\n const restartDelay = opts.restartDelay ?? 1000\n const maxFailures = opts.maxFailures ?? 5\n const restartWindow = opts.restartWindow ?? 30000\n\n const startupTimeouts = new Map<number, NodeJS.Timeout>()\n const state = reactive({\n failureTimestamps: [] as number[],\n shuttingDown: false,\n })\n const activeWorkers = ref(0)\n\n log.info(`Primary ${process.pid} starting ${numWorkers} worker(s)`)\n\n // Exactly one worker runs `KickCronAdapter` jobs, so a job fires once per\n // cluster rather than once per worker. The primary marks it with\n // KICK_CRON_WORKER=1; when it dies, the next fork inherits the role.\n let cronWorkerId: number | undefined\n const forkWorker = (): void => {\n const takesCron = cronWorkerId === undefined\n const worker = cluster.fork(takesCron ? { [CRON_WORKER_ENV]: '1' } : undefined)\n if (takesCron) cronWorkerId = worker.id\n }\n\n // Initial fork\n for (let i = 0; i < numWorkers; i++) {\n forkWorker()\n }\n\n // Detect stuck workers (no 'listening' event within timeout)\n cluster.on('fork', (worker) => {\n const timeout = setTimeout(() => {\n log.error(`Worker ${worker.process.pid} did not respond within 10s, killing...`)\n worker.kill()\n }, 10000)\n\n startupTimeouts.set(worker.id, timeout)\n activeWorkers.value++\n log.debug(`Worker ${worker.process.pid} forked (id=${worker.id})`)\n })\n\n // Clear startup timeout when worker is ready\n cluster.on('listening', (worker, address) => {\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n log.info(`Worker ${worker.process.pid} listening on ${address.address}:${address.port}`)\n })\n\n // Log when worker comes online\n cluster.on('online', (worker) => {\n log.debug(`Worker ${worker.process.pid} online (id=${worker.id})`)\n })\n\n // Auto-restart dead workers (unless intentionally disconnected)\n cluster.on('exit', (worker, code, signal) => {\n // Clear startup timeout if still pending\n const timeout = startupTimeouts.get(worker.id)\n if (timeout) {\n clearTimeout(timeout)\n startupTimeouts.delete(worker.id)\n }\n\n // Don't restart if worker was intentionally disconnected\n activeWorkers.value--\n if (worker.id === cronWorkerId) cronWorkerId = undefined\n\n if (worker.exitedAfterDisconnect) {\n log.info(`Worker ${worker.process.pid} exited gracefully (id=${worker.id})`)\n return\n }\n\n // Track crash history globally (worker IDs change on restart)\n const now = Date.now()\n // Remove timestamps outside the window, then add the current failure\n while (\n state.failureTimestamps.length > 0 &&\n now - state.failureTimestamps[0] >= restartWindow\n ) {\n state.failureTimestamps.shift()\n }\n state.failureTimestamps.push(now)\n\n // Prevent restart loops\n if (state.failureTimestamps.length > maxFailures) {\n log.error(\n `${state.failureTimestamps.length} worker failures in ${restartWindow}ms, giving up`,\n )\n // Optionally exit the primary if too many workers are crashing\n if (activeWorkers.value === 0) {\n log.error('All workers have crashed, exiting primary')\n process.exit(1)\n }\n return\n }\n\n log.warn(\n `Worker ${worker.process.pid} died (code=${code}, signal=${signal}), restarting in ${restartDelay}ms... (failures: ${state.failureTimestamps.length}/${maxFailures})`,\n )\n\n setTimeout(() => {\n // Only restart if we still need more workers\n if (activeWorkers.value < numWorkers) {\n forkWorker()\n }\n }, restartDelay)\n })\n\n // Log when worker disconnects (can happen before exit)\n cluster.on('disconnect', (worker) => {\n log.debug(`Worker ${worker.process.pid} disconnected (id=${worker.id})`)\n })\n\n // Forward shutdown signals to workers (disconnect so exitedAfterDisconnect is set)\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => {\n if (state.shuttingDown) return\n state.shuttingDown = true\n log.info(`Primary received ${signal}, disconnecting workers...`)\n cluster.disconnect(() => {\n log.info('All workers disconnected, exiting primary')\n process.exit(0)\n })\n // Force kill after graceful timeout\n setTimeout(() => {\n log.warn('Graceful shutdown timed out, forcing exit')\n process.exit(1)\n }, gracefulTimeout).unref()\n })\n }\n}\n","/**\n * The app as a request handler, with no listening server of its own — for\n * platforms that hand you requests instead of a port: Netlify Functions,\n * Vercel Functions, and any other serverless or embedding host.\n *\n * @module @forinda/kickjs/http/handler\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { Application, type ApplicationOptions } from './application'\nimport { forwardBackgroundWork, settleBackgroundWork, type PlatformContext } from './background'\n\n/** A KickJS app exposed as request handlers. See {@link createHandler}. */\nexport interface KickHandler {\n /**\n * Web-standard handler: `fetch(Request) → Response`. Netlify Functions,\n * Vercel's fetch export, and anything else that speaks `Request`.\n *\n * Pass the platform context (Netlify's `context`, `{ waitUntil }` from\n * `@vercel/functions`) so work handed to `ctx.waitUntil()` finishes after\n * the response instead of being frozen with the instance.\n */\n fetch(request: Request, platform?: PlatformContext): Promise<Response>\n /** Node handler: `(req, res)`. Vercel Node functions, `http.createServer`. */\n node(req: IncomingMessage, res: ServerResponse, platform?: PlatformContext): Promise<void>\n /** Set the app up now instead of on the first request (warm-up). */\n ready(): Promise<Application>\n /** Shut adapters down and stop the internal forwarding server, if one started. */\n close(): Promise<void>\n}\n\n/**\n * Set on `globalThis` while `createHandler(() => import('./index'))` loads the\n * app's entry: `bootstrap()` hands its app here instead of starting it.\n * @internal\n */\nexport const ENTRY_CAPTURE = Symbol.for('kickjs.handler.entryCapture')\n\n/** What `bootstrap()` hands to a loading handler. @internal */\nexport type EntryCapture = (app: Application, options: ApplicationOptions) => void\n\n/**\n * Load the app's own entry and keep the app its `bootstrap()` call builds.\n * Retries after a failed setup reuse the captured options.\n */\nfunction captureEntry(\n load: () => Promise<unknown>,\n): () => Promise<{ first: Application; options: ApplicationOptions }> {\n let pending: Promise<{ first: Application; options: ApplicationOptions }> | undefined\n return () =>\n (pending ??= (async () => {\n let captured: { first: Application; options: ApplicationOptions } | undefined\n const g = globalThis as Record<symbol, unknown>\n const capture: EntryCapture = (first, options) => {\n captured ??= { first, options }\n }\n g[ENTRY_CAPTURE] = capture\n try {\n await load()\n } finally {\n if (g[ENTRY_CAPTURE] === capture) delete g[ENTRY_CAPTURE]\n }\n if (!captured) {\n throw new Error(\n 'createHandler(): the entry finished loading without calling bootstrap(). ' +\n \"Pass the module that calls it — createHandler(() => import('./index')) — or pass the options.\",\n )\n }\n return captured\n })().catch((err) => {\n pending = undefined\n throw err\n }))\n}\n\n/**\n * Build a KickJS app as request handlers instead of a listening server.\n *\n * Takes the same options as `bootstrap()`, or a function that imports the\n * app's entry — the file that calls `bootstrap()`. With the entry, the app\n * is built from that one `bootstrap({ ... })` call, so the server and the\n * function never drift apart:\n *\n * ```ts\n * // src/serverless.ts\n * export const handler = createHandler(() => import('./index'))\n * ```\n *\n * While the entry loads, its `bootstrap()` call builds the app without\n * starting it — no port, no process signal handlers, no cluster. The app is set up once per process\n * (per function instance), lazily on the first request, and reused after that.\n * Nothing listens on a port, `afterStart` does not run, and no process signal\n * handlers are registered — the platform owns the process.\n *\n * `fetch` uses the runtime's own fetch when it has one (the h3 v2 runtime).\n * Runtimes built on Node request/response objects — Express, the default —\n * are served through a server bound to `127.0.0.1` on a random port inside the\n * same process, started on first use: the `Request` is forwarded to it and its\n * response returned. Request bodies are buffered on that path; response bodies\n * stream. Adapters that rewrite the `res` prototype (Express does) make a\n * direct Request→`res` bridge unreliable, which is why this forwards instead.\n *\n * One handler per process: the DI container is process-wide.\n *\n * @example\n * ```ts\n * // server/src/serverless.ts\n * import 'reflect-metadata'\n * import './config'\n * import { createHandler } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const handler = createHandler({ modules })\n *\n * // netlify/functions/api.mjs\n * export default (request, context) => handler.fetch(request, context)\n * export const config = { path: '/api/*' }\n * ```\n */\nexport function createHandler(options: ApplicationOptions | (() => Promise<unknown>)): KickHandler {\n let app: Promise<Application> | undefined\n const entry =\n typeof options === 'function'\n ? captureEntry(options)\n : async () => ({ first: undefined, options })\n // The app the entry's bootstrap() built is used once; a retry builds anew.\n let firstUsed = false\n\n const ready = (): Promise<Application> => {\n app ??= (async () => {\n let loaded: Awaited<ReturnType<typeof entry>>\n try {\n loaded = await entry()\n } catch (err) {\n // The entry failed to load: try again on the next request.\n app = undefined\n throw err\n }\n const instance = loaded.first && !firstUsed ? loaded.first : new Application(loaded.options)\n firstUsed = true\n try {\n await instance.startWithoutServer()\n } catch (err) {\n // A failed setup (a database that was briefly down, say) is retried on\n // the next request. Shut this attempt down first so its adapters don't\n // stay live next to the retry's.\n app = undefined\n await instance.shutdown().catch(() => {})\n throw err\n }\n return instance\n })()\n return app\n }\n\n return {\n ready,\n\n async fetch(request, platform) {\n const response = await (await ready()).fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n\n async node(req, res, platform) {\n const instance = await ready()\n instance.handle(req, res)\n if (platform?.waitUntil) {\n // The response is written asynchronously: start settling only once it\n // has gone out, so work the handler registered along the way is included.\n const sent = new Promise<void>((resolve) => res.once('close', () => resolve()))\n platform.waitUntil(sent.then(settleBackgroundWork))\n }\n },\n\n async close() {\n const current = app\n app = undefined\n if (current) await (await current).shutdown()\n },\n }\n}\n","import cluster from 'node:cluster'\nimport { reportError } from '../core/observers'\nimport { createLogger, Container } from '../core'\nimport { reloadEnv } from '../config/env'\nimport { Application, type ApplicationOptions } from './application'\nimport { setupClusterPrimary, type ClusterOptions } from './cluster'\nimport { ENTRY_CAPTURE, type EntryCapture } from './handler'\n\n/** Reload env from .env file (HMR rebuild) — config now lives in-tree. */\nfunction tryReloadEnv(): void {\n try {\n reloadEnv()\n } catch {\n // Best-effort: never crash bootstrap because env reload failed.\n }\n}\n\nconst log = createLogger('Process')\n\n/**\n * Bootstrap a KickJS application.\n *\n * Creates the Express app, registers modules and adapters, and starts\n * the HTTP server. In dev mode (`kick dev`), the Vite plugin manages\n * the server and HMR — source changes are picked up instantly without\n * losing database connections or WebSocket state.\n *\n * @returns The {@link Application} instance.\n *\n * @example\n * ```ts\n * // src/index.ts\n * import 'reflect-metadata'\n * import { bootstrap } from '@forinda/kickjs'\n * import { modules } from './modules'\n *\n * export const app = await bootstrap({ modules })\n * ```\n */\nexport async function bootstrap(options: ApplicationOptions): Promise<Application> {\n // ── Loaded by createHandler(() => import('./index')) ────────────────\n // The serverless entry reuses this call's options: build the app and hand\n // it over without listening, forking or registering process hooks.\n const capture = (globalThis as Record<symbol, unknown>)[ENTRY_CAPTURE]\n if (typeof capture === 'function') {\n const app = new Application(options)\n ;(capture as EntryCapture)(app, options)\n return app\n }\n\n // ── Cluster mode ─────────────────────────────────────────────────────\n // In cluster mode the primary process forks workers and never runs the\n // Express application itself. Only workers proceed past this block.\n // Cluster is disabled in Vite dev mode — Vite owns the HTTP server and\n // forked workers would each create their own Vite instance on separate ports.\n const isViteDev = !!(globalThis as any).__kickjs_httpServer\n if (options.cluster && isViteDev) {\n log.warn(\n 'Cluster mode is ignored in dev — Vite owns the server. Cluster applies in production (kick start).',\n )\n }\n if (options.cluster && cluster.isPrimary && !isViteDev) {\n const clusterOpts: ClusterOptions = typeof options.cluster === 'object' ? options.cluster : {}\n setupClusterPrimary(clusterOpts)\n\n // Return a placeholder — the primary never serves HTTP traffic.\n // The Application is created only so callers get a valid reference.\n return new Application(options)\n }\n\n // Internal: globalThis stores the app instance and Vite's HTTP server\n // reference across HMR rebuilds. When __kickjs_httpServer is set, the\n // Vite plugin owns the port and bootstrap() skips server creation.\n // On subsequent calls (HMR), the Express handler is swapped without\n // restarting the server — preserving DB connections and port bindings.\n const g = globalThis as any\n\n // ── Global error handlers + signal hooks ─────────────────────────────\n // `processHooks` controls whether KickJS registers its own\n // process-level handlers. Defaults to `'auto'` — register everything.\n // Adopters that bring their own observability stack (OpenTelemetry SDK,\n // Sentry, custom shutdown choreographer) often register their own\n // SIGINT/SIGTERM handlers and need to opt out of ours so the two don't\n // race to call `process.exit(0)`. Three modes:\n // - 'auto' (default): register uncaughtException/unhandledRejection\n // loggers + SIGINT/SIGTERM → `app.shutdown()` → `process.exit(0)`.\n // - 'errors-only': register the error loggers; skip signal handlers.\n // Use this when you have your own shutdown choreographer that calls\n // `app.shutdown()` itself.\n // - 'manual': skip everything. Adopter is responsible for both error\n // logging and signal-driven shutdown.\n const processHooks = options.processHooks ?? 'auto'\n\n if (!g.__kickBootstrapped) {\n if (processHooks !== 'manual') {\n // A listener here replaces Node's own handling, which exits with code\n // 1. Keep the failure in the exit code: a boot that throws — a top-level\n // `await bootstrap()` rejecting — must not end the process with 0, or a\n // deploy reads the crash as success.\n process.on('uncaughtException', (err) => {\n log.error(err, 'Uncaught exception')\n reportError(err, { source: 'uncaught' })\n process.exitCode = 1\n })\n\n process.on('unhandledRejection', (reason) => {\n log.error(reason as any, 'Unhandled rejection')\n reportError(reason, { source: 'unhandled-rejection' })\n process.exitCode = 1\n })\n }\n\n if (processHooks === 'auto' && !g.__kickjs_httpServer) {\n for (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, async () => {\n log.info(`Received ${signal}, shutting down...`)\n if (g.__app) await g.__app.shutdown()\n process.exit(0)\n })\n }\n }\n\n g.__kickBootstrapped = true\n }\n\n // ── HMR rebuild ──────────────────────────────────────────────────────\n if (g.__app) {\n log.debug('HMR rebuild triggered')\n\n // Tear the PREVIOUS app down before replacing it. Without this the old\n // Application was dropped on the floor still running: its adapters kept\n // their sockets and consumers open, so every save added another set.\n //\n // Observed in the wild as one process holding several consumer-group\n // members — on a single-partition topic only one can hold the assignment,\n // and it was a leaked consumer no longer wired to anything, so jobs\n // stopped being processed. A second socket.io server on the same HTTP\n // server crashed `handleUpgrade()` the same way.\n //\n // `closeServer: false` is load-bearing: the dev HTTP server is shared\n // across rebuilds, so a full shutdown would close the listening socket and\n // kill HMR on the first save.\n //\n // Failures are logged, not thrown — one broken adapter must not leave the\n // dev server wedged with no app at all.\n try {\n await g.__app.shutdown({ closeServer: false })\n } catch (err) {\n log.error(err as Error, 'HMR teardown of the previous app failed')\n }\n\n tryReloadEnv()\n Container.reset()\n\n const freshApp = new Application(options)\n g.__app = freshApp\n g.__kickjs_container = freshApp.getContainer()\n\n await freshApp.start()\n log.debug('HMR rebuild complete')\n return freshApp\n }\n\n // ── First boot ───────────────────────────────────────────────────────\n const app = new Application(options)\n g.__app = app\n g.__kickjs_container = app.getContainer()\n\n if (process.env.KICK_TINKER) {\n await app.registerOnly()\n return app\n }\n\n await app.start()\n\n return app\n}\n"],"mappings":";;;;;;;;;;wnBAmCA,MAAMA,MAAM,aAAa,iBAAiB,EACpC,YAAc,cAAc,YAAY,GAAG,EAGpC,gBAAkB,mBAa/B,SAAS,YAAqC,CAC5C,GAAI,CACF,OAAQ,YAAY,QAAQ,CA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,EACrD,QAAQ,SAAW,CACrB,CAAC,GAGC,eAAiB,QAAU,CAAC,EAAE,oBAChC,IAAK,IAAM,SAAU,CAAC,SAAU,SAAS,EACvC,QAAQ,GAAG,OAAQ,SAAY,CAC7B,IAAI,KAAK,YAAY,OAAO,mBAAmB,EAC3C,EAAE,OAAO,MAAM,EAAE,MAAM,SAAS,EACpC,QAAQ,KAAK,CAAC,CAChB,CAAC,EAIL,EAAE,mBAAqB,EACzB,CAGA,GAAI,EAAE,MAAO,CACX,IAAI,MAAM,uBAAuB,EAkBjC,GAAI,CACF,MAAM,EAAE,MAAM,SAAS,CAAE,YAAa,EAAM,CAAC,CAC/C,OAAS,IAAK,CACZ,IAAI,MAAM,IAAc,yCAAyC,CACnE,CAEA,aAAa,EACb,UAAU,MAAM,EAEhB,IAAM,SAAW,IAAI,YAAY,OAAO,EAMxC,MALA,GAAE,MAAQ,SACV,EAAE,mBAAqB,SAAS,aAAa,EAE7C,MAAM,SAAS,MAAM,EACrB,IAAI,MAAM,sBAAsB,EACzB,QACT,CAGA,IAAM,IAAM,IAAI,YAAY,OAAO,EAWnC,MAVA,GAAE,MAAQ,IACV,EAAE,mBAAqB,IAAI,aAAa,EAEpC,QAAQ,IAAI,aACd,MAAM,IAAI,aAAa,EAChB,MAGT,MAAM,IAAI,MAAM,EAET,IACT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.6.0
2
+ * @forinda/kickjs v10.7.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  var BoundedCounters=class{windowMs;limit;max;hits=/* @__PURE__ */ new Map;singles=/* @__PURE__ */ new Set;constructor(windowMs,limit=1/0,max=1e5){this.windowMs=windowMs,this.limit=limit,this.max=max}get size(){return this.hits.size}increment(key){let now=Date.now(),entry=this.hits.get(key);if(entry&&entry.reset>now)return entry.hits++,entry.hits>1&&this.singles.delete(key),{totalHits:entry.hits,resetTime:new Date(entry.reset)};if(this.remove(key),this.sweep(now),this.hits.size>=this.max){let single=this.limit>1?this.singles.values().next().value:void 0;if(single===void 0){let oldest=this.hits.values().next().value;return{totalHits:1/0,resetTime:new Date(oldest.reset)}}this.remove(single)}let fresh={hits:1,reset:now+this.windowMs};return this.hits.set(key,fresh),this.singles.add(key),{totalHits:1,resetTime:new Date(fresh.reset)}}decrement(key){let entry=this.hits.get(key);entry&&entry.hits!==0&&(entry.hits--,entry.hits<=1&&this.singles.add(key))}reset(key){this.remove(key)}sweep(now=Date.now()){for(let[key,entry]of this.hits){if(entry.reset>now)break;this.remove(key)}}clear(){this.hits.clear(),this.singles.clear()}remove(key){this.hits.delete(key),this.singles.delete(key)}};export{BoundedCounters as t};
12
- //# sourceMappingURL=bounded-counters-Bd7X3eI5.mjs.map
12
+ //# sourceMappingURL=bounded-counters-_6sdDRhT.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"bounded-counters-Bd7X3eI5.mjs","names":[],"sources":["../src/http/middleware/bounded-counters.ts"],"sourcesContent":["/**\n * Per-key hit counters for a fixed window, in memory, bounded — the core of\n * the in-memory rate-limit stores. Keys come from clients (an IP, a header\n * behind a proxy, a username from a custom key), so the map is capped, and\n * what happens at the cap decides who a flood of new keys can hurt:\n *\n * - Expired windows go first. The map is kept in window order (a key starting\n * a new window moves to the back), so they are always at the front, and a\n * sweep stops at the first live one — no full scan.\n * - Then a counter still at one hit, oldest first — when the limit is above\n * one, so a single hit is below it. A flood of single requests from made-up\n * keys just recycles itself; a counter a client has hit twice (a username\n * with failed logins) is never pushed out, so flooding can't reset it. At\n * most it costs a key one hit, while that key is at one. With a limit of\n * one, a single hit is already the limit, so nothing live is evicted.\n * - Only when every counter is at two or more is a new key refused, counted\n * as over any limit until the oldest window ends. Reaching that takes two\n * requests per key across the whole cap within one window.\n *\n * @internal\n */\nexport class BoundedCounters {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n /** Keys at one hit (or fewer), oldest first: the only ones evicted. */\n private readonly singles = new Set<string>()\n\n /**\n * @param limit The rate limit these counters enforce (`max`): one-hit\n * counters are only evictable while that's below it.\n */\n constructor(\n private readonly windowMs: number,\n private readonly limit = Number.POSITIVE_INFINITY,\n // ponytail: fixed cap; a store shared between instances (Redis) has its own limits.\n private readonly max = 100_000,\n ) {}\n\n get size(): number {\n return this.hits.size\n }\n\n increment(key: string): { totalHits: number; resetTime: Date } {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n if (entry.hits > 1) this.singles.delete(key)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n this.remove(key)\n this.sweep(now)\n if (this.hits.size >= this.max) {\n const single = this.limit > 1 ? this.singles.values().next().value : undefined\n if (single === undefined) {\n const oldest = this.hits.values().next().value!\n return { totalHits: Number.POSITIVE_INFINITY, resetTime: new Date(oldest.reset) }\n }\n this.remove(single)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n this.singles.add(key)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n decrement(key: string): void {\n const entry = this.hits.get(key)\n if (!entry || entry.hits === 0) return\n entry.hits--\n if (entry.hits <= 1) this.singles.add(key)\n }\n\n reset(key: string): void {\n this.remove(key)\n }\n\n /** Drop expired windows, from the front. */\n sweep(now = Date.now()): void {\n for (const [key, entry] of this.hits) {\n if (entry.reset > now) break\n this.remove(key)\n }\n }\n\n clear(): void {\n this.hits.clear()\n this.singles.clear()\n }\n\n private remove(key: string): void {\n this.hits.delete(key)\n this.singles.delete(key)\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,gBAAb,KAA6B,CAUR,SACA,MAEA,IAZnB,qBAAwB,IAAI,IAE5B,wBAA2B,IAAI,IAM/B,YACE,SACA,MAAyB,IAEzB,IAAuB,IACvB,CAJiB,KAAA,SAAA,SACA,KAAA,MAAA,MAEA,KAAA,IAAA,GAChB,CAEH,IAAI,MAAe,CACjB,OAAO,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CACZ,KAAK,KAAK,MAAM,EAChB,KAAK,QAAQ,MAAM,CACrB,CAEA,OAAe,IAAmB,CAChC,KAAK,KAAK,OAAO,GAAG,EACpB,KAAK,QAAQ,OAAO,GAAG,CACzB,CACF"}
1
+ {"version":3,"file":"bounded-counters-_6sdDRhT.mjs","names":[],"sources":["../src/http/middleware/bounded-counters.ts"],"sourcesContent":["/**\n * Per-key hit counters for a fixed window, in memory, bounded — the core of\n * the in-memory rate-limit stores. Keys come from clients (an IP, a header\n * behind a proxy, a username from a custom key), so the map is capped, and\n * what happens at the cap decides who a flood of new keys can hurt:\n *\n * - Expired windows go first. The map is kept in window order (a key starting\n * a new window moves to the back), so they are always at the front, and a\n * sweep stops at the first live one — no full scan.\n * - Then a counter still at one hit, oldest first — when the limit is above\n * one, so a single hit is below it. A flood of single requests from made-up\n * keys just recycles itself; a counter a client has hit twice (a username\n * with failed logins) is never pushed out, so flooding can't reset it. At\n * most it costs a key one hit, while that key is at one. With a limit of\n * one, a single hit is already the limit, so nothing live is evicted.\n * - Only when every counter is at two or more is a new key refused, counted\n * as over any limit until the oldest window ends. Reaching that takes two\n * requests per key across the whole cap within one window.\n *\n * @internal\n */\nexport class BoundedCounters {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n /** Keys at one hit (or fewer), oldest first: the only ones evicted. */\n private readonly singles = new Set<string>()\n\n /**\n * @param limit The rate limit these counters enforce (`max`): one-hit\n * counters are only evictable while that's below it.\n */\n constructor(\n private readonly windowMs: number,\n private readonly limit = Number.POSITIVE_INFINITY,\n // ponytail: fixed cap; a store shared between instances (Redis) has its own limits.\n private readonly max = 100_000,\n ) {}\n\n get size(): number {\n return this.hits.size\n }\n\n increment(key: string): { totalHits: number; resetTime: Date } {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n if (entry.hits > 1) this.singles.delete(key)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n this.remove(key)\n this.sweep(now)\n if (this.hits.size >= this.max) {\n const single = this.limit > 1 ? this.singles.values().next().value : undefined\n if (single === undefined) {\n const oldest = this.hits.values().next().value!\n return { totalHits: Number.POSITIVE_INFINITY, resetTime: new Date(oldest.reset) }\n }\n this.remove(single)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n this.singles.add(key)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n decrement(key: string): void {\n const entry = this.hits.get(key)\n if (!entry || entry.hits === 0) return\n entry.hits--\n if (entry.hits <= 1) this.singles.add(key)\n }\n\n reset(key: string): void {\n this.remove(key)\n }\n\n /** Drop expired windows, from the front. */\n sweep(now = Date.now()): void {\n for (const [key, entry] of this.hits) {\n if (entry.reset > now) break\n this.remove(key)\n }\n }\n\n clear(): void {\n this.hits.clear()\n this.singles.clear()\n }\n\n private remove(key: string): void {\n this.hits.delete(key)\n this.singles.delete(key)\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,gBAAb,KAA6B,CAUR,SACA,MAEA,IAZnB,qBAAwB,IAAI,IAE5B,wBAA2B,IAAI,IAM/B,YACE,SACA,MAAyB,IAEzB,IAAuB,IACvB,CAJiB,KAAA,SAAA,SACA,KAAA,MAAA,MAEA,KAAA,IAAA,GAChB,CAEH,IAAI,MAAe,CACjB,OAAO,KAAK,KAAK,IACnB,CAEA,UAAU,IAAqD,CAC7D,IAAM,IAAM,KAAK,IAAI,EACf,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC/B,GAAI,OAAS,MAAM,MAAQ,IAGzB,MAFA,OAAM,OACF,MAAM,KAAO,GAAG,KAAK,QAAQ,OAAO,GAAG,EACpC,CAAE,UAAW,MAAM,KAAM,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,EAInE,GAFA,KAAK,OAAO,GAAG,EACf,KAAK,MAAM,GAAG,EACV,KAAK,KAAK,MAAQ,KAAK,IAAK,CAC9B,IAAM,OAAS,KAAK,MAAQ,EAAI,KAAK,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,MAAQ,IAAA,GACrE,GAAI,SAAW,IAAA,GAAW,CACxB,IAAM,OAAS,KAAK,KAAK,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,MACzC,MAAO,CAAE,UAAW,IAA0B,UAAW,IAAI,KAAK,OAAO,KAAK,CAAE,CAClF,CACA,KAAK,OAAO,MAAM,CACpB,CACA,IAAM,MAAQ,CAAE,KAAM,EAAG,MAAO,IAAM,KAAK,QAAS,EAGpD,OAFA,KAAK,KAAK,IAAI,IAAK,KAAK,EACxB,KAAK,QAAQ,IAAI,GAAG,EACb,CAAE,UAAW,EAAG,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,CAC1D,CAEA,UAAU,IAAmB,CAC3B,IAAM,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC1B,OAAS,MAAM,OAAS,IAC7B,MAAM,OACF,MAAM,MAAQ,GAAG,KAAK,QAAQ,IAAI,GAAG,EAC3C,CAEA,MAAM,IAAmB,CACvB,KAAK,OAAO,GAAG,CACjB,CAGA,MAAM,IAAM,KAAK,IAAI,EAAS,CAC5B,IAAK,GAAM,CAAC,IAAK,SAAU,KAAK,KAAM,CACpC,GAAI,MAAM,MAAQ,IAAK,MACvB,KAAK,OAAO,GAAG,CACjB,CACF,CAEA,OAAc,CACZ,KAAK,KAAK,MAAM,EAChB,KAAK,QAAQ,MAAM,CACrB,CAEA,OAAe,IAAmB,CAChC,KAAK,KAAK,OAAO,GAAG,EACpB,KAAK,QAAQ,OAAO,GAAG,CACzB,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.6.0
2
+ * @forinda/kickjs v10.7.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  function firstHop(value){return typeof value==`string`&&value.length>0?value.split(`,`)[0].trim():void 0}function headerValue(headers,name){if(headers)return typeof headers.get==`function`?headers.get(name):headers[name]}function resolveClientIp(req){if(typeof req.ip==`string`&&req.ip.length>0)return req.ip;let socketAddress=req.socket?.remoteAddress;if(socketAddress)return socketAddress;let h=req.headers;return firstHop(headerValue(h,`cf-connecting-ip`))??firstHop(headerValue(h,`x-forwarded-for`))??firstHop(headerValue(h,`x-real-ip`))}function resolvePathname(req){if(typeof req.path==`string`&&req.path.length>0)return req.path;let url=req.url;if(!url)return`/`;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(url))try{return new URL(url).pathname||`/`}catch{return`/`}let q=url.indexOf(`?`);return(q===-1?url:url.slice(0,q))||`/`}export{resolvePathname as n,resolveClientIp as t};
12
- //# sourceMappingURL=client-ip-DxEVqZP-.mjs.map
12
+ //# sourceMappingURL=client-ip-CrO5ktYs.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-ip-DxEVqZP-.mjs","names":[],"sources":["../src/http/client-ip.ts"],"sourcesContent":["/**\n * Client address + pathname resolution shared by everything that runs as\n * connect-style middleware.\n *\n * Fastify and h3 hand middleware the RAW node request, so the Express\n * conveniences (`req.ip`, `req.path`, `req.originalUrl`) are `undefined`\n * there. Reading them directly produced two live bugs:\n *\n * rate-limit → every caller keyed as the `'127.0.0.1'` fallback, i.e. ONE\n * shared bucket, so a single client could exhaust the limit\n * for everyone\n * csrf → `ignorePaths` never matched, so configured exemptions were\n * silently dead\n *\n * Edge-safe: no node imports.\n */\n\n/** The request members these helpers read, from node's shape rather than Express's. */\nexport interface ClientRequestLike {\n url?: string\n /** Express-only convenience. */\n path?: string\n /** Express-only; the full path before router mounting rewrote `url`. */\n originalUrl?: string\n /** Express and Fastify compute this from their trust-proxy settings. */\n ip?: unknown\n /**\n * A plain object on every path the framework currently takes — `WebRequestShim`\n * normalizes a WHATWG `Headers` before the context is built. A `Headers`\n * instance is accepted defensively: it is not index-accessible, so if one ever\n * did arrive, every lookup would return `undefined` SILENTLY and drop each\n * caller into one shared rate-limit bucket.\n */\n headers?: Record<string, string | string[] | undefined> | Headers\n socket?: { remoteAddress?: string }\n}\n\n/** First entry of a possibly comma-separated header value. */\nfunction firstHop(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value.split(',')[0]!.trim() : undefined\n}\n\n/** Read one header from either a plain object or a WHATWG `Headers`. */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined> | Headers | undefined,\n name: string,\n): unknown {\n if (!headers) return undefined\n // `Headers` has no index access, so `headers[name]` silently yields\n // `undefined` rather than the value.\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name)\n return (headers as Record<string, string | string[] | undefined>)[name]\n}\n\n/**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the address the runtime computed — Express derives `req.ip` from\n * `trust proxy`, Fastify from `trustProxy` — because raw forwarded headers are\n * client-SPOOFABLE wherever nothing normalizes them. h3 takes the same stance:\n * its `getRequestIP` only consults `x-forwarded-for` when explicitly opted in.\n *\n * Order is `req.ip` → `socket.remoteAddress` → forwarded headers. The socket\n * comes BEFORE the headers deliberately: it cannot be spoofed, whereas a direct\n * client can vary `x-forwarded-for` per request to get a fresh rate-limit\n * bucket each time. Headers are consulted only where there is no socket — the\n * web/edge entry, where the platform terminates the connection.\n */\nexport function resolveClientIp(req: ClientRequestLike): string | undefined {\n // 1. What the runtime computed. Express derives `req.ip` from `trust proxy`,\n // Fastify from `trustProxy` — a value vetted against a CONFIGURED proxy,\n // which is the only reason to believe a forwarded header at all.\n if (typeof req.ip === 'string' && req.ip.length > 0) return req.ip\n\n // 2. The socket. Unspoofable, and present on every node runtime.\n //\n // This MUST precede the headers. A raw Fastify / h3 request has no\n // `req.ip`, so consulting `x-forwarded-for` first let a DIRECT client send\n // a different value per request and land in a fresh rate-limit bucket each\n // time — evading the limit entirely. Behind a real proxy the socket is the\n // proxy's address, which buckets clients together; the fix for that is to\n // configure the runtime's trust-proxy setting so step 1 answers, not to\n // trust an unverified header here.\n const socketAddress = req.socket?.remoteAddress\n if (socketAddress) return socketAddress\n\n // 3. Headers, only where there is no socket at all — the web/edge entry,\n // where the platform terminates the connection and these are the only\n // signal available.\n const h = req.headers\n return (\n firstHop(headerValue(h, 'cf-connecting-ip')) ??\n firstHop(headerValue(h, 'x-forwarded-for')) ??\n firstHop(headerValue(h, 'x-real-ip'))\n )\n}\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nexport function resolvePathname(req: ClientRequestLike): string {\n if (typeof req.path === 'string' && req.path.length > 0) return req.path\n const url = req.url\n if (!url) return '/'\n // `WebRequestShim` already reduces the WHATWG `Request.url` to path+search,\n // but an ABSOLUTE url would otherwise be returned whole — so a skip prefix\n // like `/health` would never match `https://host/health`.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)) {\n try {\n return new URL(url).pathname || '/'\n } catch {\n return '/'\n }\n }\n const q = url.indexOf('?')\n return (q === -1 ? url : url.slice(0, q)) || '/'\n}\n"],"mappings":";;;;;;;;;;AAsCA,SAAS,SAAS,MAAoC,CACpD,OAAO,OAAO,OAAU,UAAY,MAAM,OAAS,EAAI,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,KAAK,EAAI,IAAA,EACvF,CAGA,SAAS,YACP,QACA,KACS,CACT,GAAK,QAIL,OADI,OAAQ,QAAoB,KAAQ,WAAoB,QAAoB,IAAI,IAAI,EAChF,QAA0D,KACpE,CAgBA,SAAgB,gBAAgB,IAA4C,CAI1E,GAAI,OAAO,IAAI,IAAO,UAAY,IAAI,GAAG,OAAS,EAAG,OAAO,IAAI,GAWhE,IAAM,cAAgB,IAAI,QAAQ,cAClC,GAAI,cAAe,OAAO,cAK1B,IAAM,EAAI,IAAI,QACd,OACE,SAAS,YAAY,EAAG,kBAAkB,CAAC,GAC3C,SAAS,YAAY,EAAG,iBAAiB,CAAC,GAC1C,SAAS,YAAY,EAAG,WAAW,CAAC,CAExC,CAGA,SAAgB,gBAAgB,IAAgC,CAC9D,GAAI,OAAO,IAAI,MAAS,UAAY,IAAI,KAAK,OAAS,EAAG,OAAO,IAAI,KACpE,IAAM,IAAM,IAAI,IAChB,GAAI,CAAC,IAAK,MAAO,IAIjB,GAAI,2BAA2B,KAAK,GAAG,EACrC,GAAI,CACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC,UAAY,GAClC,MAAQ,CACN,MAAO,GACT,CAEF,IAAM,EAAI,IAAI,QAAQ,GAAG,EACzB,OAAQ,IAAM,GAAK,IAAM,IAAI,MAAM,EAAG,CAAC,IAAM,GAC/C"}
1
+ {"version":3,"file":"client-ip-CrO5ktYs.mjs","names":[],"sources":["../src/http/client-ip.ts"],"sourcesContent":["/**\n * Client address + pathname resolution shared by everything that runs as\n * connect-style middleware.\n *\n * Fastify and h3 hand middleware the RAW node request, so the Express\n * conveniences (`req.ip`, `req.path`, `req.originalUrl`) are `undefined`\n * there. Reading them directly produced two live bugs:\n *\n * rate-limit → every caller keyed as the `'127.0.0.1'` fallback, i.e. ONE\n * shared bucket, so a single client could exhaust the limit\n * for everyone\n * csrf → `ignorePaths` never matched, so configured exemptions were\n * silently dead\n *\n * Edge-safe: no node imports.\n */\n\n/** The request members these helpers read, from node's shape rather than Express's. */\nexport interface ClientRequestLike {\n url?: string\n /** Express-only convenience. */\n path?: string\n /** Express-only; the full path before router mounting rewrote `url`. */\n originalUrl?: string\n /** Express and Fastify compute this from their trust-proxy settings. */\n ip?: unknown\n /**\n * A plain object on every path the framework currently takes — `WebRequestShim`\n * normalizes a WHATWG `Headers` before the context is built. A `Headers`\n * instance is accepted defensively: it is not index-accessible, so if one ever\n * did arrive, every lookup would return `undefined` SILENTLY and drop each\n * caller into one shared rate-limit bucket.\n */\n headers?: Record<string, string | string[] | undefined> | Headers\n socket?: { remoteAddress?: string }\n}\n\n/** First entry of a possibly comma-separated header value. */\nfunction firstHop(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value.split(',')[0]!.trim() : undefined\n}\n\n/** Read one header from either a plain object or a WHATWG `Headers`. */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined> | Headers | undefined,\n name: string,\n): unknown {\n if (!headers) return undefined\n // `Headers` has no index access, so `headers[name]` silently yields\n // `undefined` rather than the value.\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name)\n return (headers as Record<string, string | string[] | undefined>)[name]\n}\n\n/**\n * The client's IP address, or `undefined` when it cannot be determined.\n *\n * Prefers the address the runtime computed — Express derives `req.ip` from\n * `trust proxy`, Fastify from `trustProxy` — because raw forwarded headers are\n * client-SPOOFABLE wherever nothing normalizes them. h3 takes the same stance:\n * its `getRequestIP` only consults `x-forwarded-for` when explicitly opted in.\n *\n * Order is `req.ip` → `socket.remoteAddress` → forwarded headers. The socket\n * comes BEFORE the headers deliberately: it cannot be spoofed, whereas a direct\n * client can vary `x-forwarded-for` per request to get a fresh rate-limit\n * bucket each time. Headers are consulted only where there is no socket — the\n * web/edge entry, where the platform terminates the connection.\n */\nexport function resolveClientIp(req: ClientRequestLike): string | undefined {\n // 1. What the runtime computed. Express derives `req.ip` from `trust proxy`,\n // Fastify from `trustProxy` — a value vetted against a CONFIGURED proxy,\n // which is the only reason to believe a forwarded header at all.\n if (typeof req.ip === 'string' && req.ip.length > 0) return req.ip\n\n // 2. The socket. Unspoofable, and present on every node runtime.\n //\n // This MUST precede the headers. A raw Fastify / h3 request has no\n // `req.ip`, so consulting `x-forwarded-for` first let a DIRECT client send\n // a different value per request and land in a fresh rate-limit bucket each\n // time — evading the limit entirely. Behind a real proxy the socket is the\n // proxy's address, which buckets clients together; the fix for that is to\n // configure the runtime's trust-proxy setting so step 1 answers, not to\n // trust an unverified header here.\n const socketAddress = req.socket?.remoteAddress\n if (socketAddress) return socketAddress\n\n // 3. Headers, only where there is no socket at all — the web/edge entry,\n // where the platform terminates the connection and these are the only\n // signal available.\n const h = req.headers\n return (\n firstHop(headerValue(h, 'cf-connecting-ip')) ??\n firstHop(headerValue(h, 'x-forwarded-for')) ??\n firstHop(headerValue(h, 'x-real-ip'))\n )\n}\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nexport function resolvePathname(req: ClientRequestLike): string {\n if (typeof req.path === 'string' && req.path.length > 0) return req.path\n const url = req.url\n if (!url) return '/'\n // `WebRequestShim` already reduces the WHATWG `Request.url` to path+search,\n // but an ABSOLUTE url would otherwise be returned whole — so a skip prefix\n // like `/health` would never match `https://host/health`.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)) {\n try {\n return new URL(url).pathname || '/'\n } catch {\n return '/'\n }\n }\n const q = url.indexOf('?')\n return (q === -1 ? url : url.slice(0, q)) || '/'\n}\n"],"mappings":";;;;;;;;;;AAsCA,SAAS,SAAS,MAAoC,CACpD,OAAO,OAAO,OAAU,UAAY,MAAM,OAAS,EAAI,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,KAAK,EAAI,IAAA,EACvF,CAGA,SAAS,YACP,QACA,KACS,CACT,GAAK,QAIL,OADI,OAAQ,QAAoB,KAAQ,WAAoB,QAAoB,IAAI,IAAI,EAChF,QAA0D,KACpE,CAgBA,SAAgB,gBAAgB,IAA4C,CAI1E,GAAI,OAAO,IAAI,IAAO,UAAY,IAAI,GAAG,OAAS,EAAG,OAAO,IAAI,GAWhE,IAAM,cAAgB,IAAI,QAAQ,cAClC,GAAI,cAAe,OAAO,cAK1B,IAAM,EAAI,IAAI,QACd,OACE,SAAS,YAAY,EAAG,kBAAkB,CAAC,GAC3C,SAAS,YAAY,EAAG,iBAAiB,CAAC,GAC1C,SAAS,YAAY,EAAG,WAAW,CAAC,CAExC,CAGA,SAAgB,gBAAgB,IAAgC,CAC9D,GAAI,OAAO,IAAI,MAAS,UAAY,IAAI,KAAK,OAAS,EAAG,OAAO,IAAI,KACpE,IAAM,IAAM,IAAI,IAChB,GAAI,CAAC,IAAK,MAAO,IAIjB,GAAI,2BAA2B,KAAK,GAAG,EACrC,GAAI,CACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC,UAAY,GAClC,MAAQ,CACN,MAAO,GACT,CAEF,IAAM,EAAI,IAAI,QAAQ,GAAG,EACzB,OAAQ,IAAM,GAAK,IAAM,IAAI,MAAM,EAAG,CAAC,IAAM,GAC/C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.6.0
2
+ * @forinda/kickjs v10.7.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"../decorate-wrAUzCjW.mjs";import{n as createConfigService,t as ConfigService}from"../config-_YTqZtnE.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
11
+ import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"../decorate-BHhpOfEF.mjs";import{n as createConfigService,t as ConfigService}from"../config-CWKj0Z66.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.6.0
2
+ * @forinda/kickjs v10.7.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Service}from"./core/decorators.mjs";import{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-wrAUzCjW.mjs";let ConfigService=class{get env(){return loadEnv()}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
12
- //# sourceMappingURL=config-_YTqZtnE.mjs.map
11
+ import{Service}from"./core/decorators.mjs";import{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-BHhpOfEF.mjs";let ConfigService=class{get env(){return loadEnv()}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
12
+ //# sourceMappingURL=config-CWKj0Z66.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-_YTqZtnE.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container._envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>\n /** With a fallback, returned when the value is unset (`undefined` or `null`). */\n get<K extends string, T = any>(\n key: ConfigKey<K>,\n fallback: NonNullable<ConfigValue<K, T>>,\n ): NonNullable<ConfigValue<K, T>>\n get(key: string, fallback?: unknown): unknown {\n return this.env[key] ?? fallback\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n get(key: string, fallback?: unknown): unknown {\n return (this.env as Record<string, unknown>)[key] ?? fallback\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;4HA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAiBA,IAAI,IAAa,SAA6B,CAC5C,OAAO,KAAK,IAAI,MAAQ,QAC1B,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAjEC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EA6GT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAIA,IAAI,IAAa,SAA6B,CAC5C,OAAQ,KAAK,IAAgC,MAAQ,QACvD,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAnCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAmCF,mBAGT"}
1
+ {"version":3,"file":"config-CWKj0Z66.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container._envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>\n /** With a fallback, returned when the value is unset (`undefined` or `null`). */\n get<K extends string, T = any>(\n key: ConfigKey<K>,\n fallback: NonNullable<ConfigValue<K, T>>,\n ): NonNullable<ConfigValue<K, T>>\n get(key: string, fallback?: unknown): unknown {\n return this.env[key] ?? fallback\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n get(key: string, fallback?: unknown): unknown {\n return (this.env as Record<string, unknown>)[key] ?? fallback\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;4HA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAiBA,IAAI,IAAa,SAA6B,CAC5C,OAAO,KAAK,IAAI,MAAQ,QAC1B,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAjEC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EA6GT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAIA,IAAI,IAAa,SAA6B,CAC5C,OAAQ,KAAK,IAAgC,MAAQ,QACvD,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAnCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAmCF,mBAGT"}