@forinda/kickjs 10.5.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.
- package/dist/{adapter-BZ1WzN1z.d.mts → adapter-9sPr_5xt.d.mts} +123 -35
- package/dist/adapter-9sPr_5xt.d.mts.map +1 -0
- package/dist/{allowed-hosts-D6qcuK5I.d.mts → allowed-hosts-BpKwviq5.d.mts} +3 -3
- package/dist/allowed-hosts-BpKwviq5.d.mts.map +1 -0
- package/dist/application-BSzwuTQ6.mjs +14 -0
- package/dist/application-BSzwuTQ6.mjs.map +1 -0
- package/dist/{application-D5Iiy7rt.d.mts → application-BZjDmsWb.d.mts} +118 -45
- package/dist/application-BZjDmsWb.d.mts.map +1 -0
- package/dist/background-BJjLKrnK.mjs +12 -0
- package/dist/background-BJjLKrnK.mjs.map +1 -0
- package/dist/bootstrap-Dxax6Mcp.mjs +12 -0
- package/dist/{bootstrap-B_6QfzXV.mjs.map → bootstrap-Dxax6Mcp.mjs.map} +1 -1
- package/dist/{bounded-counters-C8PHfWEu.mjs → bounded-counters-_6sdDRhT.mjs} +2 -2
- package/dist/{bounded-counters-C8PHfWEu.mjs.map → bounded-counters-_6sdDRhT.mjs.map} +1 -1
- package/dist/{breach-padding-C-Dnq8CS.d.mts → breach-padding-FBVGmcBb.d.mts} +3 -3
- package/dist/breach-padding-FBVGmcBb.d.mts.map +1 -0
- package/dist/{client-ip-kxT2SHut.mjs → client-ip-CrO5ktYs.mjs} +2 -2
- package/dist/{client-ip-kxT2SHut.mjs.map → client-ip-CrO5ktYs.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-Dz-HnO4c.mjs → config-CWKj0Z66.mjs} +3 -3
- package/dist/{config-Dz-HnO4c.mjs.map → config-CWKj0Z66.mjs.map} +1 -1
- package/dist/connect-BlIamapT.d.mts +41 -0
- package/dist/connect-BlIamapT.d.mts.map +1 -0
- package/dist/context-BlJRkMyq.mjs +12 -0
- package/dist/context-BlJRkMyq.mjs.map +1 -0
- package/dist/{context-errors-gitMJXxZ.mjs → context-errors-ykpXYECS.mjs} +2 -2
- package/dist/{context-errors-gitMJXxZ.mjs.map → context-errors-ykpXYECS.mjs.map} +1 -1
- package/dist/{contributor-runner-CDlPrzai.mjs → contributor-runner-BM-5Wr19.mjs} +3 -3
- package/dist/{contributor-runner-CDlPrzai.mjs.map → contributor-runner-BM-5Wr19.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/core-DlrlhjF4.mjs +12 -0
- package/dist/{core-CSWR0hHJ.mjs.map → core-DlrlhjF4.mjs.map} +1 -1
- package/dist/{cors-2Bwhyhpt.d.mts → cors-BlR_b0Qb.d.mts} +3 -3
- package/dist/cors-BlR_b0Qb.d.mts.map +1 -0
- package/dist/{csrf-BDAZK2mm.d.mts → csrf-ZFOrJZhJ.d.mts} +3 -3
- package/dist/csrf-ZFOrJZhJ.d.mts.map +1 -0
- package/dist/decorate-BHhpOfEF.mjs +13 -0
- package/dist/{decorate-D2oVJls5.mjs.map → decorate-BHhpOfEF.mjs.map} +1 -1
- package/dist/{define-adapter-oANmOi4a.mjs → define-adapter-CF-DJRq9.mjs} +2 -2
- package/dist/{define-adapter-oANmOi4a.mjs.map → define-adapter-CF-DJRq9.mjs.map} +1 -1
- package/dist/{di-hooks-HI14rSja.mjs → di-hooks-CCKeiLT-.mjs} +2 -2
- package/dist/{di-hooks-HI14rSja.mjs.map → di-hooks-CCKeiLT-.mjs.map} +1 -1
- package/dist/{disposables-CWNNe9HH.mjs → disposables-bnkL4rG7.mjs} +1 -1
- package/dist/{error-handler-CbP7hKdJ.d.mts → error-handler-CH4PPZCK.d.mts} +2 -2
- package/dist/{error-handler-CbP7hKdJ.d.mts.map → error-handler-CH4PPZCK.d.mts.map} +1 -1
- package/dist/express-4fvuMB5q.mjs +12 -0
- package/dist/express-4fvuMB5q.mjs.map +1 -0
- package/dist/express-lazy-D9MZnma8.mjs +12 -0
- package/dist/express-lazy-D9MZnma8.mjs.map +1 -0
- package/dist/handler-TzaD8jPN.mjs +12 -0
- package/dist/{handler-D23bJ6g1.mjs.map → handler-TzaD8jPN.mjs.map} +1 -1
- package/dist/{helmet-CEOmo516.d.mts → helmet-BVuVBl-D.d.mts} +3 -3
- package/dist/helmet-BVuVBl-D.d.mts.map +1 -0
- package/dist/{host-C2_vvcrO.mjs → host-CtpcIKcA.mjs} +2 -2
- package/dist/{host-C2_vvcrO.mjs.map → host-CtpcIKcA.mjs.map} +1 -1
- package/dist/http/application.d.mts +2 -2
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +1 -1
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.d.mts +1 -1
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
- package/dist/http/middleware/breach-padding.d.mts +1 -1
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/breach-padding.mjs.map +1 -1
- package/dist/http/middleware/cors.d.mts +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.d.mts +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.d.mts +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +3 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.d.mts +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +47 -0
- package/dist/http/runtimes/express.d.mts.map +1 -0
- package/dist/http/runtimes/express.mjs +11 -0
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/index.d.mts +17 -16
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{is-production-TSixl400.mjs → is-production-BfIKY2Sw.mjs} +2 -2
- package/dist/{is-production-TSixl400.mjs.map → is-production-BfIKY2Sw.mjs.map} +1 -1
- package/dist/{jobs-DIddIoQs.mjs → jobs-BJfIOWUT.mjs} +3 -3
- package/dist/{jobs-DIddIoQs.mjs.map → jobs-BJfIOWUT.mjs.map} +1 -1
- package/dist/{kv-stores-B9xLP0mg.mjs → kv-stores-BeDHfiyW.mjs} +3 -3
- package/dist/{kv-stores-B9xLP0mg.mjs.map → kv-stores-BeDHfiyW.mjs.map} +1 -1
- package/dist/{kv-stores-DXFBEYYu.d.mts → kv-stores-C1sQs2Rb.d.mts} +4 -4
- package/dist/{kv-stores-DXFBEYYu.d.mts.map → kv-stores-C1sQs2Rb.d.mts.map} +1 -1
- package/dist/lazy-serve-static-BUMcYDMn.mjs +12 -0
- package/dist/lazy-serve-static-BUMcYDMn.mjs.map +1 -0
- package/dist/{metadata-CJRJvpAK.mjs → metadata-x0eCJRTl.mjs} +1 -1
- package/dist/{observers-DaIAahW4.mjs → observers-Ss6-7Si7.mjs} +2 -2
- package/dist/{observers-DaIAahW4.mjs.map → observers-Ss6-7Si7.mjs.map} +1 -1
- package/dist/precompressed-BBXQUDXp.mjs +12 -0
- package/dist/precompressed-BBXQUDXp.mjs.map +1 -0
- package/dist/{query-CUvSp-JT.mjs → query-DIS_2QiJ.mjs} +2 -2
- package/dist/{query-CUvSp-JT.mjs.map → query-DIS_2QiJ.mjs.map} +1 -1
- package/dist/{rate-limit-BgoeahE5.d.mts → rate-limit-DQDk6bAH.d.mts} +5 -5
- package/dist/rate-limit-DQDk6bAH.d.mts.map +1 -0
- package/dist/reply-BVdki3Z4.mjs +12 -0
- package/dist/reply-BVdki3Z4.mjs.map +1 -0
- package/dist/{request-id-CVzJ1uHD.d.mts → request-id-Dn64nEHK.d.mts} +3 -3
- package/dist/request-id-Dn64nEHK.d.mts.map +1 -0
- package/dist/request-scope-BTdpkAqv.mjs +12 -0
- package/dist/request-scope-BTdpkAqv.mjs.map +1 -0
- package/dist/{respond-Ius0bnxZ.mjs → respond-BUWP_L0Y.mjs} +2 -2
- package/dist/{respond-Ius0bnxZ.mjs.map → respond-BUWP_L0Y.mjs.map} +1 -1
- package/dist/rolldown-runtime-Dp0gGuQG.mjs +11 -0
- package/dist/{route-flag-BP_jbhNy.mjs → route-flag-p89Wzt0D.mjs} +3 -3
- package/dist/{route-flag-BP_jbhNy.mjs.map → route-flag-p89Wzt0D.mjs.map} +1 -1
- package/dist/{route-policy-BF1hOoUO.mjs → route-policy-DJMiiTrD.mjs} +2 -2
- package/dist/{route-policy-BF1hOoUO.mjs.map → route-policy-DJMiiTrD.mjs.map} +1 -1
- package/dist/{router-builder-BewIsj7V.d.mts → router-builder-BfbEdxew.d.mts} +2 -2
- package/dist/{router-builder-BewIsj7V.d.mts.map → router-builder-BfbEdxew.d.mts.map} +1 -1
- package/dist/{router-builder-CBjQNcUy.mjs → router-builder-dCWA4pdK.mjs} +3 -3
- package/dist/{router-builder-CBjQNcUy.mjs.map → router-builder-dCWA4pdK.mjs.map} +1 -1
- package/dist/{session-ChXx7jG5.d.mts → session-8uNRCplB.d.mts} +3 -3
- package/dist/session-8uNRCplB.d.mts.map +1 -0
- package/dist/{settings-DlZtVJ3I.mjs → settings-BHYpcj_p.mjs} +3 -3
- package/dist/{settings-DlZtVJ3I.mjs.map → settings-BHYpcj_p.mjs.map} +1 -1
- package/dist/{token-9VtCdkUp.mjs → token-Cz4YKuL-.mjs} +1 -1
- package/dist/upload-Jgs9BFC4.d.mts +55 -0
- package/dist/upload-Jgs9BFC4.d.mts.map +1 -0
- package/dist/{upload-config-DYr3a8LW.mjs → upload-config-CkMQ5bW5.mjs} +2 -2
- package/dist/upload-config-CkMQ5bW5.mjs.map +1 -0
- package/dist/{url-for-Cci2zH9d.mjs → url-for-CDxa8ik-.mjs} +3 -3
- package/dist/{url-for-Cci2zH9d.mjs.map → url-for-CDxa8ik-.mjs.map} +1 -1
- package/dist/{validate-CzjCbRUn.d.mts → validate-D4Poe2EE.d.mts} +3 -3
- package/dist/validate-D4Poe2EE.d.mts.map +1 -0
- package/dist/{web-crypto-CWrgn2Yq.mjs → web-crypto-Bijc63tB.mjs} +2 -2
- package/dist/{web-crypto-CWrgn2Yq.mjs.map → web-crypto-Bijc63tB.mjs.map} +1 -1
- package/dist/web.d.mts +3 -3
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +8 -1
- package/dist/adapter-BZ1WzN1z.d.mts.map +0 -1
- package/dist/allowed-hosts-D6qcuK5I.d.mts.map +0 -1
- package/dist/application-D5Iiy7rt.d.mts.map +0 -1
- package/dist/application-DtuQSky3.mjs +0 -14
- package/dist/application-DtuQSky3.mjs.map +0 -1
- package/dist/bootstrap-B_6QfzXV.mjs +0 -12
- package/dist/breach-padding-C-Dnq8CS.d.mts.map +0 -1
- package/dist/context-p-KpSsLy.mjs +0 -12
- package/dist/context-p-KpSsLy.mjs.map +0 -1
- package/dist/core-CSWR0hHJ.mjs +0 -12
- package/dist/cors-2Bwhyhpt.d.mts.map +0 -1
- package/dist/csrf-BDAZK2mm.d.mts.map +0 -1
- package/dist/decorate-D2oVJls5.mjs +0 -13
- package/dist/handler-D23bJ6g1.mjs +0 -12
- package/dist/helmet-CEOmo516.d.mts.map +0 -1
- package/dist/lazy-serve-static-BNM_5G_r.mjs +0 -12
- package/dist/lazy-serve-static-BNM_5G_r.mjs.map +0 -1
- package/dist/rate-limit-BgoeahE5.d.mts.map +0 -1
- package/dist/reply-C1CoxeQt.mjs +0 -12
- package/dist/reply-C1CoxeQt.mjs.map +0 -1
- package/dist/request-id-CVzJ1uHD.d.mts.map +0 -1
- package/dist/session-ChXx7jG5.d.mts.map +0 -1
- package/dist/upload-DkT2p1gd.d.mts +0 -104
- package/dist/upload-DkT2p1gd.d.mts.map +0 -1
- package/dist/upload-config-DYr3a8LW.mjs.map +0 -1
- package/dist/validate-CzjCbRUn.d.mts.map +0 -1
|
@@ -1,26 +1,22 @@
|
|
|
1
1
|
|
|
2
2
|
import { i as SettingsDeclaration, s as VarOrigin, t as ConfigVar } from "./settings-BnE75hnr.mjs";
|
|
3
3
|
import "./index-B4aOLoId.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { E as RequestContext, K as AdapterFactory, Ot as KickPlugin, Rt as ResponseInfo, U as UrlForArgs, Ut as ConditionOutcome, V as RouteName, a as KickServer, b as RuntimeCapabilities, c as ActiveRuntime, d as HttpRuntime, h as RouteEntry, kt as ModuleRegistry, m as RouteContributor, r as AppAdapter, x as RuntimeResponse, xt as ModuleFactory } from "./adapter-9sPr_5xt.mjs";
|
|
5
|
+
import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse } from "./connect-BlIamapT.mjs";
|
|
5
6
|
import { t as Container } from "./container-4iJdDkRH.mjs";
|
|
6
7
|
import { p as RouteFlags, s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
|
|
7
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";
|
|
8
|
-
import { l as PlatformContext, m as Reply } from "./kv-stores-
|
|
9
|
-
import "./
|
|
10
|
-
import { t as ValidationErrorFactory } from "./validate-
|
|
11
|
-
import { t as AllowedHostsOptions } from "./allowed-hosts-
|
|
12
|
-
import { t as BuildRoutesOptions } from "./router-builder-
|
|
13
|
-
import "./
|
|
14
|
-
import "./
|
|
15
|
-
import "./
|
|
16
|
-
import "./helmet-CEOmo516.mjs";
|
|
17
|
-
import "./breach-padding-C-Dnq8CS.mjs";
|
|
18
|
-
import "./cors-2Bwhyhpt.mjs";
|
|
19
|
-
import "./rate-limit-BgoeahE5.mjs";
|
|
20
|
-
import "./upload-DkT2p1gd.mjs";
|
|
9
|
+
import { l as PlatformContext, m as Reply } from "./kv-stores-C1sQs2Rb.mjs";
|
|
10
|
+
import { t as ComputedRef } from "./reactivity-BkMNA0kp.mjs";
|
|
11
|
+
import { t as ValidationErrorFactory } from "./validate-D4Poe2EE.mjs";
|
|
12
|
+
import { t as AllowedHostsOptions } from "./allowed-hosts-BpKwviq5.mjs";
|
|
13
|
+
import { t as BuildRoutesOptions } from "./router-builder-BfbEdxew.mjs";
|
|
14
|
+
import "./error-handler-CH4PPZCK.mjs";
|
|
15
|
+
import "./csrf-ZFOrJZhJ.mjs";
|
|
16
|
+
import "./upload-Jgs9BFC4.mjs";
|
|
21
17
|
import http, { IncomingMessage, ServerResponse } from "node:http";
|
|
18
|
+
import https from "node:https";
|
|
22
19
|
import tls from "node:tls";
|
|
23
|
-
import { Express, NextFunction, Request as Request$1, RequestHandler, Response as Response$1, Router } from "express";
|
|
24
20
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
25
21
|
//#region src/core/kick-error.d.ts
|
|
26
22
|
/**
|
|
@@ -465,6 +461,12 @@ interface MetricsOptions {
|
|
|
465
461
|
token?: string;
|
|
466
462
|
/** Histogram buckets, in seconds. Default: Prometheus' defaults, 5ms to 10s. */
|
|
467
463
|
buckets?: number[];
|
|
464
|
+
/**
|
|
465
|
+
* Serve the metrics on the management port (`bootstrap({ management: { port } })`)
|
|
466
|
+
* instead of the app's — reachable by the scraper, not the public. Without a
|
|
467
|
+
* management port it stays on the app's.
|
|
468
|
+
*/
|
|
469
|
+
management?: boolean;
|
|
468
470
|
}
|
|
469
471
|
/** The request histogram, keyed by its label set. */
|
|
470
472
|
declare class RequestHistogram {
|
|
@@ -767,31 +769,20 @@ interface Signer {
|
|
|
767
769
|
/** Create a signer for one purpose. */
|
|
768
770
|
declare function createSigner(options: SignerOptions): Signer;
|
|
769
771
|
//#endregion
|
|
770
|
-
//#region src/http/runtimes/express.d.ts
|
|
772
|
+
//#region src/http/runtimes/express-lazy.d.ts
|
|
773
|
+
/** The default HTTP runtime; Express loads on the Application's first setup. */
|
|
774
|
+
declare function expressRuntime(): HttpRuntime;
|
|
771
775
|
/**
|
|
772
|
-
* Materialize
|
|
773
|
-
*
|
|
774
|
-
* `(ctx, next)` middleware → contributor runner → terminal handler, with
|
|
775
|
-
* `beforeValidation` contributors ahead of validation. Each step
|
|
776
|
-
* constructs its own `RequestContext` over the same `req`/`res` — request-scoped
|
|
777
|
-
* state lives in the AsyncLocalStorage store, not on the ctx instance, so the
|
|
778
|
-
* per-step instances share state exactly as before.
|
|
776
|
+
* Materialize route entries onto an Express `Router`, built on the first
|
|
777
|
+
* request (Express has loaded by then in an app running it).
|
|
779
778
|
*/
|
|
780
|
-
declare function materializeRouter(entries: RouteEntry[]):
|
|
779
|
+
declare function materializeRouter(entries: RouteEntry[]): ConnectHandler;
|
|
781
780
|
/**
|
|
782
|
-
*
|
|
783
|
-
*
|
|
784
|
-
*
|
|
785
|
-
* `express.Router` exactly as before — modules pass it to `app.use(path, router)`.
|
|
786
|
-
*
|
|
787
|
-
* @see buildRouteTable for the engine-neutral route-table form.
|
|
781
|
+
* A controller's routes as an Express `Router`. The route table is built now,
|
|
782
|
+
* so a contributor cycle or a missing dependency still fails at boot; the
|
|
783
|
+
* router on the first request.
|
|
788
784
|
*/
|
|
789
|
-
declare function buildRoutes(controllerClass: any, options?: BuildRoutesOptions):
|
|
790
|
-
/**
|
|
791
|
-
* The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;
|
|
792
|
-
* apps that pass no `runtime` get this and behave exactly as before.
|
|
793
|
-
*/
|
|
794
|
-
declare function expressRuntime(): HttpRuntime<Express>;
|
|
785
|
+
declare function buildRoutes(controllerClass: any, options?: BuildRoutesOptions): ConnectHandler;
|
|
795
786
|
//#endregion
|
|
796
787
|
//#region src/http/request-store.d.ts
|
|
797
788
|
/** Per-request storage for REQUEST-scoped DI and request context propagation */
|
|
@@ -872,7 +863,7 @@ declare function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K>
|
|
|
872
863
|
* `Application` mounts this automatically unless `contextStore: 'manual'` is set
|
|
873
864
|
* or the user already includes one in their middleware list.
|
|
874
865
|
*/
|
|
875
|
-
declare function requestScopeMiddleware(): (req:
|
|
866
|
+
declare function requestScopeMiddleware(): (req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => void;
|
|
876
867
|
//#endregion
|
|
877
868
|
//#region src/http/middleware/trace-context.d.ts
|
|
878
869
|
/**
|
|
@@ -926,7 +917,7 @@ declare function parseTraceparent(header: string): TraceContext | null;
|
|
|
926
917
|
* })
|
|
927
918
|
* ```
|
|
928
919
|
*/
|
|
929
|
-
declare function traceContext(options?: TraceContextOptions): (req:
|
|
920
|
+
declare function traceContext(options?: TraceContextOptions): (req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => void;
|
|
930
921
|
//#endregion
|
|
931
922
|
//#region src/http/middleware/views.d.ts
|
|
932
923
|
interface ViewAdapterOptions {
|
|
@@ -1141,6 +1132,8 @@ interface HealthCheckResult {
|
|
|
1141
1132
|
interface HealthProbe {
|
|
1142
1133
|
/** True once shutdown has begun and traffic should drain away. */
|
|
1143
1134
|
isDraining(): boolean;
|
|
1135
|
+
/** True while the app is still starting — before it serves. */
|
|
1136
|
+
isStarting?(): boolean;
|
|
1144
1137
|
/** Aggregated `onHealthCheck()` results from every adapter that has one. */
|
|
1145
1138
|
checks(): Promise<HealthCheckResult[]>;
|
|
1146
1139
|
}
|
|
@@ -1207,9 +1200,9 @@ declare const healthModule: ModuleFactory<HealthModuleConfig, unknown>;
|
|
|
1207
1200
|
* A middleware entry in the declarative pipeline.
|
|
1208
1201
|
* Can be a bare handler or an object with path scoping.
|
|
1209
1202
|
*/
|
|
1210
|
-
type MiddlewareEntry =
|
|
1203
|
+
type MiddlewareEntry = ConnectHandler | {
|
|
1211
1204
|
path: string;
|
|
1212
|
-
handler:
|
|
1205
|
+
handler: ConnectHandler;
|
|
1213
1206
|
};
|
|
1214
1207
|
/** Options for {@link Application.shutdown}. */
|
|
1215
1208
|
interface ShutdownOptions {
|
|
@@ -1243,12 +1236,17 @@ interface ServerOptions {
|
|
|
1243
1236
|
/** A mounted controller route, as `app.getRoutes()` lists it. */
|
|
1244
1237
|
interface MountedRouteInfo {
|
|
1245
1238
|
method: string;
|
|
1246
|
-
/** Full pattern, prefix and version included: `/api/v1/users/:id`. */
|
|
1239
|
+
/** Full pattern, prefix and version included: `/api/v1/users/:id`. Static files: `/assets/*`. */
|
|
1247
1240
|
pattern: string;
|
|
1241
|
+
/** The controller — or, for a route an adapter added, the adapter's name. */
|
|
1248
1242
|
controller: string;
|
|
1249
1243
|
handler: string;
|
|
1250
1244
|
/** Context contributors in execution order, with where each was registered. */
|
|
1251
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';
|
|
1252
1250
|
}
|
|
1253
1251
|
/** What `app.describeConfig()` returns. */
|
|
1254
1252
|
interface ConfigDescription {
|
|
@@ -1330,6 +1328,22 @@ interface ApplicationOptions {
|
|
|
1330
1328
|
* ```
|
|
1331
1329
|
*/
|
|
1332
1330
|
server?: ServerOptions;
|
|
1331
|
+
/**
|
|
1332
|
+
* Serve operational endpoints on a second port — the same app and container,
|
|
1333
|
+
* a second listener, like Spring Boot's `management.server.port`. `/health/live`
|
|
1334
|
+
* and `/health/ready` move there, off the public port, along with whatever
|
|
1335
|
+
* adapters register on `AdapterContext.management` (DevTools with
|
|
1336
|
+
* `DevToolsAdapter({ management: true })`). The management port skips the
|
|
1337
|
+
* app's middleware, and keeps answering while the public port drains.
|
|
1338
|
+
*
|
|
1339
|
+
* Off by default. Ignored in dev mode (Vite owns the only server) and in
|
|
1340
|
+
* handler mode (serverless), where everything stays on the one entry.
|
|
1341
|
+
*
|
|
1342
|
+
* ```ts
|
|
1343
|
+
* bootstrap({ modules, management: { port: 9090 } })
|
|
1344
|
+
* ```
|
|
1345
|
+
*/
|
|
1346
|
+
management?: ManagementOptions;
|
|
1333
1347
|
/** Global API prefix (default: '/api'). Pass `''` to mount at the root. */
|
|
1334
1348
|
apiPrefix?: string;
|
|
1335
1349
|
/**
|
|
@@ -1685,6 +1699,26 @@ interface ApplicationOptions {
|
|
|
1685
1699
|
* ```
|
|
1686
1700
|
*/
|
|
1687
1701
|
declare const APPLICATION: import("@forinda/kickjs-di").InjectionToken<Application>;
|
|
1702
|
+
/** {@link Application.status}. */
|
|
1703
|
+
type AppStatus = 'idle' | 'starting' | 'ready' | 'draining' | 'stopped';
|
|
1704
|
+
/** {@link ApplicationOptions.management}. */
|
|
1705
|
+
interface ManagementOptions {
|
|
1706
|
+
/** Port for the management listener. */
|
|
1707
|
+
port: number;
|
|
1708
|
+
/**
|
|
1709
|
+
* Interface to bind. Default: every interface, like the public port — an
|
|
1710
|
+
* orchestrator probes the pod's address, so `127.0.0.1` would fail its
|
|
1711
|
+
* probes. Narrow it with a network policy, or bind an internal address.
|
|
1712
|
+
*/
|
|
1713
|
+
host?: string;
|
|
1714
|
+
/**
|
|
1715
|
+
* Serve the management port over HTTPS — same shape as `server.tls`. Off by
|
|
1716
|
+
* default: the port is meant for an internal network. Set it when anything
|
|
1717
|
+
* that crosses that network carries a credential (a DevTools token, an
|
|
1718
|
+
* admin route's bearer token).
|
|
1719
|
+
*/
|
|
1720
|
+
tls?: tls.SecureContextOptions & tls.TlsOptions;
|
|
1721
|
+
}
|
|
1688
1722
|
declare class Application {
|
|
1689
1723
|
private readonly options;
|
|
1690
1724
|
private app;
|
|
@@ -1692,6 +1726,14 @@ declare class Application {
|
|
|
1692
1726
|
private readonly runtime;
|
|
1693
1727
|
private container;
|
|
1694
1728
|
private httpServer;
|
|
1729
|
+
/**
|
|
1730
|
+
* `bootstrap({ management })`: its engine app, created by start() outside dev
|
|
1731
|
+
* mode — whatever `runtime` builds (Express, Fastify, h3), so not typed as one.
|
|
1732
|
+
*/
|
|
1733
|
+
private managementApp;
|
|
1734
|
+
private managementServer;
|
|
1735
|
+
/** Set by start() when `management` applies; setup() then creates the management app. */
|
|
1736
|
+
private wantsManagement;
|
|
1695
1737
|
/** Set by startWithoutServer() — the serverless path, where cron runs over HTTP. */
|
|
1696
1738
|
private handlerMode;
|
|
1697
1739
|
/** The observer set this app installed — released on shutdown only if still current. */
|
|
@@ -1737,7 +1779,15 @@ declare class Application {
|
|
|
1737
1779
|
/** Number of HTTP requests currently being processed */
|
|
1738
1780
|
private _inFlightRequests;
|
|
1739
1781
|
/** Whether the application is draining (shutting down gracefully) */
|
|
1740
|
-
private
|
|
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>;
|
|
1741
1791
|
/** Whether shutdown has already been initiated (prevents double-shutdown) */
|
|
1742
1792
|
private _shutdownInitiated;
|
|
1743
1793
|
/** Resolvers waiting for in-flight requests to reach zero */
|
|
@@ -1878,6 +1928,12 @@ declare class Application {
|
|
|
1878
1928
|
* (it receives the `http.Server`), and no process signal handlers.
|
|
1879
1929
|
*/
|
|
1880
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;
|
|
1881
1937
|
/**
|
|
1882
1938
|
* Start the HTTP server.
|
|
1883
1939
|
*
|
|
@@ -1888,6 +1944,12 @@ declare class Application {
|
|
|
1888
1944
|
* In **production**: creates its own `http.Server` and binds to the port.
|
|
1889
1945
|
*/
|
|
1890
1946
|
start(): Promise<void>;
|
|
1947
|
+
private startSteps;
|
|
1948
|
+
/** Listen on the public port, then run afterStart and onReady. */
|
|
1949
|
+
private listenAndFinishStartup;
|
|
1950
|
+
private closeManagementServer;
|
|
1951
|
+
/** The management listener: on its own port, before the public one; HTTPS with `tls`. */
|
|
1952
|
+
private listenManagement;
|
|
1891
1953
|
/** The production server for {@link ApplicationOptions.server}. */
|
|
1892
1954
|
private createNodeServer;
|
|
1893
1955
|
private createBareServer;
|
|
@@ -1923,7 +1985,7 @@ declare class Application {
|
|
|
1923
1985
|
capabilities: RuntimeCapabilities;
|
|
1924
1986
|
};
|
|
1925
1987
|
/** @deprecated Use {@link getRuntimeApp}. Returns the engine-native app. */
|
|
1926
|
-
getExpressApp():
|
|
1988
|
+
getExpressApp(): ActiveRuntime['app'];
|
|
1927
1989
|
/** Get registered adapters — used by DevToolsAdapter for peer discovery */
|
|
1928
1990
|
getAdapters(): AppAdapter[];
|
|
1929
1991
|
/**
|
|
@@ -1963,6 +2025,12 @@ declare class Application {
|
|
|
1963
2025
|
dependsOn: readonly string[];
|
|
1964
2026
|
}>;
|
|
1965
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;
|
|
1966
2034
|
/**
|
|
1967
2035
|
* Decide whether {@link Application} should auto-mount the
|
|
1968
2036
|
* {@link requestScopeMiddleware} ALS wrapper.
|
|
@@ -1991,6 +2059,11 @@ declare class Application {
|
|
|
1991
2059
|
/** Middleware that tracks in-flight requests for graceful draining */
|
|
1992
2060
|
private requestTrackingMiddleware;
|
|
1993
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[];
|
|
1994
2067
|
//#endregion
|
|
1995
|
-
export {
|
|
1996
|
-
//# sourceMappingURL=application-
|
|
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;;;;;cAM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BAAkB;;;;;;;EA4BlB,iBAAiB;;UAaT;;UAYA;;UAUA;EAUF,SAAS;;EA8fT,gBAAgB;;;;;;;;;EAYhB,sBAAsB;;;;;UAQd;UASA;;;;;;;;;;EAmCR,SAAS;UAID;;UAyFA;UAwCA;;UAWA;;UAwBN;UAeA;;EAkBF,WAAW;;;;;;;;;;;EAuDX,SAAS,UAAS,kBAAuB;;;;;;;EAkM/C,iBAAiB;;;;;;;;EAWjB;IAAsB;IAAc,cAAc;;;EAKlD,iBAAiB;;EAKjB,eAAe;;;;;;EASf,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;EA2BvB,sBAAsB;EAItB,mBAAmB;IACjB;IACA;IACA;IACA;;EA+DF,iBAAiB;;;;;;EASjB,uBAAuB,KAAK,SAAS,MAAM;;;;;;;;;;;;;;UAmBnC;UAWA;UAmBA;UAUA;;;;;;;;UAeA;;UAoBA;;;;;;iBAgDM,eAAe,iBAAiB"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v10.7.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{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
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v10.7.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{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-B_6QfzXV.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":";;;;;;;;;;qnBAmCA,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,OAAO,iGAEjB,EACA,MACF,CAEA,IAAM,KAAO,IAAc,UAAiC,CAE1D,IAAM,EAAI,WAAW,IAAK,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AqB,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,CAAC,CAA0B,IACzD,MAAQ,CACN,MACF,CACF,CAGA,SAAS,eAAyB,CAChC,MAAO,CAAC,QA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AAM,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.
|
|
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-
|
|
12
|
+
//# sourceMappingURL=bounded-counters-_6sdDRhT.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bounded-counters-
|
|
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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K,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
|
-
import {
|
|
2
|
+
import { a as ConnectRequest, i as ConnectNext, o as ConnectResponse } from "./connect-BlIamapT.mjs";
|
|
3
3
|
//#region src/http/middleware/breach-padding.d.ts
|
|
4
4
|
interface BreachPaddingOptions {
|
|
5
5
|
/**
|
|
@@ -33,7 +33,7 @@ declare function padGzipHeader(chunk: Uint8Array, maxBytes: number): Uint8Array;
|
|
|
33
33
|
* get gzip, and the padding applies. Not for the web entry: Netlify, Vercel
|
|
34
34
|
* and Cloudflare compress at the edge.
|
|
35
35
|
*/
|
|
36
|
-
declare function breachPadding(options?: BreachPaddingOptions): (req:
|
|
36
|
+
declare function breachPadding(options?: BreachPaddingOptions): (req: ConnectRequest, res: ConnectResponse, next: ConnectNext) => void;
|
|
37
37
|
//#endregion
|
|
38
38
|
export { breachPadding as n, padGzipHeader as r, BreachPaddingOptions as t };
|
|
39
|
-
//# sourceMappingURL=breach-padding-
|
|
39
|
+
//# sourceMappingURL=breach-padding-FBVGmcBb.d.mts.map
|