@forinda/kickjs 10.10.0 → 10.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/dist/{adapter-DLjn8q0c.d.mts → adapter-DiJfCKXU.d.mts} +27 -8
  2. package/dist/adapter-DiJfCKXU.d.mts.map +1 -0
  3. package/dist/{application-DLRHEOeg.mjs → application-BCXdtJd1.mjs} +3 -3
  4. package/dist/{application-DLRHEOeg.mjs.map → application-BCXdtJd1.mjs.map} +1 -1
  5. package/dist/{application-CdUI5E_3.d.mts → application-EinAcKLu.d.mts} +6 -6
  6. package/dist/{application-CdUI5E_3.d.mts.map → application-EinAcKLu.d.mts.map} +1 -1
  7. package/dist/{body-policy-DIgqprai.mjs → body-policy-DccDxmmR.mjs} +2 -2
  8. package/dist/{body-policy-DIgqprai.mjs.map → body-policy-DccDxmmR.mjs.map} +1 -1
  9. package/dist/bootstrap-C5op763j.mjs +12 -0
  10. package/dist/{bootstrap-6ltjueRe.mjs.map → bootstrap-C5op763j.mjs.map} +1 -1
  11. package/dist/{bounded-counters-Dxi2jekd.mjs → bounded-counters-CmmPOr2v.mjs} +2 -2
  12. package/dist/{bounded-counters-Dxi2jekd.mjs.map → bounded-counters-CmmPOr2v.mjs.map} +1 -1
  13. package/dist/{client-ip-dLKJKDZL.mjs → client-ip-STshfERA.mjs} +2 -2
  14. package/dist/{client-ip-dLKJKDZL.mjs.map → client-ip-STshfERA.mjs.map} +1 -1
  15. package/dist/config/index.mjs +2 -2
  16. package/dist/{config-BEoFtveu.mjs → config-DZd8tqGC.mjs} +3 -3
  17. package/dist/{config-BEoFtveu.mjs.map → config-DZd8tqGC.mjs.map} +1 -1
  18. package/dist/context-BJ6HVq4W.mjs +12 -0
  19. package/dist/context-BJ6HVq4W.mjs.map +1 -0
  20. package/dist/{context-errors-B2uJdmkX.mjs → context-errors-s1zG7eax.mjs} +2 -2
  21. package/dist/{context-errors-B2uJdmkX.mjs.map → context-errors-s1zG7eax.mjs.map} +1 -1
  22. package/dist/{contributor-runner-CaZkoZOK.mjs → contributor-runner-B5pv7_R-.mjs} +3 -3
  23. package/dist/{contributor-runner-CaZkoZOK.mjs.map → contributor-runner-B5pv7_R-.mjs.map} +1 -1
  24. package/dist/core/adapter.d.mts +1 -1
  25. package/dist/core/adapter.mjs +1 -1
  26. package/dist/core/app-module.mjs +1 -1
  27. package/dist/core/cache.mjs +1 -1
  28. package/dist/core/container.mjs +2 -2
  29. package/dist/core/cron.mjs +2 -2
  30. package/dist/core/decorators.mjs +2 -2
  31. package/dist/core/errors.mjs +1 -1
  32. package/dist/core/interfaces.mjs +1 -1
  33. package/dist/core/logger.mjs +1 -1
  34. package/dist/core/path.mjs +1 -1
  35. package/dist/core/plugin.d.mts +1 -1
  36. package/dist/core/plugin.mjs +1 -1
  37. package/dist/core/reactivity.mjs +2 -2
  38. package/dist/{core-MyOlkejk.mjs → core-Cf6gPv9R.mjs} +3 -3
  39. package/dist/{core-MyOlkejk.mjs.map → core-Cf6gPv9R.mjs.map} +1 -1
  40. package/dist/{decorate-CU19-7Fw.mjs → decorate-BQA6M9jq.mjs} +3 -3
  41. package/dist/{decorate-CU19-7Fw.mjs.map → decorate-BQA6M9jq.mjs.map} +1 -1
  42. package/dist/{define-adapter-1FfgX1AQ.mjs → define-adapter-B9DcBJKt.mjs} +2 -2
  43. package/dist/{define-adapter-1FfgX1AQ.mjs.map → define-adapter-B9DcBJKt.mjs.map} +1 -1
  44. package/dist/{di-hooks-DX9rJX_0.mjs → di-hooks-DGmtRWDI.mjs} +2 -2
  45. package/dist/{di-hooks-DX9rJX_0.mjs.map → di-hooks-DGmtRWDI.mjs.map} +1 -1
  46. package/dist/{disposables-Bq6gIO7N.mjs → disposables-C1xhXyD6.mjs} +1 -1
  47. package/dist/{error-handler-BrihKETE.d.mts → error-handler-OfxVJX3s.d.mts} +2 -2
  48. package/dist/{error-handler-BrihKETE.d.mts.map → error-handler-OfxVJX3s.d.mts.map} +1 -1
  49. package/dist/{express-BBhisCna.mjs → express-DqWsJylQ.mjs} +3 -3
  50. package/dist/{express-BBhisCna.mjs.map → express-DqWsJylQ.mjs.map} +1 -1
  51. package/dist/{express-lazy-Pua2eR0n.mjs → express-lazy-CdPN1krb.mjs} +3 -3
  52. package/dist/{express-lazy-Pua2eR0n.mjs.map → express-lazy-CdPN1krb.mjs.map} +1 -1
  53. package/dist/handler-Ce16qhGr.mjs +12 -0
  54. package/dist/{handler-C_mWEafU.mjs.map → handler-Ce16qhGr.mjs.map} +1 -1
  55. package/dist/{host-d9X0p13s.mjs → host-BZcjkJ-A.mjs} +2 -2
  56. package/dist/{host-d9X0p13s.mjs.map → host-BZcjkJ-A.mjs.map} +1 -1
  57. package/dist/http/application.d.mts +1 -1
  58. package/dist/http/application.mjs +2 -2
  59. package/dist/http/bootstrap.d.mts +1 -1
  60. package/dist/http/bootstrap.mjs +2 -2
  61. package/dist/http/context.d.mts +1 -1
  62. package/dist/http/context.mjs +2 -2
  63. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  64. package/dist/http/middleware/breach-padding.mjs +1 -1
  65. package/dist/http/middleware/cors.mjs +1 -1
  66. package/dist/http/middleware/csrf.mjs +2 -2
  67. package/dist/http/middleware/error-handler.d.mts +1 -1
  68. package/dist/http/middleware/error-handler.mjs +2 -2
  69. package/dist/http/middleware/helmet.mjs +1 -1
  70. package/dist/http/middleware/rate-limit.mjs +2 -2
  71. package/dist/http/middleware/request-id.mjs +1 -1
  72. package/dist/http/middleware/request-logger.mjs +2 -2
  73. package/dist/http/middleware/session.mjs +2 -2
  74. package/dist/http/middleware/spa.d.mts +1 -1
  75. package/dist/http/middleware/spa.mjs +2 -2
  76. package/dist/http/middleware/upload.d.mts +2 -2
  77. package/dist/http/middleware/upload.mjs +2 -2
  78. package/dist/http/middleware/validate.mjs +1 -1
  79. package/dist/http/middleware/views.d.mts +1 -1
  80. package/dist/http/middleware/views.mjs +2 -2
  81. package/dist/http/query/index.mjs +2 -2
  82. package/dist/http/router-builder.d.mts +1 -1
  83. package/dist/http/router-builder.mjs +2 -2
  84. package/dist/http/runtimes/express.d.mts +2 -2
  85. package/dist/http/runtimes/express.mjs +2 -2
  86. package/dist/http/runtimes/fastify.d.mts +1 -1
  87. package/dist/http/runtimes/fastify.mjs +2 -2
  88. package/dist/http/runtimes/fastify.mjs.map +1 -1
  89. package/dist/http/runtimes/h3-web.mjs +1 -1
  90. package/dist/http/runtimes/h3.d.mts +1 -1
  91. package/dist/http/runtimes/h3.d.mts.map +1 -1
  92. package/dist/http/runtimes/h3.mjs +2 -2
  93. package/dist/http/runtimes/h3.mjs.map +1 -1
  94. package/dist/index.d.mts +7 -7
  95. package/dist/index.mjs +3 -3
  96. package/dist/index.mjs.map +1 -1
  97. package/dist/{is-production-BYwEumHI.mjs → is-production-et6gyyxF.mjs} +2 -2
  98. package/dist/{is-production-BYwEumHI.mjs.map → is-production-et6gyyxF.mjs.map} +1 -1
  99. package/dist/{jobs-bGtYcSgo.mjs → jobs-B4wle0iS.mjs} +3 -3
  100. package/dist/{jobs-bGtYcSgo.mjs.map → jobs-B4wle0iS.mjs.map} +1 -1
  101. package/dist/{kv-stores-DJBnGQsJ.d.mts → kv-stores-BN7c9bt9.d.mts} +2 -2
  102. package/dist/{kv-stores-DJBnGQsJ.d.mts.map → kv-stores-BN7c9bt9.d.mts.map} +1 -1
  103. package/dist/{kv-stores-DbM-V83V.mjs → kv-stores-CLR0N5im.mjs} +3 -3
  104. package/dist/{kv-stores-DbM-V83V.mjs.map → kv-stores-CLR0N5im.mjs.map} +1 -1
  105. package/dist/{lazy-serve-static-Dp3lqSlT.mjs → lazy-serve-static-CKaL8clq.mjs} +3 -3
  106. package/dist/{lazy-serve-static-Dp3lqSlT.mjs.map → lazy-serve-static-CKaL8clq.mjs.map} +1 -1
  107. package/dist/{metadata-BvNkZphr.mjs → metadata-CsfVw6pp.mjs} +1 -1
  108. package/dist/{observers-Bjs-1F1Z.mjs → observers-BbNYzGfC.mjs} +2 -2
  109. package/dist/{observers-Bjs-1F1Z.mjs.map → observers-BbNYzGfC.mjs.map} +1 -1
  110. package/dist/{precompressed-Cydk_Bpr.mjs → precompressed-BTEVCjT_.mjs} +2 -2
  111. package/dist/{precompressed-Cydk_Bpr.mjs.map → precompressed-BTEVCjT_.mjs.map} +1 -1
  112. package/dist/{query-BEnIVY7Q.mjs → query-EQM3lEr_.mjs} +2 -2
  113. package/dist/{query-BEnIVY7Q.mjs.map → query-EQM3lEr_.mjs.map} +1 -1
  114. package/dist/reply-Detphot1.mjs +12 -0
  115. package/dist/reply-Detphot1.mjs.map +1 -0
  116. package/dist/request-scope-D5ggZdvq.mjs +12 -0
  117. package/dist/{request-scope-u_VhYe4-.mjs.map → request-scope-D5ggZdvq.mjs.map} +1 -1
  118. package/dist/{respond-C0NoT3br.mjs → respond-B_5BPAJp.mjs} +2 -2
  119. package/dist/{respond-C0NoT3br.mjs.map → respond-B_5BPAJp.mjs.map} +1 -1
  120. package/dist/{rolldown-runtime-D2dh8WuU.mjs → rolldown-runtime-BgeRdaSa.mjs} +1 -1
  121. package/dist/{route-flag-xPz2wbyz.mjs → route-flag-CO7wkxhn.mjs} +3 -3
  122. package/dist/{route-flag-xPz2wbyz.mjs.map → route-flag-CO7wkxhn.mjs.map} +1 -1
  123. package/dist/{route-policy-weZwvZYs.mjs → route-policy-DJd0iddt.mjs} +2 -2
  124. package/dist/{route-policy-weZwvZYs.mjs.map → route-policy-DJd0iddt.mjs.map} +1 -1
  125. package/dist/{router-builder-CPJHwoL1.d.mts → router-builder-DtGrng_X.d.mts} +2 -2
  126. package/dist/{router-builder-CPJHwoL1.d.mts.map → router-builder-DtGrng_X.d.mts.map} +1 -1
  127. package/dist/{router-builder-CnCNsI87.mjs → router-builder-DtjsnD0b.mjs} +3 -3
  128. package/dist/{router-builder-CnCNsI87.mjs.map → router-builder-DtjsnD0b.mjs.map} +1 -1
  129. package/dist/{settings-Ciut2k76.mjs → settings-CJWJPERr.mjs} +3 -3
  130. package/dist/{settings-Ciut2k76.mjs.map → settings-CJWJPERr.mjs.map} +1 -1
  131. package/dist/{token-CBe6OMQK.mjs → token-kfP7I0D6.mjs} +1 -1
  132. package/dist/{upload-DtQ1pdQw.d.mts → upload-C9IfY1aQ.d.mts} +2 -2
  133. package/dist/{upload-DtQ1pdQw.d.mts.map → upload-C9IfY1aQ.d.mts.map} +1 -1
  134. package/dist/{upload-config-d_LW2u9b.mjs → upload-config-DldXNOHe.mjs} +2 -2
  135. package/dist/{upload-config-d_LW2u9b.mjs.map → upload-config-DldXNOHe.mjs.map} +1 -1
  136. package/dist/{url-for-Df_ts-iM.mjs → url-for-O-DQnRvH.mjs} +3 -3
  137. package/dist/{url-for-Df_ts-iM.mjs.map → url-for-O-DQnRvH.mjs.map} +1 -1
  138. package/dist/{background-CiKEgaD2.mjs → view-renderer-NbkTobFF.mjs} +3 -3
  139. package/dist/view-renderer-NbkTobFF.mjs.map +1 -0
  140. package/dist/{web-crypto-BNF60ZAh.mjs → web-crypto-BNP8o7BF.mjs} +2 -2
  141. package/dist/{web-crypto-BNF60ZAh.mjs.map → web-crypto-BNP8o7BF.mjs.map} +1 -1
  142. package/dist/web.d.mts +2 -2
  143. package/dist/web.d.mts.map +1 -1
  144. package/dist/web.mjs +2 -2
  145. package/dist/web.mjs.map +1 -1
  146. package/package.json +1 -1
  147. package/dist/adapter-DLjn8q0c.d.mts.map +0 -1
  148. package/dist/background-CiKEgaD2.mjs.map +0 -1
  149. package/dist/bootstrap-6ltjueRe.mjs +0 -12
  150. package/dist/context-BPszif4a.mjs +0 -12
  151. package/dist/context-BPszif4a.mjs.map +0 -1
  152. package/dist/handler-C_mWEafU.mjs +0 -12
  153. package/dist/reply-CGn9BmYj.mjs +0 -12
  154. package/dist/reply-CGn9BmYj.mjs.map +0 -1
  155. package/dist/request-scope-u_VhYe4-.mjs +0 -12
package/dist/index.d.mts CHANGED
@@ -3,32 +3,32 @@ import { a as isInjectionToken, i as ctn, n as InjectionToken, r as createToken,
3
3
  import { a as SettingsOf, c as defineSettings, i as SettingsDeclaration, l as loadSettings, n as ProvidedSettings, o as ValueOrigin, r as Settings, s as VarOrigin, t as ConfigVar, u as originsOf } from "./settings-BFQisfqG.mjs";
4
4
  import { A as Service, B as resolveAsset, C as Post, D as Put, F as ASSET_MANIFEST_VERSION, I as KickAssets, L as UnknownAssetError, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, P as ASSETS, R as assets, S as Patch, T as PreDestroy, V as useAssets, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable, z as clearAssetCache } from "./decorators-DxNb5mWw.mjs";
5
5
  import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, f as withEnv, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "./index-CNBYZDto.mjs";
6
- import { $ as ContributorSource, At as MutableModuleRegistry, B as ROUTE_URLS, Bt as reportResponse, C as UseConnectOptions, Ct as BuildContext, D as RouteShape, Dt as definePlugin, E as RequestContext, Et as PluginFactory, Ft as IntrospectionSnapshot, G as AdapterAsyncOptions, Gt as onEnv, H as UrlBuilder, Ht as AdapterCondition, I as resolveMimeTypes, It as ErrorInfo, J as defineAdapter, K as AdapterFactory, Kt as onPackage, L as ConditionalOutcome, Lt as ErrorSource, M as UploadedFile, Mt as KickJsPluginRegistry, Nt as IntrospectFn, O as SseHandler, Ot as KickPlugin, Pt as IntrospectionKind, Q as ContributorPipeline, R as Validators, Rt as ResponseInfo, S as RuntimeTypeMap, St as defineModule, T as DeepReadonly, Tt as PluginAsyncOptions, U as UrlForArgs, Ut as ConditionOutcome, V as RouteName, Vt as FailureAdvice, W as UrlQuery, Wt as allOf, X as runContributors, Y as RunContributorsOptions, Z as BuildPipelineOptions, _ as RouteMethod, _t as registerDisposable, a as KickServer, at as getMetaRecord, b as RuntimeCapabilities, bt as DefineModuleOptions, c as ActiveRuntime, ct as hasClassMeta, d as HttpRuntime, dt as setClassMeta, et as SourcedRegistration, f as KickRuntimeRegister, ft as setInMetaMap, g as RouteMeta, gt as disposeAll, h as RouteEntry, ht as Disposable, i as AppAdapterClass, it as getMetaMap, j as UploadStorageEngine, jt as KickJsPluginName, kt as ModuleRegistry, l as AdapterHttp, lt as pushClassMeta, m as RouteContributor, mt as setMethodMeta, n as AdapterMiddleware, nt as getClassMeta, o as MiddlewarePath, ot as getMethodMeta, p as MatchedRoute, pt as setInMetaRecord, q as DefineAdapterOptions, r as AppAdapter, rt as getClassMetaOrUndefined, s as MiddlewarePhase, st as getMethodMetaOrUndefined, t as AdapterContext, tt as buildPipeline, u as CtxHandler, ut as pushMethodMeta, v as RouteTable, vt as ModuleList, w as Ctx, wt as DefinePluginOptions, x as RuntimeResponse, xt as ModuleFactory, y as RuntimeAppOptions, yt as defineModules, z as evaluatePreconditions, zt as reportError } from "./adapter-DLjn8q0c.mjs";
6
+ import { $ as defineAdapter, At as PluginAsyncOptions, B as ROUTE_URLS, Bt as IntrospectionSnapshot, C as UseConnectOptions, Ct as ModuleList, D as RouteShape, Dt as defineModule, E as RequestContext, Et as ModuleFactory, Ft as MutableModuleRegistry, G as VIEW_RENDERER, Gt as reportResponse, H as UrlBuilder, Ht as ErrorSource, I as resolveMimeTypes, It as KickJsPluginName, J as bindViewRenderer, Jt as ConditionOutcome, K as ViewRenderOptions, Kt as FailureAdvice, L as ConditionalOutcome, Lt as KickJsPluginRegistry, M as UploadedFile, Mt as definePlugin, Nt as KickPlugin, O as SseHandler, Ot as BuildContext, Pt as ModuleRegistry, Q as DefineAdapterOptions, R as Validators, Rt as IntrospectFn, S as RuntimeTypeMap, St as registerDisposable, T as DeepReadonly, Tt as DefineModuleOptions, U as UrlForArgs, Ut as ResponseInfo, V as RouteName, Vt as ErrorInfo, W as UrlQuery, Wt as reportError, X as AdapterAsyncOptions, Xt as onEnv, Y as viewRendererFor, Yt as allOf, Z as AdapterFactory, Zt as onPackage, _ as RouteMethod, _t as setInMetaMap, a as KickServer, at as SourcedRegistration, b as RuntimeCapabilities, bt as Disposable, c as ActiveRuntime, ct as getClassMetaOrUndefined, d as HttpRuntime, dt as getMethodMeta, et as RunContributorsOptions, f as KickRuntimeRegister, ft as getMethodMetaOrUndefined, g as RouteMeta, gt as setClassMeta, h as RouteEntry, ht as pushMethodMeta, i as AppAdapterClass, it as ContributorSource, j as UploadStorageEngine, jt as PluginFactory, kt as DefinePluginOptions, l as AdapterHttp, lt as getMetaMap, m as RouteContributor, mt as pushClassMeta, n as AdapterMiddleware, nt as BuildPipelineOptions, o as MiddlewarePath, ot as buildPipeline, p as MatchedRoute, pt as hasClassMeta, q as ViewRenderer, qt as AdapterCondition, r as AppAdapter, rt as ContributorPipeline, s as MiddlewarePhase, st as getClassMeta, t as AdapterContext, tt as runContributors, u as CtxHandler, ut as getMetaRecord, v as RouteTable, vt as setInMetaRecord, w as Ctx, wt as defineModules, x as RuntimeResponse, xt as disposeAll, y as RuntimeAppOptions, yt as setMethodMeta, z as evaluatePreconditions, zt as IntrospectionKind } from "./adapter-DiJfCKXU.mjs";
7
7
  import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse, r as ConnectMiddleware, t as ConnectErrorHandler } from "./connect-BlIamapT.mjs";
8
8
  import { a as tokenName, i as KickJsRegistry, n as ContainerChangeEvent, r as ContainerChangeListener, t as Container } from "./container-4iJdDkRH.mjs";
9
9
  import { _ as getRouteFlags, a as RouteFlagContext, c as RouteFlagName, d as RouteFlagTest, f as RouteFlagValue, g as defineRouteFlag, h as assertFlagTest, i as RouteFlag, l as RouteFlagPredicate, m as ValuedRouteFlag, n as KickRouteFlags, o as RouteFlagDeclaration, p as RouteFlags, r as NegatedRouteFlagName, s as RouteFlagDeclarations, t as BareRouteFlag, u as RouteFlagRecord, v as matchesFlagTest, y as resolveRouteFlags } from "./route-flag-B1lQht6v.mjs";
10
10
  import { c as PostConstructStatus, i as Constructor, l as Scope, n as BuilderOf, o as METADATA, r as ClassKind, s as MaybePromise, t as Buildable, u as ServiceOptions } from "./interfaces-C6LHcYsg.mjs";
11
11
  import { C as MetaValue, S as ExecutionContext, _ as ResolvedDeps, a as ModuleRoutes, b as ContextMeta, c as ContextDecorator, d as ContextDecoratorTarget, f as ContextDecoratorWithDefaults, g as MissingParamKeys, h as DepValue, l as ContextDecoratorRequiringParams, m as ContributorRegistrations, n as AppModuleClass, o as AnyContributorRegistration, p as ContributorRegistration, r as AppModuleEntry, s as CallSiteParams, t as AppModule, u as ContextDecoratorSpec, v as defineContextDecorator, x as ContextMetaKey, y as ContextKeys } from "./app-module-Bk3glnPP.mjs";
12
12
  import { a as CronOptions, c as getCronJobs, d as runCronJob, f as runCronJobs, i as CronJobMeta, l as isCronJobEnabled, n as Cron, o as CronRun, r as CronJob, s as cronScheduleId, t as CRON_META, u as listCronJobs } from "./cron-BTGytNg-.mjs";
13
- import { A as NoJobHandlerError, C as JOB_DISPATCHER, D as JobDispatcher, E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, M as ProcessDefinition, N as listJobHandlers, O as JobHandler, P as listJobQueues, S as JOB_CONTEXT_FIELD, T as Job, _ as Respondable, a as KvSessionStoreOptions, b as isRespondable, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, j as Process, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, p as RESPOND, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as settleBackgroundWork, v as applyHandlerResult, w as JOB_META, x as reply, y as isReply } from "./kv-stores-DJBnGQsJ.mjs";
13
+ import { A as NoJobHandlerError, C as JOB_DISPATCHER, D as JobDispatcher, E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, M as ProcessDefinition, N as listJobHandlers, O as JobHandler, P as listJobQueues, S as JOB_CONTEXT_FIELD, T as Job, _ as Respondable, a as KvSessionStoreOptions, b as isRespondable, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, j as Process, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, p as RESPOND, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as settleBackgroundWork, v as applyHandlerResult, w as JOB_META, x as reply, y as isReply } from "./kv-stores-BN7c9bt9.mjs";
14
14
  import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider } from "./cache-CdRHSXow.mjs";
15
15
  import { a as describeError, i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "./logger-xE9qI_FS.mjs";
16
16
  import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "./errors-By6UueCm.mjs";
17
- import { $ as createHandler, A as requestScopeMiddleware, At as groupAssetKeys, B as SignerOptions, Bt as MissingContextValueError, C as ViewAdapterOptions, Ct as RoutePolicyTable, D as TraceContextOptions, Dt as AssetKeyStrategy, E as TraceContext, Et as AssetKeyPair, F as buildRoutes, Ft as MountKind, G as PasswordHashOptions, Gt as CircuitBreakerStats, H as createSigner, Ht as CircuitBreaker, I as expressRuntime, It as MountSortItem, J as verifyPassword, Jt as KickError, K as VerifyPasswordOptions, Kt as CircuitOpenError, L as materializeRouter, Lt as mountSort, M as getRequestStore, Mt as DuplicateMountNameError, N as getRequestValue, Nt as MissingMountDepError, O as parseTraceparent, Ot as GroupAssetKeysOptions, P as requestStore, Pt as MountCycleError, Q as KickHandler, R as SignedCheck, Rt as ContributorCycleError, S as ViewAdapter, St as StartupTimelineSnapshot, T as TRACEPARENT_HEADER, Tt as offerRoutePolicy, U as LegacyHasher, Ut as CircuitBreakerOptions, V as VerifyOptions, Vt as MissingContributorError, W as PasswordCheck, Wt as CircuitBreakerState, X as ClusterOptions, Xt as formatKickError, Y as defineHttpContextDecorator, Yt as KickErrorInit, Z as isClusterPrimary, _ as HealthProbe, _t as CheckMessage, a as ConfigDescription, at as CRON_WORKER_ENV, b as SpaAdapterOptions, bt as defineCheck, c as MiddlewareEntry, ct as CronScheduler, dt as MetricsOptions, et as bootstrap, ft as RequestHistogram, g as HealthModuleConfig, gt as CheckContext, h as HealthController, ht as CacheResponseOptions, i as ApplicationOptions, it as RESPONSE_CHANNEL, j as RequestStore, jt as stripExt, k as traceContext, kt as GroupAssetKeysResult, l as MountedRouteInfo, lt as KickCronAdapter, m as HealthCheckResult, mt as CacheResponse, n as AppStatus, nt as HANDLER_CHANNEL, o as ConfigOrigins, ot as CronAdapterOptions, p as HEALTH_PROBE, pt as metricsAdapter, q as hashPassword, qt as FormatKickErrorOptions, r as Application, rt as HandlerTraceContext, s as ManagementOptions, st as CronSchedule, t as APPLICATION, tt as ERROR_CHANNEL, u as ServerOptions, ut as RAW_BODY, v as healthModule, vt as StartupCheck, wt as bindRoutePolicy, xt as StartupStep, y as SpaAdapter, yt as StartupCheckError, z as Signer, zt as DuplicateContributorError } from "./application-CdUI5E_3.mjs";
17
+ import { $ as createHandler, A as requestScopeMiddleware, At as groupAssetKeys, B as SignerOptions, Bt as MissingContextValueError, C as ViewAdapterOptions, Ct as RoutePolicyTable, D as TraceContextOptions, Dt as AssetKeyStrategy, E as TraceContext, Et as AssetKeyPair, F as buildRoutes, Ft as MountKind, G as PasswordHashOptions, Gt as CircuitBreakerStats, H as createSigner, Ht as CircuitBreaker, I as expressRuntime, It as MountSortItem, J as verifyPassword, Jt as KickError, K as VerifyPasswordOptions, Kt as CircuitOpenError, L as materializeRouter, Lt as mountSort, M as getRequestStore, Mt as DuplicateMountNameError, N as getRequestValue, Nt as MissingMountDepError, O as parseTraceparent, Ot as GroupAssetKeysOptions, P as requestStore, Pt as MountCycleError, Q as KickHandler, R as SignedCheck, Rt as ContributorCycleError, S as ViewAdapter, St as StartupTimelineSnapshot, T as TRACEPARENT_HEADER, Tt as offerRoutePolicy, U as LegacyHasher, Ut as CircuitBreakerOptions, V as VerifyOptions, Vt as MissingContributorError, W as PasswordCheck, Wt as CircuitBreakerState, X as ClusterOptions, Xt as formatKickError, Y as defineHttpContextDecorator, Yt as KickErrorInit, Z as isClusterPrimary, _ as HealthProbe, _t as CheckMessage, a as ConfigDescription, at as CRON_WORKER_ENV, b as SpaAdapterOptions, bt as defineCheck, c as MiddlewareEntry, ct as CronScheduler, dt as MetricsOptions, et as bootstrap, ft as RequestHistogram, g as HealthModuleConfig, gt as CheckContext, h as HealthController, ht as CacheResponseOptions, i as ApplicationOptions, it as RESPONSE_CHANNEL, j as RequestStore, jt as stripExt, k as traceContext, kt as GroupAssetKeysResult, l as MountedRouteInfo, lt as KickCronAdapter, m as HealthCheckResult, mt as CacheResponse, n as AppStatus, nt as HANDLER_CHANNEL, o as ConfigOrigins, ot as CronAdapterOptions, p as HEALTH_PROBE, pt as metricsAdapter, q as hashPassword, qt as FormatKickErrorOptions, r as Application, rt as HandlerTraceContext, s as ManagementOptions, st as CronSchedule, t as APPLICATION, tt as ERROR_CHANNEL, u as ServerOptions, ut as RAW_BODY, v as healthModule, vt as StartupCheck, wt as bindRoutePolicy, xt as StartupStep, y as SpaAdapter, yt as StartupCheckError, z as Signer, zt as DuplicateContributorError } from "./application-EinAcKLu.mjs";
18
18
  import { n as joinPaths, r as normalizePath, t as buildMountPath } from "./path-CMwIHsdv.mjs";
19
19
  import { a as batch, c as reactive, d as toRefs, f as unref, i as WatchOptions, l as ref, n as Ref, o as computed, p as watch, r as RefOptions, s as isRef, t as ComputedRef, u as toRef } from "./reactivity-DZrc3Yhu.mjs";
20
20
  import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData } from "./session-8uNRCplB.mjs";
21
21
  import { A as TypedParsedQuery, C as PaginatedResponse, D as QueryFieldConfig, E as QueryBuilderAdapter, O as SortItem, S as FilterOperator, T as ParsedQuery, _ as CursorQuery, a as getQueryParsingDefaults, b as FieldsOf, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as CursorPosition, h as CursorPaginatedResponse, i as buildQueryParams, l as parseSearchQuery, m as CursorPaginateOptions, n as QueryRejectReason, o as parseFilters, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as CursorValue, w as PaginationParams, x as FilterItem, y as FILTER_OPERATORS } from "./index-Blgka75E.mjs";
22
22
  import { a as validate, i as defaultValidationError, n as ValidationFailure, t as ValidationErrorFactory } from "./validate-D4Poe2EE.mjs";
23
23
  import { n as allowedHosts, t as AllowedHostsOptions } from "./allowed-hosts-BpKwviq5.mjs";
24
- import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-CPJHwoL1.mjs";
24
+ import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-DtGrng_X.mjs";
25
25
  import { n as requestId, t as REQUEST_ID_HEADER } from "./request-id-Dn64nEHK.mjs";
26
- import { n as errorHandler, r as notFoundHandler } from "./error-handler-BrihKETE.mjs";
26
+ import { n as errorHandler, r as notFoundHandler } from "./error-handler-OfxVJX3s.mjs";
27
27
  import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-w5bc-PGs.mjs";
28
28
  import { i as requestLogger, n as LoggedResponse, r as RequestLoggerOptions, t as LoggedRequest } from "./request-logger-TgcKRNDD.mjs";
29
29
  import { n as HelmetOptions, r as helmet } from "./helmet-BVuVBl-D.mjs";
30
30
  import { n as breachPadding, t as BreachPaddingOptions } from "./breach-padding-FBVGmcBb.mjs";
31
31
  import { n as cors, t as CorsOptions } from "./cors-BlR_b0Qb.mjs";
32
32
  import { i as rateLimit, n as RateLimitOptions, r as RateLimitStore } from "./rate-limit-DQDk6bAH.mjs";
33
- import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-DtQ1pdQw.mjs";
34
- export { APPLICATION, ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterCondition, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AllowedHostsOptions, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, type AppStatus, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, Autowired, type BareRouteFlag, type BaseUploadOptions, type BreachPaddingOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CRON_WORKER_ENV, CacheEvict, type CacheOptions, type CacheProvider, CacheResponse, type CacheResponseOptions, Cacheable, type CallSiteParams, type CheckContext, type CheckMessage, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, type ConditionOutcome, type ConditionalOutcome, type ConfigDescription, type ConfigOrigins, ConfigService, type ConfigVar, type ConnectErrorHandler, type ConnectHandler, type ConnectMiddleware, type ConnectNext, type ConnectRequest, type ConnectResponse, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronAdapterOptions, type CronJob, type CronJobMeta, type CronOptions, type CronRun, type CronSchedule, type CronScheduler, type CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, type CursorPaginateOptions, type CursorPaginatedResponse, type CursorPosition, type CursorQuery, type CursorValue, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, ERROR_CHANNEL, type Env, type EnvKey, type ErrorInfo, type ErrorSource, type ExecutionContext, FILTER_OPERATORS, type FailureAdvice, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, HANDLER_CHANNEL, HEALTH_PROBE, type HandlerTraceContext, type HealthCheckResult, HealthController, type HealthModuleConfig, type HealthProbe, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, JOB_CONTEXT_FIELD, JOB_DISPATCHER, JOB_META, Job, type JobContextCarrier, type JobDispatcher, type JobHandler, type JobLike, type KickAssets, KickCronAdapter, KickError, type KickErrorInit, type KickHandler, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRouteFlags, type KickRuntimeRegister, type KickServer, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type LegacyHasher, type LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type ManagementOptions, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, type MetricsOptions, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, type MountedRouteInfo, MutableModuleRegistry, type NegatedRouteFlagName, NoJobHandlerError, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, type PasswordCheck, type PasswordHashOptions, Patch, type PlatformContext, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Process, type ProcessDefinition, type ProvidedSettings, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, RAW_BODY, REQUEST_ID_HEADER, RESPOND, RESPONSE_CHANNEL, ROUTE_URLS, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type RefOptions, type Reply, type ReplyHeaders, type ReplyOptions, Repository, RequestContext, RequestHistogram, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type Respondable, type ResponseInfo, type RouteContributor, type RouteDefinition, type RouteEntry, type RouteFlag, type RouteFlagContext, type RouteFlagDeclaration, type RouteFlagDeclarations, type RouteFlagName, type RouteFlagPredicate, type RouteFlagRecord, type RouteFlagTest, type RouteFlagValue, type RouteFlags, type RouteMeta, type RouteMethod, type RouteName, RoutePolicyTable, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, type ServerOptions, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type Settings, type SettingsDeclaration, type SettingsOf, type SignedCheck, type Signer, type SignerOptions, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, type StartupCheck, StartupCheckError, type StartupStep, type StartupTimelineSnapshot, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UploadStorageEngine, type UploadedFile, type UrlBuilder, type UrlForArgs, type UrlQuery, type UseConnectOptions, type ValidationError, type ValidationErrorFactory, type ValidationFailure, type Validators, Value, type ValueOrigin, type ValuedRouteFlag, type VarOrigin, type VerifyOptions, type VerifyPasswordOptions, ViewAdapter, type ViewAdapterOptions, type WatchOptions, allOf, allowedHosts, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, batch, bindRoutePolicy, bootstrap, breachPadding, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createSigner, createToken, cronScheduleId, csrf, csrfGuard, ctn, defaultProblemTitle, defaultValidationError, defineAdapter, defineCheck, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, defineSettings, describeError, disposeAll, errorHandler, evaluatePreconditions, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, hashPassword, healthModule, helmet, isClusterPrimary, isCronJobEnabled, isInjectionToken, isRef, isReply, isRespondable, joinPaths, listCronJobs, listJobHandlers, listJobQueues, loadEnv, loadEnvFromSchema, loadSettings, matchesBearer, matchesFlagTest, materializeRouter, metricsAdapter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, onEnv, onPackage, originsOf, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, registerJobContext, reloadEnv, reply, reportError, reportResponse, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, resolveRouteFlags, runContributors, runCronJob, runCronJobs, runJob, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, settleBackgroundWork, stampJobContext, stripExt, toRef, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, verifyPassword, waitUntil, watch, withBuilder, withEnv };
33
+ import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-C9IfY1aQ.mjs";
34
+ export { APPLICATION, ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterCondition, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AllowedHostsOptions, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, type AppStatus, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, Autowired, type BareRouteFlag, type BaseUploadOptions, type BreachPaddingOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CRON_WORKER_ENV, CacheEvict, type CacheOptions, type CacheProvider, CacheResponse, type CacheResponseOptions, Cacheable, type CallSiteParams, type CheckContext, type CheckMessage, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, type ConditionOutcome, type ConditionalOutcome, type ConfigDescription, type ConfigOrigins, ConfigService, type ConfigVar, type ConnectErrorHandler, type ConnectHandler, type ConnectMiddleware, type ConnectNext, type ConnectRequest, type ConnectResponse, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronAdapterOptions, type CronJob, type CronJobMeta, type CronOptions, type CronRun, type CronSchedule, type CronScheduler, type CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, type CursorPaginateOptions, type CursorPaginatedResponse, type CursorPosition, type CursorQuery, type CursorValue, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, ERROR_CHANNEL, type Env, type EnvKey, type ErrorInfo, type ErrorSource, type ExecutionContext, FILTER_OPERATORS, type FailureAdvice, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, HANDLER_CHANNEL, HEALTH_PROBE, type HandlerTraceContext, type HealthCheckResult, HealthController, type HealthModuleConfig, type HealthProbe, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, JOB_CONTEXT_FIELD, JOB_DISPATCHER, JOB_META, Job, type JobContextCarrier, type JobDispatcher, type JobHandler, type JobLike, type KickAssets, KickCronAdapter, KickError, type KickErrorInit, type KickHandler, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRouteFlags, type KickRuntimeRegister, type KickServer, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, type LegacyHasher, type LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type ManagementOptions, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, type MetricsOptions, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, type MountedRouteInfo, MutableModuleRegistry, type NegatedRouteFlagName, NoJobHandlerError, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, type PasswordCheck, type PasswordHashOptions, Patch, type PlatformContext, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Process, type ProcessDefinition, type ProvidedSettings, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, RAW_BODY, REQUEST_ID_HEADER, RESPOND, RESPONSE_CHANNEL, ROUTE_URLS, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type RefOptions, type Reply, type ReplyHeaders, type ReplyOptions, Repository, RequestContext, RequestHistogram, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type Respondable, type ResponseInfo, type RouteContributor, type RouteDefinition, type RouteEntry, type RouteFlag, type RouteFlagContext, type RouteFlagDeclaration, type RouteFlagDeclarations, type RouteFlagName, type RouteFlagPredicate, type RouteFlagRecord, type RouteFlagTest, type RouteFlagValue, type RouteFlags, type RouteMeta, type RouteMethod, type RouteName, RoutePolicyTable, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, type ServerOptions, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type Settings, type SettingsDeclaration, type SettingsOf, type SignedCheck, type Signer, type SignerOptions, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, type StartupCheck, StartupCheckError, type StartupStep, type StartupTimelineSnapshot, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UploadStorageEngine, type UploadedFile, type UrlBuilder, type UrlForArgs, type UrlQuery, type UseConnectOptions, VIEW_RENDERER, type ValidationError, type ValidationErrorFactory, type ValidationFailure, type Validators, Value, type ValueOrigin, type ValuedRouteFlag, type VarOrigin, type VerifyOptions, type VerifyPasswordOptions, ViewAdapter, type ViewAdapterOptions, type ViewRenderOptions, type ViewRenderer, type WatchOptions, allOf, allowedHosts, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, batch, bindRoutePolicy, bindViewRenderer, bootstrap, breachPadding, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createSigner, createToken, cronScheduleId, csrf, csrfGuard, ctn, defaultProblemTitle, defaultValidationError, defineAdapter, defineCheck, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, defineSettings, describeError, disposeAll, errorHandler, evaluatePreconditions, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, hashPassword, healthModule, helmet, isClusterPrimary, isCronJobEnabled, isInjectionToken, isRef, isReply, isRespondable, joinPaths, listCronJobs, listJobHandlers, listJobQueues, loadEnv, loadEnvFromSchema, loadSettings, matchesBearer, matchesFlagTest, materializeRouter, metricsAdapter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, onEnv, onPackage, originsOf, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, registerJobContext, reloadEnv, reply, reportError, reportResponse, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, resolveRouteFlags, runContributors, runCronJob, runCronJobs, runJob, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, settleBackgroundWork, stampJobContext, stripExt, toRef, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, verifyPassword, viewRendererFor, waitUntil, watch, withBuilder, withEnv };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.11.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,9 +8,9 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{o as KickError,s as formatKickError}from"./di-hooks-DX9rJX_0.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{i as isInjectionToken,n as createToken,r as ctn,t as INJECTION_TOKEN}from"./token-CBe6OMQK.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-BvNkZphr.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{i as defineModule,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-Df_ts-iM.mjs";import{i as reportResponse,r as reportError}from"./observers-Bjs-1F1Z.mjs";import{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs}from"./core/cron.mjs";import{a as NoJobHandlerError,c as listJobQueues,d as stampJobContext,i as Job,l as registerJobContext,n as JOB_DISPATCHER,o as Process,r as JOB_META,s as listJobHandlers,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-bGtYcSgo.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-Bq6gIO7N.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-xPz2wbyz.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-MyOlkejk.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-B2uJdmkX.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-CnCNsI87.mjs";import{t as runContributors}from"./contributor-runner-CaZkoZOK.mjs";import{_ as MountCycleError,a as HealthController,c as defineCheck,d as onPackage,f as ERROR_CHANNEL,g as MissingMountDepError,h as DuplicateMountNameError,i as HEALTH_PROBE,l as allOf,m as RESPONSE_CHANNEL,n as Application,o as healthModule,p as HANDLER_CHANNEL,s as StartupCheckError,t as APPLICATION,u as onEnv,v as mountSort}from"./application-DLRHEOeg.mjs";import{t as defineAdapter}from"./define-adapter-1FfgX1AQ.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-weZwvZYs.mjs";import{n as randomHex,t as matchesBearer}from"./web-crypto-BNF60ZAh.mjs";import{n as RAW_BODY}from"./body-policy-DIgqprai.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as getRequestStore,i as waitUntil,o as getRequestValue,r as settleBackgroundWork,s as requestStore}from"./background-CiKEgaD2.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware}from"./request-scope-u_VhYe4-.mjs";import{a as originsOf,i as loadSettings,n as defineSettings}from"./settings-Ciut2k76.mjs";import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"./decorate-CU19-7Fw.mjs";import{a as reply,i as isRespondable,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-CGn9BmYj.mjs";import{a as materializeRouter,i as expressRuntime,n as buildRoutes}from"./express-lazy-Pua2eR0n.mjs";import{a as evaluatePreconditions,i as stringifyJson,t as RequestContext}from"./context-BPszif4a.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-6ltjueRe.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-BEnIVY7Q.mjs";import{defaultValidationError,validate}from"./http/middleware/validate.mjs";import{csrf,csrfGuard}from"./http/middleware/csrf.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{breachPadding}from"./http/middleware/breach-padding.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-DbM-V83V.mjs";import{session}from"./http/middleware/session.mjs";import{o as resolveMimeTypes}from"./upload-config-d_LW2u9b.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-BEoFtveu.mjs";import{createHmac,randomBytes,scrypt,timingSafeEqual}from"node:crypto";import{monitorEventLoopDelay}from"node:perf_hooks";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=/* @__PURE__ */ new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}const inFlight=/* @__PURE__ */ new Map,PERSONAL=[`authorization`,`proxy-authorization`,`x-api-key`,`cookie`];function CacheResponse(options){let maxAgeMs=options.maxAge*1e3,swrMs=(options.swr??0)*1e3,varies=(options.varies??[]).map(h=>h.toLowerCase());return(target,propertyKey,descriptor)=>{let original=descriptor.value,owner=typeof target==`function`?target.name:target.constructor?.name,prefix=typeof options.key==`string`?options.key:`kick:response:${owner??`anonymous`}.${String(propertyKey)}`,keyOf=typeof options.key==`function`?options.key:void 0;return descriptor.value=async function(ctx,...rest){let req=ctx.req,method=String(req.method??`GET`).toUpperCase(),headers=ctx.headers;if(method!==`GET`&&method!==`HEAD`||maxAgeMs+swrMs<=0)return original.call(this,ctx,...rest);let identity;if(keyOf){let chosen=keyOf(ctx);if(chosen===null)return original.call(this,ctx,...rest);identity=chosen}else{if(PERSONAL.some(h=>headers[h]!==void 0&&!varies.includes(h))||ctx.user!==void 0&&!varies.some(h=>PERSONAL.includes(h)))return original.call(this,ctx,...rest);let host=String(headers.host??``);if(!VALID_HOST.test(host))return original.call(this,ctx,...rest);identity=JSON.stringify([host.toLowerCase(),req.originalUrl??req.url??``])}let varied=varies.map(h=>`${h}=${String(headers[h]??``)}`).join(`&`),key=`${prefix}:${identity}|${varied}`,provider=getCacheProvider(),run=()=>record(original,this,ctx,rest),build=()=>buildOnce(key,run),store=async({recorded,shared})=>{if(!shared&&recorded&&cacheable(recorded)){let entry={recorded,storedAt:Date.now()};await provider.set(key,entry,maxAgeMs+swrMs)}},entry=await provider.get(key);if(entry){let age=Date.now()-entry.storedAt;if(age<maxAgeMs+swrMs){age>=maxAgeMs&&waitUntil(build().then(store)),replay(ctx,entry.recorded);return}}let built=await build();await store(built);let recorded=built.recorded;built.shared&&!(recorded&&cacheable(recorded))&&(recorded=await run()),recorded&&replay(ctx,recorded)},descriptor}}const VALID_HOST=/^(?:\[[0-9a-f:.]+\]|[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::\d{1,5})?$/i;async function buildOnce(key,run){let pending=inFlight.get(key);if(pending)return{recorded:await pending,shared:!0};let load=run().finally(()=>inFlight.delete(key));return inFlight.set(key,load),{recorded:await load,shared:!1}}function cacheable(recorded){return recorded.status===200&&!(`set-cookie`in recorded.headers)&&!recorded.native}async function record(handler,self,ctx,rest){let recorded={status:200,headers:{},body:``},sent=!1,finish=body=>{body instanceof Uint8Array?(recorded.body=toBase64(body),recorded.binary=!0):typeof body==`string`?recorded.body=body:body!=null&&(recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(body)),sent=!0},unsupported=what=>()=>{throw Error(`@CacheResponse: the handler called ${what}. A cached route answers with ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.`)},response={status(code){return recorded.status=code,response},type(contentType){return recorded.type=contentType,response},json(data){return recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(data),sent=!0,response},send(data){return finish(data),response},end(data){return finish(data),response},setHeader(name,value){recorded.headers[name.toLowerCase()]=Array.isArray(value)?[...value]:String(value)},get headersSent(){return sent},once(){},render:unsupported(`render()`),writeHead:unsupported(`writeHead()`),flushHeaders:unsupported(`flushHeaders()`),write:unsupported(`write()`)},native=new Proxy(ctx.res,{get(target,prop){let value=Reflect.get(target,prop,target);return typeof value==`function`?(...args)=>(recorded.native=!0,value.apply(target,args)):value},set(target,prop,value){return recorded.native=!0,Reflect.set(target,prop,value,target)}}),recordingCtx=Object.create(ctx,{_response:{value:response},res:{value:native}}),result=await handler.call(self,recordingCtx,...rest);return sent||await applyHandlerResult(recordingCtx,result),sent?recorded:null}function replay(ctx,recorded){if(ctx._response.headersSent)return;for(let[name,value]of Object.entries(recorded.headers))name!==`etag`&&name!==`content-type`&&ctx.setHeader(name,value);if(recorded.status===200){let etag=recorded.headers.etag??weakEtag(recorded.body);if(ctx.conditional({etag}))return}let options={status:recorded.status,type:recorded.type??`text/plain; charset=utf-8`};ctx.send(recorded.binary?fromBase64(recorded.body):recorded.body,options)}function weakEtag(body){let hash=2166136261;for(let i=0;i<body.length;i++)hash^=body.charCodeAt(i),hash=Math.imul(hash,16777619);return`W/"${body.length.toString(16)}-${(hash>>>0).toString(16)}"`}function toBase64(bytes){let binary=``;for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}function fromBase64(text){let binary=atob(text),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}const DEFAULT_BUCKETS=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],label=value=>value.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`
11
+ import{o as KickError,s as formatKickError}from"./di-hooks-DGmtRWDI.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{i as isInjectionToken,n as createToken,r as ctn,t as INJECTION_TOKEN}from"./token-kfP7I0D6.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-CsfVw6pp.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{i as defineModule,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-O-DQnRvH.mjs";import{i as reportResponse,r as reportError}from"./observers-BbNYzGfC.mjs";import{CRON_META,Cron,cronScheduleId,getCronJobs,isCronJobEnabled,listCronJobs,runCronJob,runCronJobs}from"./core/cron.mjs";import{a as NoJobHandlerError,c as listJobQueues,d as stampJobContext,i as Job,l as registerJobContext,n as JOB_DISPATCHER,o as Process,r as JOB_META,s as listJobHandlers,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-B4wle0iS.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-C1xhXyD6.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{batch,computed,isRef,reactive,ref,toRef,toRefs,unref,watch}from"./core/reactivity.mjs";import{l as resolveRouteFlags,n as assertFlagTest,o as getRouteFlags,r as defineRouteFlag,s as matchesFlagTest}from"./route-flag-CO7wkxhn.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-Cf6gPv9R.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-s1zG7eax.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-DtjsnD0b.mjs";import{t as runContributors}from"./contributor-runner-B5pv7_R-.mjs";import{_ as MountCycleError,a as HealthController,c as defineCheck,d as onPackage,f as ERROR_CHANNEL,g as MissingMountDepError,h as DuplicateMountNameError,i as HEALTH_PROBE,l as allOf,m as RESPONSE_CHANNEL,n as Application,o as healthModule,p as HANDLER_CHANNEL,s as StartupCheckError,t as APPLICATION,u as onEnv,v as mountSort}from"./application-BCXdtJd1.mjs";import{t as defineAdapter}from"./define-adapter-B9DcBJKt.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-DJd0iddt.mjs";import{n as randomHex,t as matchesBearer}from"./web-crypto-BNP8o7BF.mjs";import{n as RAW_BODY}from"./body-policy-DccDxmmR.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as viewRendererFor,c as settleBackgroundWork,d as getRequestValue,f as requestStore,l as waitUntil,n as bindViewRenderer,t as VIEW_RENDERER,u as getRequestStore}from"./view-renderer-NbkTobFF.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware}from"./request-scope-D5ggZdvq.mjs";import{a as originsOf,i as loadSettings,n as defineSettings}from"./settings-CJWJPERr.mjs";import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"./decorate-BQA6M9jq.mjs";import{a as reply,i as isRespondable,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-Detphot1.mjs";import{a as materializeRouter,i as expressRuntime,n as buildRoutes}from"./express-lazy-CdPN1krb.mjs";import{a as evaluatePreconditions,i as stringifyJson,t as RequestContext}from"./context-BJ6HVq4W.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-C5op763j.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-EQM3lEr_.mjs";import{defaultValidationError,validate}from"./http/middleware/validate.mjs";import{csrf,csrfGuard}from"./http/middleware/csrf.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{breachPadding}from"./http/middleware/breach-padding.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-CLR0N5im.mjs";import{session}from"./http/middleware/session.mjs";import{o as resolveMimeTypes}from"./upload-config-DldXNOHe.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-DZd8tqGC.mjs";import{createHmac,randomBytes,scrypt,timingSafeEqual}from"node:crypto";import{monitorEventLoopDelay}from"node:perf_hooks";var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=/* @__PURE__ */ new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}const inFlight=/* @__PURE__ */ new Map,PERSONAL=[`authorization`,`proxy-authorization`,`x-api-key`,`cookie`];function CacheResponse(options){let maxAgeMs=options.maxAge*1e3,swrMs=(options.swr??0)*1e3,varies=(options.varies??[]).map(h=>h.toLowerCase());return(target,propertyKey,descriptor)=>{let original=descriptor.value,owner=typeof target==`function`?target.name:target.constructor?.name,prefix=typeof options.key==`string`?options.key:`kick:response:${owner??`anonymous`}.${String(propertyKey)}`,keyOf=typeof options.key==`function`?options.key:void 0;return descriptor.value=async function(ctx,...rest){let req=ctx.req,method=String(req.method??`GET`).toUpperCase(),headers=ctx.headers;if(method!==`GET`&&method!==`HEAD`||maxAgeMs+swrMs<=0)return original.call(this,ctx,...rest);let identity;if(keyOf){let chosen=keyOf(ctx);if(chosen===null)return original.call(this,ctx,...rest);identity=chosen}else{if(PERSONAL.some(h=>headers[h]!==void 0&&!varies.includes(h))||ctx.user!==void 0&&!varies.some(h=>PERSONAL.includes(h)))return original.call(this,ctx,...rest);let host=String(headers.host??``);if(!VALID_HOST.test(host))return original.call(this,ctx,...rest);identity=JSON.stringify([host.toLowerCase(),req.originalUrl??req.url??``])}let varied=varies.map(h=>`${h}=${String(headers[h]??``)}`).join(`&`),key=`${prefix}:${identity}|${varied}`,provider=getCacheProvider(),run=()=>record(original,this,ctx,rest),build=()=>buildOnce(key,run),store=async({recorded,shared})=>{if(!shared&&recorded&&cacheable(recorded)){let entry={recorded,storedAt:Date.now()};await provider.set(key,entry,maxAgeMs+swrMs)}},entry=await provider.get(key);if(entry){let age=Date.now()-entry.storedAt;if(age<maxAgeMs+swrMs){age>=maxAgeMs&&waitUntil(build().then(store)),replay(ctx,entry.recorded);return}}let built=await build();await store(built);let recorded=built.recorded;built.shared&&!(recorded&&cacheable(recorded))&&(recorded=await run()),recorded&&replay(ctx,recorded)},descriptor}}const VALID_HOST=/^(?:\[[0-9a-f:.]+\]|[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::\d{1,5})?$/i;async function buildOnce(key,run){let pending=inFlight.get(key);if(pending)return{recorded:await pending,shared:!0};let load=run().finally(()=>inFlight.delete(key));return inFlight.set(key,load),{recorded:await load,shared:!1}}function cacheable(recorded){return recorded.status===200&&!(`set-cookie`in recorded.headers)&&!recorded.native}async function record(handler,self,ctx,rest){let recorded={status:200,headers:{},body:``},sent=!1,finish=body=>{body instanceof Uint8Array?(recorded.body=toBase64(body),recorded.binary=!0):typeof body==`string`?recorded.body=body:body!=null&&(recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(body)),sent=!0},unsupported=what=>()=>{throw Error(`@CacheResponse: the handler called ${what}. A cached route answers with ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.`)},response={status(code){return recorded.status=code,response},type(contentType){return recorded.type=contentType,response},json(data){return recorded.type??=`application/json; charset=utf-8`,recorded.body=stringifyJson(data),sent=!0,response},send(data){return finish(data),response},end(data){return finish(data),response},setHeader(name,value){recorded.headers[name.toLowerCase()]=Array.isArray(value)?[...value]:String(value)},get headersSent(){return sent},once(){},render:unsupported(`render()`),writeHead:unsupported(`writeHead()`),flushHeaders:unsupported(`flushHeaders()`),write:unsupported(`write()`)},native=new Proxy(ctx.res,{get(target,prop){let value=Reflect.get(target,prop,target);return typeof value==`function`?(...args)=>(recorded.native=!0,value.apply(target,args)):value},set(target,prop,value){return recorded.native=!0,Reflect.set(target,prop,value,target)}}),recordingCtx=Object.create(ctx,{_response:{value:response},res:{value:native}}),result=await handler.call(self,recordingCtx,...rest);return sent||await applyHandlerResult(recordingCtx,result),sent?recorded:null}function replay(ctx,recorded){if(ctx._response.headersSent)return;for(let[name,value]of Object.entries(recorded.headers))name!==`etag`&&name!==`content-type`&&ctx.setHeader(name,value);if(recorded.status===200){let etag=recorded.headers.etag??weakEtag(recorded.body);if(ctx.conditional({etag}))return}let options={status:recorded.status,type:recorded.type??`text/plain; charset=utf-8`};ctx.send(recorded.binary?fromBase64(recorded.body):recorded.body,options)}function weakEtag(body){let hash=2166136261;for(let i=0;i<body.length;i++)hash^=body.charCodeAt(i),hash=Math.imul(hash,16777619);return`W/"${body.length.toString(16)}-${(hash>>>0).toString(16)}"`}function toBase64(bytes){let binary=``;for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));return btoa(binary)}function fromBase64(text){let binary=atob(text),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}const DEFAULT_BUCKETS=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],label=value=>value.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`
12
12
  `,`\\n`);var RequestHistogram=class{series=/* @__PURE__ */ new Map;buckets;constructor(buckets=DEFAULT_BUCKETS){if(buckets.length===0||buckets.some(b=>!Number.isFinite(b)||b<=0))throw Error(`metrics: buckets must be finite positive numbers (seconds)`);this.buckets=[...new Set(buckets)].toSorted((a,b)=>a-b)}observe(info){let labels=`method="${label(knownMethod(info.method))}",route="${label(info.route??`unmatched`)}",status="${info.status}"`,series=this.series.get(labels);series||(series={labels,counts:this.buckets.map(()=>0),sum:0,count:0},this.series.set(labels,series));let seconds=info.durationMs/1e3;for(let[i,bound]of this.buckets.entries())seconds<=bound&&series.counts[i]++;series.sum+=seconds,series.count++}render(){let name=`http_request_duration_seconds`,lines=[`# HELP ${name} Time to answer an HTTP request, by route pattern.`,`# TYPE ${name} histogram`];for(let s of this.series.values()){for(let[i,bound]of this.buckets.entries())lines.push(`${name}_bucket{${s.labels},le="${bound}"} ${s.counts[i]}`);lines.push(`${name}_bucket{${s.labels},le="+Inf"} ${s.count}`),lines.push(`${name}_sum{${s.labels}} ${s.sum}`),lines.push(`${name}_count{${s.labels}} ${s.count}`)}return lines.join(`
13
13
  `)}};const METHODS=/* @__PURE__ */ new Set([`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`,`QUERY`]);function knownMethod(method){let upper=method.toUpperCase();return METHODS.has(upper)?upper:`OTHER`}function gauge(name,help,value){return`# HELP ${name} ${help}\n# TYPE ${name} gauge\n${name} ${value}`}function metricsAdapter(options={}){let path=options.path??`/metrics`,histogram=new RequestHistogram(options.buckets??DEFAULT_BUCKETS),loop,render=()=>{let memory=process.memoryUsage(),lag=loop&&loop.count>0?loop.mean/1e9:0;return[histogram.render(),gauge(`process_resident_memory_bytes`,`Resident set size.`,memory.rss),gauge(`nodejs_heap_used_bytes`,`V8 heap in use.`,memory.heapUsed),gauge(`nodejs_heap_total_bytes`,`V8 heap allocated.`,memory.heapTotal),gauge(`nodejs_eventloop_lag_seconds`,`Mean event-loop delay since the last scrape.`,lag),gauge(`process_uptime_seconds`,`Seconds since the process started.`,process.uptime())].join(`
14
14
 
15
- `)};return{name:`MetricsAdapter`,beforeMount({http:appHttp,management}){let http=options.management&&management?management.http:appHttp;loop=monitorEventLoopDelay({resolution:20}),loop.enable(),http.route(`GET`,path,ctx=>{let{token}=options;if(token!==void 0&&!matchesBearer(ctx.headers.authorization,token)){ctx.setHeader(`WWW-Authenticate`,`Bearer`),ctx.json({message:`Unauthorized`},401);return}let body=render();loop?.reset(),ctx.setHeader(`Cache-Control`,`no-store`),ctx.send(`${body}\n`,{type:`text/plain; version=0.0.4; charset=utf-8`})})},onResponse(info){info.route!==path&&histogram.observe(info)},shutdown(){loop?.disable()}}}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),DEFAULTS={N:2**14,r:8,p:5};function derive(password,salt,cost){let options={...cost,maxmem:128*cost.r*(cost.N+cost.p+2)+1048576};return new Promise((resolve,reject)=>scrypt(password.normalize(`NFKC`),salt,64,options,(err,key)=>err?reject(err):resolve(key)))}function costOf(options){let cost={...DEFAULTS,...options};if(!Number.isInteger(Math.log2(cost.N))||cost.N<2)throw Error(`hashPassword: N must be a power of two`);return cost}async function hashPassword(password,options={}){let cost=costOf(options),salt=randomBytes(16),encoded=[salt,await derive(password,salt,cost)].map(bytes=>bytes.toString(`base64`));return[`scrypt`,cost.N,cost.r,cost.p,...encoded].join(`$`)}const DUMMY_SALT=randomBytes(16);async function verifyPassword(password,stored,options={}){let{legacy=[],...scryptCost}=options,parsed=stored?parse(stored):void 0,older=!parsed&&stored?legacy.find(hasher=>matches(hasher,stored)):void 0,[scrypt,checks]=await Promise.all([parsed?derive(password,parsed.salt,parsed.cost).catch(()=>void 0):derive(password,DUMMY_SALT,costOf(scryptCost)),Promise.all(legacy.map(hasher=>check(hasher,password,hasher===older?stored:hasher.dummy)))]);if(older){let ok=checks[legacy.indexOf(older)];return{ok,needsRehash:ok}}if(!parsed||!scrypt)return{ok:!1,needsRehash:!1};let ok=scrypt.length===parsed.key.length&&timingSafeEqual(scrypt,parsed.key),wanted=costOf(scryptCost);return{ok,needsRehash:ok&&(parsed.cost.N!==wanted.N||parsed.cost.r!==wanted.r||parsed.cost.p!==wanted.p)}}function matches(hasher,stored){try{return hasher.matches(stored)===!0}catch{return!1}}function check(hasher,password,hash){return Promise.resolve().then(()=>hasher.verify(password,hash)).then(result=>result===!0,()=>!1)}function parse(stored){let[algorithm,N,r,pp,salt,key]=stored.split(`$`);if(algorithm!==`scrypt`||key===void 0)return;let cost={N:Number(N),r:Number(r),p:Number(pp)};if(!(!Number.isInteger(Math.log2(cost.N))||cost.N<2||!Number.isInteger(cost.r)||cost.r<1||cost.r>32||!Number.isInteger(cost.p)||cost.p<1||cost.p>16||128*cost.N*cost.r>2**28))return{cost,salt:Buffer.from(salt,`base64`),key:Buffer.from(key,`base64`)}}function createSigner(options){let secrets=Array.isArray(options.secret)?options.secret:[options.secret];if(secrets.length===0||secrets.some(s=>typeof s!=`string`||s.length===0))throw Error("createSigner: `secret` must be a non-empty string or list of strings");if(!options.salt)throw Error("createSigner: `salt` names what the tokens are for");let keys=secrets.map(secret=>createHmac(`sha256`,secret).update(`kickjs.signing:${options.salt}`).digest()),mac=(key,data)=>createHmac(`sha256`,key).update(data).digest(`base64url`);return{sign(value){let json=JSON.stringify(value);if(json===void 0)throw Error(`signer.sign: the value must be JSON-serialisable`);let signed=`${Buffer.from(json).toString(`base64url`)}.${Date.now().toString(36)}`;return`${signed}.${mac(keys[0],signed)}`},verify(token,verifyOptions={}){let invalid={ok:!1,reason:`invalid`};if(typeof token!=`string`)return invalid;let cut=token.lastIndexOf(`.`),signed=token.slice(0,cut),signature=Buffer.from(token.slice(cut+1)),[payload,stamp,extra]=signed.split(`.`);if(cut<0||stamp===void 0||extra!==void 0||!keys.some(key=>{let expected=Buffer.from(mac(key,signed));return expected.length===signature.length&&timingSafeEqual(expected,signature)}))return invalid;let issued=parseInt(stamp,36);if(!Number.isFinite(issued))return invalid;if(verifyOptions.maxAge!==void 0&&Date.now()-issued>verifyOptions.maxAge)return{ok:!1,reason:`expired`};try{return{ok:!0,value:JSON.parse(Buffer.from(payload,`base64url`).toString()),issuedAt:new Date(issued)}}catch{return invalid}}}}const TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{APPLICATION,ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CRON_WORKER_ENV,CacheEvict,CacheResponse,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,ERROR_CHANNEL,FILTER_OPERATORS,FileUpload,Get,HANDLER_CHANNEL,HEALTH_PROBE,HealthController,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,JOB_CONTEXT_FIELD,JOB_DISPATCHER,JOB_META,Job,KickCronAdapter,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,NoJobHandlerError,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Process,Put,RAW_BODY,REQUEST_ID_HEADER,RESPOND,RESPONSE_CHANNEL,ROUTE_URLS,Repository,RequestContext,RequestHistogram,RoutePolicyTable,Scope,Service,SpaAdapter,StartupCheckError,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,allOf,allowedHosts,applyHandlerResult,assertFlagTest,assets,baseEnvSchema,batch,bindRoutePolicy,bootstrap,breachPadding,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createHandler,createLogger,createSigner,createToken,cronScheduleId,csrf,csrfGuard,ctn,defaultProblemTitle,defaultValidationError,defineAdapter,defineCheck,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,defineRouteFlag,defineSettings,describeError,disposeAll,errorHandler,evaluatePreconditions,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,getRouteFlags,groupAssetKeys,hasClassMeta,hashPassword,healthModule,helmet,isClusterPrimary,isCronJobEnabled,isInjectionToken,isRef,isReply,isRespondable,joinPaths,listCronJobs,listJobHandlers,listJobQueues,loadEnv,loadEnvFromSchema,loadSettings,matchesBearer,matchesFlagTest,materializeRouter,metricsAdapter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,offerRoutePolicy,onEnv,onPackage,originsOf,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,registerJobContext,reloadEnv,reply,reportError,reportResponse,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,resolveRouteFlags,runContributors,runCronJob,runCronJobs,runJob,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,settleBackgroundWork,stampJobContext,stripExt,toRef,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,verifyPassword,waitUntil,watch,withBuilder,withEnv};
15
+ `)};return{name:`MetricsAdapter`,beforeMount({http:appHttp,management}){let http=options.management&&management?management.http:appHttp;loop=monitorEventLoopDelay({resolution:20}),loop.enable(),http.route(`GET`,path,ctx=>{let{token}=options;if(token!==void 0&&!matchesBearer(ctx.headers.authorization,token)){ctx.setHeader(`WWW-Authenticate`,`Bearer`),ctx.json({message:`Unauthorized`},401);return}let body=render();loop?.reset(),ctx.setHeader(`Cache-Control`,`no-store`),ctx.send(`${body}\n`,{type:`text/plain; version=0.0.4; charset=utf-8`})})},onResponse(info){info.route!==path&&histogram.observe(info)},shutdown(){loop?.disable()}}}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),DEFAULTS={N:2**14,r:8,p:5};function derive(password,salt,cost){let options={...cost,maxmem:128*cost.r*(cost.N+cost.p+2)+1048576};return new Promise((resolve,reject)=>scrypt(password.normalize(`NFKC`),salt,64,options,(err,key)=>err?reject(err):resolve(key)))}function costOf(options){let cost={...DEFAULTS,...options};if(!Number.isInteger(Math.log2(cost.N))||cost.N<2)throw Error(`hashPassword: N must be a power of two`);return cost}async function hashPassword(password,options={}){let cost=costOf(options),salt=randomBytes(16),encoded=[salt,await derive(password,salt,cost)].map(bytes=>bytes.toString(`base64`));return[`scrypt`,cost.N,cost.r,cost.p,...encoded].join(`$`)}const DUMMY_SALT=randomBytes(16);async function verifyPassword(password,stored,options={}){let{legacy=[],...scryptCost}=options,parsed=stored?parse(stored):void 0,older=!parsed&&stored?legacy.find(hasher=>matches(hasher,stored)):void 0,[scrypt,checks]=await Promise.all([parsed?derive(password,parsed.salt,parsed.cost).catch(()=>void 0):derive(password,DUMMY_SALT,costOf(scryptCost)),Promise.all(legacy.map(hasher=>check(hasher,password,hasher===older?stored:hasher.dummy)))]);if(older){let ok=checks[legacy.indexOf(older)];return{ok,needsRehash:ok}}if(!parsed||!scrypt)return{ok:!1,needsRehash:!1};let ok=scrypt.length===parsed.key.length&&timingSafeEqual(scrypt,parsed.key),wanted=costOf(scryptCost);return{ok,needsRehash:ok&&(parsed.cost.N!==wanted.N||parsed.cost.r!==wanted.r||parsed.cost.p!==wanted.p)}}function matches(hasher,stored){try{return hasher.matches(stored)===!0}catch{return!1}}function check(hasher,password,hash){return Promise.resolve().then(()=>hasher.verify(password,hash)).then(result=>result===!0,()=>!1)}function parse(stored){let[algorithm,N,r,pp,salt,key]=stored.split(`$`);if(algorithm!==`scrypt`||key===void 0)return;let cost={N:Number(N),r:Number(r),p:Number(pp)};if(!(!Number.isInteger(Math.log2(cost.N))||cost.N<2||!Number.isInteger(cost.r)||cost.r<1||cost.r>32||!Number.isInteger(cost.p)||cost.p<1||cost.p>16||128*cost.N*cost.r>2**28))return{cost,salt:Buffer.from(salt,`base64`),key:Buffer.from(key,`base64`)}}function createSigner(options){let secrets=Array.isArray(options.secret)?options.secret:[options.secret];if(secrets.length===0||secrets.some(s=>typeof s!=`string`||s.length===0))throw Error("createSigner: `secret` must be a non-empty string or list of strings");if(!options.salt)throw Error("createSigner: `salt` names what the tokens are for");let keys=secrets.map(secret=>createHmac(`sha256`,secret).update(`kickjs.signing:${options.salt}`).digest()),mac=(key,data)=>createHmac(`sha256`,key).update(data).digest(`base64url`);return{sign(value){let json=JSON.stringify(value);if(json===void 0)throw Error(`signer.sign: the value must be JSON-serialisable`);let signed=`${Buffer.from(json).toString(`base64url`)}.${Date.now().toString(36)}`;return`${signed}.${mac(keys[0],signed)}`},verify(token,verifyOptions={}){let invalid={ok:!1,reason:`invalid`};if(typeof token!=`string`)return invalid;let cut=token.lastIndexOf(`.`),signed=token.slice(0,cut),signature=Buffer.from(token.slice(cut+1)),[payload,stamp,extra]=signed.split(`.`);if(cut<0||stamp===void 0||extra!==void 0||!keys.some(key=>{let expected=Buffer.from(mac(key,signed));return expected.length===signature.length&&timingSafeEqual(expected,signature)}))return invalid;let issued=parseInt(stamp,36);if(!Number.isFinite(issued))return invalid;if(verifyOptions.maxAge!==void 0&&Date.now()-issued>verifyOptions.maxAge)return{ok:!1,reason:`expired`};try{return{ok:!0,value:JSON.parse(Buffer.from(payload,`base64url`).toString()),issuedAt:new Date(issued)}}catch{return invalid}}}}const TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{APPLICATION,ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CRON_WORKER_ENV,CacheEvict,CacheResponse,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,ERROR_CHANNEL,FILTER_OPERATORS,FileUpload,Get,HANDLER_CHANNEL,HEALTH_PROBE,HealthController,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,JOB_CONTEXT_FIELD,JOB_DISPATCHER,JOB_META,Job,KickCronAdapter,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,NoJobHandlerError,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Process,Put,RAW_BODY,REQUEST_ID_HEADER,RESPOND,RESPONSE_CHANNEL,ROUTE_URLS,Repository,RequestContext,RequestHistogram,RoutePolicyTable,Scope,Service,SpaAdapter,StartupCheckError,TRACEPARENT_HEADER,UnknownAssetError,VIEW_RENDERER,Value,ViewAdapter,allOf,allowedHosts,applyHandlerResult,assertFlagTest,assets,baseEnvSchema,batch,bindRoutePolicy,bindViewRenderer,bootstrap,breachPadding,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createHandler,createLogger,createSigner,createToken,cronScheduleId,csrf,csrfGuard,ctn,defaultProblemTitle,defaultValidationError,defineAdapter,defineCheck,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,defineRouteFlag,defineSettings,describeError,disposeAll,errorHandler,evaluatePreconditions,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,getRouteFlags,groupAssetKeys,hasClassMeta,hashPassword,healthModule,helmet,isClusterPrimary,isCronJobEnabled,isInjectionToken,isRef,isReply,isRespondable,joinPaths,listCronJobs,listJobHandlers,listJobQueues,loadEnv,loadEnvFromSchema,loadSettings,matchesBearer,matchesFlagTest,materializeRouter,metricsAdapter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,offerRoutePolicy,onEnv,onPackage,originsOf,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,registerJobContext,reloadEnv,reply,reportError,reportResponse,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,resolveRouteFlags,runContributors,runCronJob,runCronJobs,runJob,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,settleBackgroundWork,stampJobContext,stripExt,toRef,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,verifyPassword,viewRendererFor,waitUntil,watch,withBuilder,withEnv};
16
16
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["\"_response\""],"sources":["../src/core/define-modules.ts","../src/core/circuit-breaker.ts","../src/core/define-plugin.ts","../src/http/cache-response.ts","../src/http/metrics.ts","../src/http/define-http-context-decorator.ts","../src/core/password.ts","../src/core/signing.ts","../src/http/middleware/trace-context.ts"],"sourcesContent":["import type { AppModuleEntry } from './app-module'\n\n/**\n * Chainable registry returned by {@link defineModules}. Extends\n * `Array<AppModuleEntry>` so it drops into `bootstrap({ modules })`\n * unchanged — the framework loader already iterates the array, so a\n * `ModuleList` IS a valid `modules` value with no special handling.\n *\n * The added affordance is `.mount(module)` returning `this` so\n * adopters can build the list fluently:\n *\n * ```ts\n * const modules = defineModules()\n * .mount(HelloModule())\n * .mount(AdminModule())\n *\n * bootstrap({ modules })\n * ```\n *\n * **Why not just use a plain array?** Two reasons. First, the\n * fluent shape reads more naturally for module-list construction —\n * adopters used to `definePlugin().scoped(...)` / `defineAdapter(...)`\n * see the same call-then-call pattern. Second, the registry is the\n * stable extension point: a future `.use(module)` for non-HTTP\n * modules (queues, cron, workers) lands as a method on `ModuleList`\n * without breaking the `Array<AppModuleEntry>` superclass contract.\n */\nexport class ModuleList extends Array<AppModuleEntry> {\n /**\n * Append a module to the list. Returns `this` for chaining.\n *\n * Accepts both class form (`SomeModule extends AppModule`) and\n * `defineModule` factory output — same as the underlying\n * `bootstrap({ modules })` array. The framework loader\n * discriminates `typeof entry === 'function'` at boot.\n */\n mount(module: AppModuleEntry): this {\n this.push(module)\n return this\n }\n}\n\n/**\n * Build a {@link ModuleList} for the application. Optional vararg\n * lets adopters seed the list inline; subsequent `.mount()` calls\n * append.\n *\n * @example\n * ```ts\n * import { bootstrap, defineModules } from '@forinda/kickjs'\n * import { HelloModule } from './modules/hello/hello.module'\n * import { AdminModule } from './modules/admin/admin.module'\n *\n * // Fluent — most common\n * const modules = defineModules()\n * .mount(HelloModule())\n * .mount(AdminModule())\n *\n * // Or seeded inline + chained\n * const modules2 = defineModules(HelloModule()).mount(AdminModule())\n *\n * await bootstrap({ modules })\n * ```\n *\n * The returned value is an `AppModuleEntry[]` subclass — `bootstrap`\n * accepts it directly without any special-casing. For conditional /\n * dynamic registration at bootstrap time (env flags, runtime config,\n * tenant lists), use the `setup(registry)` callback on `bootstrap`\n * instead — both surfaces compose.\n */\nexport function defineModules(...initial: AppModuleEntry[]): ModuleList {\n const list = new ModuleList()\n for (const entry of initial) list.push(entry)\n return list\n}\n","/**\n * Circuit Breaker pattern for external service calls.\n *\n * Protects your application from cascading failures when downstream\n * services are unhealthy by short-circuiting requests after a\n * configurable failure threshold.\n *\n * @example\n * ```ts\n * const breaker = new CircuitBreaker('payment-api', {\n * failureThreshold: 5,\n * resetTimeout: 30_000,\n * })\n *\n * const result = await breaker.execute(() => fetch('https://payment.example.com/charge'))\n * ```\n */\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half_open'\n\nexport interface CircuitBreakerOptions {\n /** Number of consecutive failures before the circuit opens. */\n failureThreshold: number\n /** Milliseconds to wait before transitioning from OPEN to HALF_OPEN. */\n resetTimeout: number\n /** Max requests allowed in HALF_OPEN state before deciding (default 1). */\n halfOpenMax?: number\n}\n\nexport interface CircuitBreakerStats {\n failures: number\n successes: number\n state: CircuitBreakerState\n lastFailure?: Date\n}\n\n/**\n * Error thrown when the circuit is open and calls are being rejected.\n */\nexport class CircuitOpenError extends Error {\n constructor(public readonly breakerName: string) {\n super(`Circuit breaker \"${breakerName}\" is open — request rejected`)\n this.name = 'CircuitOpenError'\n }\n}\n\nexport class CircuitBreaker {\n private state: CircuitBreakerState = 'closed'\n private failures = 0\n private successes = 0\n private halfOpenAttempts = 0\n private lastFailure?: Date\n private openedAt?: number\n\n private readonly failureThreshold: number\n private readonly resetTimeout: number\n private readonly halfOpenMax: number\n\n constructor(\n public readonly name: string,\n options: CircuitBreakerOptions,\n ) {\n this.failureThreshold = options.failureThreshold\n this.resetTimeout = options.resetTimeout\n this.halfOpenMax = options.halfOpenMax ?? 1\n }\n\n /**\n * Execute an async function through the circuit breaker.\n * Throws `CircuitOpenError` if the circuit is open.\n */\n async execute<T>(fn: () => Promise<T>): Promise<T> {\n this.maybeTransitionToHalfOpen()\n\n if (this.state === 'open') {\n throw new CircuitOpenError(this.name)\n }\n\n if (this.state === 'half_open' && this.halfOpenAttempts >= this.halfOpenMax) {\n throw new CircuitOpenError(this.name)\n }\n\n if (this.state === 'half_open') {\n this.halfOpenAttempts++\n }\n\n try {\n const result = await fn()\n this.onSuccess()\n return result\n } catch (error) {\n this.onFailure()\n throw error\n }\n }\n\n /** Returns the current circuit state. */\n getState(): CircuitBreakerState {\n this.maybeTransitionToHalfOpen()\n return this.state\n }\n\n /** Returns current statistics. */\n getStats(): CircuitBreakerStats {\n this.maybeTransitionToHalfOpen()\n return {\n failures: this.failures,\n successes: this.successes,\n state: this.state,\n ...(this.lastFailure ? { lastFailure: this.lastFailure } : {}),\n }\n }\n\n /** Manually reset the circuit breaker to CLOSED state. */\n reset(): void {\n this.state = 'closed'\n this.failures = 0\n this.successes = 0\n this.halfOpenAttempts = 0\n this.lastFailure = undefined\n this.openedAt = undefined\n }\n\n private onSuccess(): void {\n if (this.state === 'half_open') {\n // Recovery confirmed — close the circuit\n this.state = 'closed'\n this.failures = 0\n this.halfOpenAttempts = 0\n this.openedAt = undefined\n }\n this.successes++\n }\n\n private onFailure(): void {\n this.failures++\n this.lastFailure = new Date()\n\n if (this.state === 'half_open') {\n // Recovery failed — re-open\n this.state = 'open'\n this.openedAt = Date.now()\n this.halfOpenAttempts = 0\n } else if (this.state === 'closed' && this.failures >= this.failureThreshold) {\n this.state = 'open'\n this.openedAt = Date.now()\n }\n }\n\n private maybeTransitionToHalfOpen(): void {\n if (this.state === 'open' && this.openedAt != null) {\n if (Date.now() - this.openedAt >= this.resetTimeout) {\n this.state = 'half_open'\n this.halfOpenAttempts = 0\n }\n }\n }\n}\n","import type { Container } from './container'\nimport type { KickPlugin } from './plugin'\n\n/**\n * Options passed to {@link definePlugin}. Mirrors the spec in\n * `architecture.md` §21.3.1 + §21.2.2 (Phase A \"lite\").\n */\nexport interface DefinePluginOptions<TConfig> {\n /** Stable identity used for logging, `dependsOn` lookups, and `.scoped()` namespacing. */\n name: string\n\n /** Optional plugin version — surfaced to DevTools and `kick add` compatibility checks (Phase B). */\n version?: string\n\n /**\n * Peer-version ranges this plugin needs from the framework or other\n * plugins. Recorded as metadata; runtime enforcement lands in §21.4.4.\n */\n requires?: { kickjs?: string }\n\n /** Default config merged under any caller overrides. */\n defaults?: Partial<TConfig>\n\n /** Builds the underlying {@link KickPlugin} from the resolved config. */\n build(config: TConfig, ctx: BuildContext): Omit<KickPlugin, 'name'>\n}\n\n/**\n * Hook context handed to a plugin/adapter `build` function. `name` is the\n * resolved instance name (the bare definition name for the bare call,\n * or `${defName}:${scope}` for `.scoped()`). `scoped` is the discriminator\n * authors use to namespace DI tokens or resource keys.\n */\nexport interface BuildContext {\n name: string\n scoped: boolean\n}\n\n/**\n * Async-config form of a plugin or adapter — `inject` lists DI tokens to\n * resolve from the container, then `useFactory` produces the config.\n *\n * Plugins resolve this lazily inside `onReady`, so any module/adapter/\n * middleware/contributor a plugin contributes via `build` is **not\n * available** when `.async()` is used. Use the bare/`.scoped()` form for\n * plugins that need to register modules or middleware.\n */\nexport interface PluginAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link definePlugin}. Callable form is the singleton\n * (`AuthPlugin(config)`); `.scoped()` and `.async()` are the multi-instance\n * and deferred-config forms.\n */\nexport interface PluginFactory<TConfig> {\n (config?: Partial<TConfig>): KickPlugin\n scoped(scopeName: string, config?: Partial<TConfig>): KickPlugin\n async(opts: PluginAsyncOptions<TConfig>): KickPlugin\n /** Read-only access to the original definition — useful for DevTools introspection. */\n readonly definition: Readonly<DefinePluginOptions<TConfig>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build a {@link KickPlugin} factory from a typed definition. See\n * `architecture.md` §21.2.2 for the design rationale.\n *\n * @example\n * ```ts\n * const FlagsPlugin = definePlugin<FlagsConfig>({\n * name: 'FlagsPlugin',\n * defaults: { defaultTtl: 60_000 },\n * build(config) {\n * return {\n * register(container) {\n * container.registerInstance(FLAGS, makeProvider(config))\n * },\n * }\n * },\n * })\n *\n * bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })\n * ```\n */\nexport function definePlugin<TConfig = Record<string, unknown>>(\n options: DefinePluginOptions<TConfig>,\n): PluginFactory<TConfig> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): KickPlugin => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n const built = options.build(config, { name: instanceName, scoped }) as KickPlugin\n built.name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: PluginAsyncOptions<TConfig>): KickPlugin => {\n let inner: KickPlugin | undefined\n\n const ensureInner = async (container: Container): Promise<KickPlugin> => {\n if (inner) return inner\n const deps = (opts.inject ?? []).map((tok) => container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n return inner\n }\n\n return {\n name: instanceName,\n async onReady(container: Container) {\n const built = await ensureInner(container)\n // Run the inner plugin's register() now that we have the config —\n // late but better than never; `.async()` plugins skip the early\n // module/middleware contribution surface by design.\n built.register?.(container)\n await built.onReady?.(container)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as PluginFactory<TConfig>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: PluginAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n","/**\n * `@CacheResponse` — cache a route's whole response on the server, answer\n * `304` on a matching ETag, and serve a stale copy while a fresh one is built\n * in the background (stale-while-revalidate).\n *\n * The handler runs against a recording of the response: whatever it sends —\n * `ctx.json`, `ctx.send`, `ctx.html`, or a returned value — is captured,\n * replayed onto the real response, and stored when the status is 200. Entries\n * live in the {@link CacheProvider} (`setCacheProvider`), so a shared store\n * such as Redis serves every instance.\n *\n * Edge-safe: no node imports — shared by every runtime and the web entry.\n *\n * @module @forinda/kickjs/http/cache-response\n */\nimport { getCacheProvider } from '../core/cache'\nimport { waitUntil } from './background'\nimport type { RequestContext } from './context'\nimport { applyHandlerResult } from './reply'\nimport { stringifyJson, type RuntimeResponse } from './runtime'\n\nexport interface CacheResponseOptions {\n /** Seconds a stored response is served as fresh. */\n maxAge: number\n /**\n * Seconds past `maxAge` a stale response is still served, while one request\n * rebuilds it in the background. Default 0: past `maxAge` the next request waits.\n */\n swr?: number\n /**\n * Request headers that select a different response — `accept-language`, or\n * `authorization` for per-user responses. Their values are part of the key.\n * Every header the handler reads belongs here.\n *\n * A request that identifies its caller — `authorization`, `proxy-authorization`,\n * `x-api-key`, a `cookie`, or a signed-in `ctx.user` — skips the cache unless\n * that header is listed here: under a shared key, one user's response would\n * reach another.\n */\n varies?: string[]\n /**\n * A string is the key prefix — `@CacheEvict(prefix)` clears the route's\n * entries. Default: `kick:response:Controller.method`.\n *\n * A function decides the key per request, from the whole context — params,\n * `ctx.get('tenant')`, `ctx.user`. It owns the decision: the caller check\n * above doesn't apply, so include the user or tenant when the response\n * depends on them. Return `null` to skip the cache for that request.\n */\n key?: string | ((ctx: RequestContext) => string | null)\n}\n\n/** What a handler sent, enough to send it again. */\ninterface Recorded {\n status: number\n type?: string\n headers: Record<string, string | string[]>\n body: string\n /** `body` is base64 of bytes the handler sent. */\n binary?: boolean\n /** The handler used `ctx.res` directly: what it did there isn't recorded, so this is never stored. */\n native?: boolean\n}\n\ninterface Entry {\n recorded: Recorded\n storedAt: number\n}\n\n/** Requests that would otherwise each build the same response, by key. */\nconst inFlight = new Map<string, Promise<Recorded | null>>()\n\n/** Headers that identify the caller: a request carrying one is never cached under a shared key. */\nconst PERSONAL = ['authorization', 'proxy-authorization', 'x-api-key', 'cookie']\n\nexport function CacheResponse(options: CacheResponseOptions): MethodDecorator {\n const maxAgeMs = options.maxAge * 1000\n const swrMs = (options.swr ?? 0) * 1000\n const varies = (options.varies ?? []).map((h) => h.toLowerCase())\n\n return (target, propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value as (ctx: RequestContext, ...rest: unknown[]) => unknown\n const owner = typeof target === 'function' ? target.name : target.constructor?.name\n const prefix =\n typeof options.key === 'string'\n ? options.key\n : `kick:response:${owner ?? 'anonymous'}.${String(propertyKey)}`\n const keyOf = typeof options.key === 'function' ? options.key : undefined\n\n descriptor.value = async function (this: unknown, ctx: RequestContext, ...rest: unknown[]) {\n const req = ctx.req as { method?: string; url?: string; originalUrl?: string }\n const method = String(req.method ?? 'GET').toUpperCase()\n const headers = ctx.headers as Record<string, string | string[] | undefined>\n if ((method !== 'GET' && method !== 'HEAD') || maxAgeMs + swrMs <= 0) {\n return original.call(this, ctx, ...rest)\n }\n let identity: string\n if (keyOf) {\n const chosen = keyOf(ctx)\n if (chosen === null) return original.call(this, ctx, ...rest)\n identity = chosen\n } else {\n const personal =\n PERSONAL.some((h) => headers[h] !== undefined && !varies.includes(h)) ||\n (ctx.user !== undefined && !varies.some((h) => PERSONAL.includes(h)))\n if (personal) return original.call(this, ctx, ...rest)\n // The exact host the handler sees: one app serving several hosts answers\n // each differently, and a handler may put the host in the body. A host\n // that isn't `name[:port]` is never cached — nothing ambiguous in the key.\n const host = String(headers.host ?? '')\n if (!VALID_HOST.test(host)) return original.call(this, ctx, ...rest)\n identity = JSON.stringify([host.toLowerCase(), req.originalUrl ?? req.url ?? ''])\n }\n const varied = varies.map((h) => `${h}=${String(headers[h] ?? '')}`).join('&')\n const key = `${prefix}:${identity}|${varied}`\n const provider = getCacheProvider()\n const run = () => record(original, this, ctx, rest)\n const build = () => buildOnce(key, run)\n const store = async ({ recorded, shared }: Built) => {\n // The request that ran the handler stores it; the ones that waited don't again.\n if (!shared && recorded && cacheable(recorded)) {\n const entry: Entry = { recorded, storedAt: Date.now() }\n await provider.set(key, entry, maxAgeMs + swrMs)\n }\n }\n\n const entry = (await provider.get(key)) as Entry | null\n if (entry) {\n const age = Date.now() - entry.storedAt\n if (age < maxAgeMs + swrMs) {\n // Stale: answer now, rebuild for the next request.\n if (age >= maxAgeMs) waitUntil(build().then(store))\n replay(ctx, entry.recorded)\n return undefined\n }\n }\n\n const built = await build()\n await store(built)\n let recorded = built.recorded\n // A response that isn't shared — a cookie, a 404, ctx.res — belongs to the\n // request that produced it: one that only waited for it runs the handler itself.\n if (built.shared && !(recorded && cacheable(recorded))) recorded = await run()\n if (recorded) replay(ctx, recorded)\n return undefined\n }\n return descriptor\n }\n}\n\n/** `name[:port]` or `[ipv6][:port]` — no path, userinfo or whitespace. */\nconst VALID_HOST = /^(?:\\[[0-9a-f:.]+\\]|[a-z0-9-]+(?:\\.[a-z0-9-]+)*)(?::\\d{1,5})?$/i\n\n/** A build's result, and whether this request only waited for another one's. */\ninterface Built {\n recorded: Recorded | null\n shared: boolean\n}\n\n/** Concurrent misses on one key share a single build. */\nasync function buildOnce(key: string, run: () => Promise<Recorded | null>): Promise<Built> {\n const pending = inFlight.get(key)\n if (pending) return { recorded: await pending, shared: true }\n const load = run().finally(() => inFlight.delete(key))\n inFlight.set(key, load)\n return { recorded: await load, shared: false }\n}\n\n/** Only a 200 that sets no cookie, written through ctx alone, is shared. */\nfunction cacheable(recorded: Recorded): boolean {\n return recorded.status === 200 && !('set-cookie' in recorded.headers) && !recorded.native\n}\n\n/**\n * Run the handler against a context whose response is a recording. Null when\n * it sent nothing — the request then falls through as it would uncached.\n */\nasync function record(\n handler: (ctx: RequestContext, ...rest: unknown[]) => unknown,\n self: unknown,\n ctx: RequestContext,\n rest: unknown[],\n): Promise<Recorded | null> {\n const recorded: Recorded = { status: 200, headers: {}, body: '' }\n let sent = false\n const finish = (body: unknown) => {\n if (body instanceof Uint8Array) {\n recorded.body = toBase64(body)\n recorded.binary = true\n } else if (typeof body === 'string') {\n recorded.body = body\n } else if (body !== undefined && body !== null) {\n recorded.type ??= 'application/json; charset=utf-8'\n recorded.body = stringifyJson(body)\n }\n sent = true\n }\n const unsupported = (what: string) => () => {\n throw new Error(\n `@CacheResponse: the handler called ${what}. A cached route answers with ` +\n 'ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.',\n )\n }\n const response = {\n status(code: number) {\n recorded.status = code\n return response\n },\n type(contentType: string) {\n recorded.type = contentType\n return response\n },\n json(data: unknown) {\n recorded.type ??= 'application/json; charset=utf-8'\n recorded.body = stringifyJson(data)\n sent = true\n return response\n },\n send(data: unknown) {\n finish(data)\n return response\n },\n end(data?: unknown) {\n finish(data)\n return response\n },\n setHeader(name: string, value: string | number | readonly string[]) {\n recorded.headers[name.toLowerCase()] = Array.isArray(value)\n ? [...(value as readonly string[])]\n : String(value)\n },\n get headersSent() {\n return sent\n },\n once() {},\n render: unsupported('render()'),\n writeHead: unsupported('writeHead()'),\n flushHeaders: unsupported('flushHeaders()'),\n write: unsupported('write()'),\n }\n // `ctx.res` is the engine's own response: what a handler does to it directly\n // (a header, a cookie) isn't recorded, so any use of it marks the response unshareable.\n const native = new Proxy(ctx.res as object, {\n get(target, prop) {\n const value = Reflect.get(target, prop, target)\n if (typeof value !== 'function') return value\n return (...args: unknown[]) => {\n recorded.native = true\n return value.apply(target, args)\n }\n },\n set(target, prop, value) {\n recorded.native = true\n return Reflect.set(target, prop, value, target)\n },\n })\n // Everything else is the real request's: params, query, headers, metadata.\n const recordingCtx = Object.create(ctx, {\n _response: { value: response as unknown as RuntimeResponse },\n res: { value: native },\n }) as RequestContext\n const result = await handler.call(self, recordingCtx, ...rest)\n if (!sent) await applyHandlerResult(recordingCtx, result)\n return sent ? recorded : null\n}\n\n/** Send a recorded response — `304` when the client's copy is current. */\nfunction replay(ctx: RequestContext, recorded: Recorded): void {\n // The handler already answered through ctx.res itself.\n if (ctx['_response'].headersSent) return\n for (const [name, value] of Object.entries(recorded.headers)) {\n if (name !== 'etag' && name !== 'content-type') ctx.setHeader(name, value)\n }\n if (recorded.status === 200) {\n const etag = (recorded.headers.etag as string | undefined) ?? weakEtag(recorded.body)\n if (ctx.conditional({ etag })) return\n }\n const options = { status: recorded.status, type: recorded.type ?? 'text/plain; charset=utf-8' }\n ctx.send(recorded.binary ? fromBase64(recorded.body) : recorded.body, options)\n}\n\n/** A weak ETag from the body — FNV-1a, enough to tell versions apart. */\nfunction weakEtag(body: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < body.length; i++) {\n hash ^= body.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return `W/\"${body.length.toString(16)}-${(hash >>> 0).toString(16)}\"`\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(binary)\n}\n\nfunction fromBase64(text: string): Uint8Array {\n const binary = atob(text)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n","/**\n * `/metrics` in the Prometheus text format: a request-duration histogram per\n * route pattern, plus process health (memory, heap, event-loop lag).\n *\n * @module @forinda/kickjs/http/metrics\n */\nimport { monitorEventLoopDelay } from 'node:perf_hooks'\nimport type { AppAdapter, AdapterContext } from '../core/adapter'\nimport type { ResponseInfo } from '../core/observers'\nimport { matchesBearer } from '../core/web-crypto'\nimport type { RequestContext } from './context'\n\nexport interface MetricsOptions {\n /** Where to serve the metrics. Default `/metrics`. */\n path?: string\n /**\n * Require `Authorization: Bearer <token>` to read them. The endpoint is\n * mounted before the app's middleware (so a scraper doesn't need your\n * auth), which also means your auth doesn't cover it — set this unless\n * the port is only reachable by the scraper.\n */\n token?: string\n /** Histogram buckets, in seconds. Default: Prometheus' defaults, 5ms to 10s. */\n buckets?: number[]\n /**\n * Serve the metrics on the management port (`bootstrap({ management: { port } })`)\n * instead of the app's — reachable by the scraper, not the public. Without a\n * management port it stays on the app's.\n */\n management?: boolean\n}\n\nconst DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]\n\n/** Label values per the exposition format: backslash, quote and newline escaped. */\nconst label = (value: string) =>\n value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n')\n\ninterface Series {\n labels: string\n counts: number[]\n sum: number\n count: number\n}\n\n/** The request histogram, keyed by its label set. */\nexport class RequestHistogram {\n private readonly series = new Map<string, Series>()\n\n private readonly buckets: readonly number[]\n\n /**\n * Bounds in seconds — sorted and deduplicated here, since the exposition\n * format needs them strictly increasing; anything not a finite positive\n * number is rejected.\n */\n constructor(buckets: readonly number[] = DEFAULT_BUCKETS) {\n if (buckets.length === 0 || buckets.some((b) => !Number.isFinite(b) || b <= 0)) {\n throw new Error('metrics: buckets must be finite positive numbers (seconds)')\n }\n this.buckets = [...new Set(buckets)].toSorted((a, b) => a - b)\n }\n\n observe(info: Pick<ResponseInfo, 'method' | 'route' | 'status' | 'durationMs'>): void {\n // The route pattern, never the raw path: `/users/42` and `/users/43` are\n // one series, and a scan of random URLs adds one series (`unmatched`),\n // not one per URL.\n const labels =\n `method=\"${label(knownMethod(info.method))}\",route=\"${label(info.route ?? 'unmatched')}\",` +\n `status=\"${info.status}\"`\n let series = this.series.get(labels)\n if (!series) {\n series = { labels, counts: this.buckets.map(() => 0), sum: 0, count: 0 }\n this.series.set(labels, series)\n }\n const seconds = info.durationMs / 1000\n for (const [i, bound] of this.buckets.entries()) if (seconds <= bound) series.counts[i]++\n series.sum += seconds\n series.count++\n }\n\n render(): string {\n const name = 'http_request_duration_seconds'\n const lines = [\n `# HELP ${name} Time to answer an HTTP request, by route pattern.`,\n `# TYPE ${name} histogram`,\n ]\n for (const s of this.series.values()) {\n for (const [i, bound] of this.buckets.entries()) {\n lines.push(`${name}_bucket{${s.labels},le=\"${bound}\"} ${s.counts[i]}`)\n }\n lines.push(`${name}_bucket{${s.labels},le=\"+Inf\"} ${s.count}`)\n lines.push(`${name}_sum{${s.labels}} ${s.sum}`)\n lines.push(`${name}_count{${s.labels}} ${s.count}`)\n }\n return lines.join('\\n')\n }\n}\n\nconst METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'QUERY'])\n\n/**\n * The method as a label, or `OTHER`. Node only parses known methods, but a\n * fetch-based host (Bun, Deno) passes any token through, and each one would\n * start a series.\n */\nfunction knownMethod(method: string): string {\n const upper = method.toUpperCase()\n return METHODS.has(upper) ? upper : 'OTHER'\n}\n\nfunction gauge(name: string, help: string, value: number): string {\n return `# HELP ${name} ${help}\\n# TYPE ${name} gauge\\n${name} ${value}`\n}\n\n/**\n * Serve Prometheus metrics. Add it to `adapters`:\n *\n * ```ts\n * bootstrap({ modules, adapters: [metricsAdapter({ token: process.env.METRICS_TOKEN })] })\n * ```\n */\nexport function metricsAdapter(options: MetricsOptions = {}): AppAdapter {\n const path = options.path ?? '/metrics'\n const histogram = new RequestHistogram(options.buckets ?? DEFAULT_BUCKETS)\n let loop: ReturnType<typeof monitorEventLoopDelay> | undefined\n\n const render = () => {\n const memory = process.memoryUsage()\n const lag = loop && loop.count > 0 ? loop.mean / 1e9 : 0\n return [\n histogram.render(),\n gauge('process_resident_memory_bytes', 'Resident set size.', memory.rss),\n gauge('nodejs_heap_used_bytes', 'V8 heap in use.', memory.heapUsed),\n gauge('nodejs_heap_total_bytes', 'V8 heap allocated.', memory.heapTotal),\n gauge('nodejs_eventloop_lag_seconds', 'Mean event-loop delay since the last scrape.', lag),\n gauge('process_uptime_seconds', 'Seconds since the process started.', process.uptime()),\n ].join('\\n\\n')\n }\n\n return {\n name: 'MetricsAdapter',\n beforeMount({ http: appHttp, management }: AdapterContext) {\n const http = options.management && management ? management.http : appHttp\n loop = monitorEventLoopDelay({ resolution: 20 })\n loop.enable()\n http.route('GET', path, (ctx: RequestContext) => {\n const { token } = options\n if (token !== undefined && !matchesBearer(ctx.headers.authorization, token)) {\n ctx.setHeader('WWW-Authenticate', 'Bearer')\n ctx.json({ message: 'Unauthorized' }, 401)\n return\n }\n const body = render()\n // Lag is \"since the last scrape\": start the next window now.\n loop?.reset()\n ctx.setHeader('Cache-Control', 'no-store')\n ctx.send(`${body}\\n`, { type: 'text/plain; version=0.0.4; charset=utf-8' })\n })\n },\n onResponse(info: ResponseInfo) {\n // The scrape itself is not a request worth measuring.\n if (info.route === path) return\n histogram.observe(info)\n },\n shutdown() {\n loop?.disable()\n },\n }\n}\n","/**\n * HTTP-flavoured wrapper around {@link defineContextDecorator}.\n *\n * The core factory leaves `Ctx` defaulted to {@link ExecutionContext} so the\n * Context Contributor pipeline stays transport-agnostic — future WebSocket,\n * queue, and cron contexts share the same primitive. The cost is that the\n * vast majority of contributors (which are HTTP) have to spell the fourth\n * generic by hand to get `ctx.req` / `ctx.headers` typing:\n *\n * ```ts\n * // Verbose: spell every generic, including the params shape `P`.\n * defineContextDecorator<'tenant', Record<string, never>, Record<string, never>, RequestContext>({\n * key: 'tenant',\n * resolve: (ctx) => ({ id: ctx.req.headers['x-tenant-id'] as string }),\n * })\n * ```\n *\n * `defineHttpContextDecorator` removes that ceremony — the spec is typed\n * against `RequestContext` from the start, so resolvers can read `ctx.req`,\n * `ctx.headers`, `ctx.params`, etc. without a cast or generic dance:\n *\n * ```ts\n * import { defineHttpContextDecorator } from '@forinda/kickjs'\n *\n * const LoadTenant = defineHttpContextDecorator({\n * key: 'tenant',\n * resolve: (ctx) => ({ id: ctx.req.headers['x-tenant-id'] as string }),\n * })\n *\n * // Parameterised — the positional form forces you to also spell `K`\n * // and `D`, which loses automatic `deps` inference. Prefer the curried\n * // `.withParams<P>()` entry point below.\n * const LoadTenantParameterised = defineHttpContextDecorator<\n * 'tenant',\n * Record<string, never>,\n * { source: 'header' | 'subdomain' }\n * >({\n * key: 'tenant',\n * paramDefaults: { source: 'header' },\n * resolve: (ctx, _deps, params) => {\n * // params.source narrows inside `if` branches.\n * },\n * })\n *\n * // Parameterised + deps — only `P` is spelled; `K` and `D` infer from\n * // the spec, so `deps.repo` is fully typed in the resolver.\n * const LoadTenantWithRepo = defineHttpContextDecorator.withParams<{\n * source: 'header' | 'subdomain'\n * }>()({\n * key: 'tenant',\n * deps: { repo: TENANT_REPO },\n * paramDefaults: { source: 'header' },\n * resolve: (ctx, { repo }, params) =>\n * repo.findFor(ctx.req.headers['x-tenant-id'] as string, params.source),\n * })\n * ```\n *\n * Use {@link defineContextDecorator} directly when authoring contributors\n * for non-HTTP transports or when you want to share one contributor across\n * HTTP + WS + queue (the resolver then has to stick to the\n * `ExecutionContext` surface — `ctx.get` / `ctx.set` / `ctx.requestId`).\n */\n\nimport {\n defineContextDecorator,\n type ContextDecorator,\n type ContextDecoratorSpec,\n type ContextMetaKey,\n type DepValue,\n} from '../core/context-decorator'\nimport type { RequestContext } from './context'\n\n/**\n * Curried form returned by {@link DefineHttpContextDecoratorFn.withParams}.\n * Spell only the per-call params shape `P`; `K` and `D` are inferred\n * from the spec, and `Ctx` is locked to `RequestContext`.\n */\nexport interface DefineHttpContextDecoratorWithParams<P extends Record<string, unknown>> {\n <K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>>(\n spec: ContextDecoratorSpec<K, D, P, RequestContext>,\n ): ContextDecorator<K, D, P, RequestContext>\n}\n\n/**\n * Public shape of {@link defineHttpContextDecorator} — the positional\n * call signature plus the curried `.withParams<P>()` helper that fixes\n * partial-inference for the parameterised case.\n */\nexport interface DefineHttpContextDecoratorFn {\n <\n K extends ContextMetaKey,\n D extends Record<string, DepValue> = Record<string, never>,\n P extends Record<string, unknown> = Record<string, never>,\n >(\n spec: ContextDecoratorSpec<K, D, P, RequestContext>,\n ): ContextDecorator<K, D, P, RequestContext>\n\n /**\n * Curried entry point. Spell only `P`; `K` and `D` infer from the\n * spec. `Ctx` is locked to `RequestContext`.\n *\n * ```ts\n * const LoadTenant = defineHttpContextDecorator.withParams<{\n * source: 'header' | 'subdomain'\n * }>()({\n * key: 'tenant',\n * deps: { repo: TENANT_REPO }, // D inferred\n * paramDefaults: { source: 'header' },\n * resolve: (ctx, { repo }, params) => repo.findFor(ctx, params),\n * })\n * ```\n */\n withParams<P extends Record<string, unknown>>(): DefineHttpContextDecoratorWithParams<P>\n}\n\nfunction defineHttpContextDecoratorImpl<\n K extends ContextMetaKey,\n D extends Record<string, DepValue> = Record<string, never>,\n P extends Record<string, unknown> = Record<string, never>,\n>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext> {\n return defineContextDecorator<K, D, P, RequestContext>(spec)\n}\n\nexport const defineHttpContextDecorator: DefineHttpContextDecoratorFn = Object.freeze(\n Object.assign(defineHttpContextDecoratorImpl, {\n withParams: <P extends Record<string, unknown>>(): DefineHttpContextDecoratorWithParams<P> => {\n return <K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>>(\n spec: ContextDecoratorSpec<K, D, P, RequestContext>,\n ): ContextDecorator<K, D, P, RequestContext> => defineHttpContextDecoratorImpl<K, D, P>(spec)\n },\n }),\n) as DefineHttpContextDecoratorFn\n","/**\n * Password hashing with scrypt — salted, memory-hard, and self-describing,\n * so the cost can be raised later and old hashes upgrade on the next login:\n *\n * ```ts\n * const stored = await hashPassword(input) // at sign-up\n *\n * const { ok, needsRehash } = await verifyPassword(input, user?.passwordHash)\n * if (!ok) throw HttpException.unauthorized()\n * if (needsRehash) await users.update(user.id, { passwordHash: await hashPassword(input) })\n * ```\n *\n * Node only (`node:crypto` scrypt); not part of the web entry.\n *\n * @module @forinda/kickjs/core/password\n */\nimport { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from 'node:crypto'\n\n/** scrypt cost. Memory per hash is `128 * N * r` bytes. */\nexport interface PasswordHashOptions {\n /** CPU/memory cost, a power of two. Default `2 ** 14`. */\n N?: number\n /** Block size. Default `8`. */\n r?: number\n /** Parallelism. Default `5`. */\n p?: number\n}\n\n// OWASP's scrypt option with 16 MiB per hash (N=2^14, r=8, p=5); Django's\n// defaults too. Raising N later marks existing hashes `needsRehash`.\nconst DEFAULTS = { N: 2 ** 14, r: 8, p: 5 }\nconst SALT_BYTES = 16\nconst KEY_BYTES = 64\n\nfunction derive(password: string, salt: Buffer, cost: Required<PasswordHashOptions>) {\n // What OpenSSL allocates (128 * r * (N + p + 2)), plus slack; `256 * N * r`\n // alone is too little when p is large next to N.\n const options: ScryptOptions = {\n ...cost,\n maxmem: 128 * cost.r * (cost.N + cost.p + 2) + 1024 * 1024,\n }\n return new Promise<Buffer>((resolve, reject) =>\n // NFKC, as NIST 800-63B suggests: the same password typed on another\n // keyboard or OS (composed vs decomposed accents) still matches.\n scrypt(password.normalize('NFKC'), salt, KEY_BYTES, options, (err, key) =>\n err ? reject(err) : resolve(key),\n ),\n )\n}\n\nfunction costOf(options: PasswordHashOptions): Required<PasswordHashOptions> {\n const cost = { ...DEFAULTS, ...options }\n if (!Number.isInteger(Math.log2(cost.N)) || cost.N < 2) {\n throw new Error('hashPassword: N must be a power of two')\n }\n return cost\n}\n\n/**\n * Hash a password for storage: `scrypt$N$r$p$salt$hash`, salt and hash in\n * base64. The same password hashes differently every time.\n */\nexport async function hashPassword(\n password: string,\n options: PasswordHashOptions = {},\n): Promise<string> {\n const cost = costOf(options)\n const salt = randomBytes(SALT_BYTES)\n const key = await derive(password, salt, cost)\n const encoded = [salt, key].map((bytes) => bytes.toString('base64'))\n return ['scrypt', cost.N, cost.r, cost.p, ...encoded].join('$')\n}\n\n/** What {@link verifyPassword} returns. */\nexport interface PasswordCheck {\n /** The password matches. */\n ok: boolean\n /**\n * The hash was made with a different cost than `options` (the defaults):\n * hash the password again and store it. Only ever true when `ok` is.\n */\n needsRehash: boolean\n}\n\n/**\n * A hash format from before scrypt — bcrypt or argon2 rows imported from\n * another system. It still verifies; on success `needsRehash` is true, so the\n * account moves to scrypt at its next login.\n *\n * ```ts\n * import bcrypt from 'bcrypt'\n * const bcryptHashes: LegacyHasher = {\n * matches: (stored) => /^\\$2[aby]\\$/.test(stored),\n * verify: (password, stored) => bcrypt.compare(password, stored),\n * dummy: await bcrypt.hash('dummy', 12), // the cost your rows use\n * }\n * await verifyPassword(input, user?.passwordHash, { legacy: [bcryptHashes] })\n * ```\n */\nexport interface LegacyHasher {\n /** Whether `stored` is in this format — by prefix (`$2b$` for bcrypt, `$argon2id$`). */\n matches(stored: string): boolean\n /** Whether `password` matches `stored`: the library's own check. */\n verify(password: string, stored: string): boolean | Promise<boolean>\n /**\n * A hash in this format, of any password, at the cost the rows it\n * `matches` use. Every check runs scrypt once and each legacy hasher once —\n * against this when the account isn't in its format — so a login takes as\n * long for a scrypt account, an imported one or a missing one, and timing\n * can't tell them apart. Rows at several costs: one hasher per cost, each\n * matching its own (bcrypt's `$2b$10$` vs `$2b$12$`) with a dummy at that\n * cost; every login then runs all of them and takes the slowest's time.\n */\n dummy: string\n}\n\n/** {@link verifyPassword}'s options: the scrypt cost, and older formats that still verify. */\nexport interface VerifyPasswordOptions extends PasswordHashOptions {\n /** Formats besides scrypt, tried in order on a hash scrypt can't read. */\n legacy?: readonly LegacyHasher[]\n}\n\n// What a missing user is checked against: the same work as a real check.\nconst DUMMY_SALT = randomBytes(SALT_BYTES)\n\n/**\n * Check a password against a stored hash. Constant-time, and pass\n * `undefined` for a user that doesn't exist: the password is still hashed,\n * so a missing account takes as long to reject as a wrong password and the\n * timing doesn't reveal which accounts exist. A hash not in this format\n * (another algorithm, or corrupt) fails rather than throws, unless one of\n * `options.legacy` reads it.\n */\nexport async function verifyPassword(\n password: string,\n stored: string | null | undefined,\n options: VerifyPasswordOptions = {},\n): Promise<PasswordCheck> {\n const { legacy = [], ...scryptCost } = options\n const parsed = stored ? parse(stored) : undefined\n const older = !parsed && stored ? legacy.find((hasher) => matches(hasher, stored)) : undefined\n // The same work on every path: scrypt once, and each legacy hasher once —\n // on its dummy unless the account is in its format.\n const [scrypt, checks] = await Promise.all([\n // Costs OpenSSL still refuses (N >= 2^(16r) with a small r) fail, not throw.\n parsed\n ? derive(password, parsed.salt, parsed.cost).catch(() => undefined)\n : derive(password, DUMMY_SALT, costOf(scryptCost)),\n Promise.all(\n legacy.map((hasher) => check(hasher, password, hasher === older ? stored! : hasher.dummy)),\n ),\n ])\n if (older) {\n const ok = checks[legacy.indexOf(older)]!\n return { ok, needsRehash: ok }\n }\n // No such user, or a hash nobody here reads: the work is done, and it fails.\n if (!parsed || !scrypt) return { ok: false, needsRehash: false }\n const ok = scrypt.length === parsed.key.length && timingSafeEqual(scrypt, parsed.key)\n const wanted = costOf(scryptCost)\n const needsRehash =\n ok && (parsed.cost.N !== wanted.N || parsed.cost.r !== wanted.r || parsed.cost.p !== wanted.p)\n return { ok, needsRehash }\n}\n\n/** Whether `hasher` reads `stored`; a matcher that throws on a malformed row doesn't. */\nfunction matches(hasher: LegacyHasher, stored: string): boolean {\n try {\n return hasher.matches(stored) === true\n } catch {\n return false\n }\n}\n\n/** A legacy hasher's verdict: only `true` is a match; a throw (a malformed row) is not. */\nfunction check(hasher: LegacyHasher, password: string, hash: string): Promise<boolean> {\n return Promise.resolve()\n .then(() => hasher.verify(password, hash))\n .then(\n (result) => result === true,\n () => false,\n )\n}\n\nfunction parse(stored: string) {\n const [algorithm, N, r, pp, salt, key] = stored.split('$')\n if (algorithm !== 'scrypt' || key === undefined) return undefined\n const cost = { N: Number(N), r: Number(r), p: Number(pp) }\n // A hash from elsewhere can't make verification allocate gigabytes: at most\n // 256 MiB (128 * N * r), sixteen times the default.\n if (\n !Number.isInteger(Math.log2(cost.N)) ||\n cost.N < 2 ||\n !Number.isInteger(cost.r) ||\n cost.r < 1 ||\n cost.r > 32 ||\n !Number.isInteger(cost.p) ||\n cost.p < 1 ||\n cost.p > 16 ||\n 128 * cost.N * cost.r > 2 ** 28\n ) {\n return undefined\n }\n return { cost, salt: Buffer.from(salt, 'base64'), key: Buffer.from(key, 'base64') }\n}\n","/**\n * Signed, timestamped tokens — a password-reset link, an unsubscribe link,\n * an email-confirmation code — that the server can verify later without\n * storing them:\n *\n * ```ts\n * const resets = createSigner({ secret: process.env.SIGNING_SECRET!, salt: 'password-reset' })\n *\n * const token = resets.sign({ userId: user.id }) // put it in the link\n * const check = resets.verify<{ userId: string }>(token, { maxAge: 60 * 60_000 })\n * if (!check.ok) throw HttpException.badRequest(check.reason) // 'invalid' | 'expired'\n * ```\n *\n * The value is signed, not encrypted: anyone holding the token can read it.\n * Node only (`node:crypto` HMAC); not part of the web entry.\n *\n * @module @forinda/kickjs/core/signing\n */\nimport { createHmac, timingSafeEqual } from 'node:crypto'\n\nexport interface SignerOptions {\n /**\n * The signing secret. Pass a list to rotate: the first signs, every one\n * verifies. Drop the old one once its tokens have expired.\n */\n secret: string | string[]\n /**\n * What the tokens are for — `'password-reset'`, `'unsubscribe'`. Signers\n * with different salts reject each other's tokens even with the same\n * secret, so a token issued for one purpose can't be used for another.\n */\n salt: string\n}\n\nexport interface VerifyOptions {\n /** Reject tokens older than this, in milliseconds. */\n maxAge?: number\n}\n\n/** What {@link Signer.verify} returns. */\nexport type SignedCheck<T> =\n | { ok: true; value: T; issuedAt: Date }\n | { ok: false; reason: 'invalid' | 'expired' }\n\nexport interface Signer {\n /** Sign a JSON-serialisable value: `payload.timestamp.signature`, URL-safe. */\n sign(value: unknown): string\n /** Check a token's signature and, with `maxAge`, its age. Never throws. */\n verify<T = unknown>(token: string, options?: VerifyOptions): SignedCheck<T>\n}\n\n/** Create a signer for one purpose. */\nexport function createSigner(options: SignerOptions): Signer {\n const secrets = Array.isArray(options.secret) ? options.secret : [options.secret]\n if (secrets.length === 0 || secrets.some((s) => typeof s !== 'string' || s.length === 0)) {\n throw new Error('createSigner: `secret` must be a non-empty string or list of strings')\n }\n if (!options.salt) throw new Error('createSigner: `salt` names what the tokens are for')\n // One key per secret and purpose, so the raw secret never signs directly.\n const keys = secrets.map((secret) =>\n createHmac('sha256', secret).update(`kickjs.signing:${options.salt}`).digest(),\n )\n const mac = (key: Buffer, data: string) =>\n createHmac('sha256', key).update(data).digest('base64url')\n\n return {\n sign(value) {\n const json = JSON.stringify(value)\n if (json === undefined) throw new Error('signer.sign: the value must be JSON-serialisable')\n const payload = Buffer.from(json).toString('base64url')\n const signed = `${payload}.${Date.now().toString(36)}`\n return `${signed}.${mac(keys[0], signed)}`\n },\n verify<T>(token: string, verifyOptions: VerifyOptions = {}): SignedCheck<T> {\n const invalid = { ok: false, reason: 'invalid' } as const\n if (typeof token !== 'string') return invalid\n const cut = token.lastIndexOf('.')\n const signed = token.slice(0, cut)\n const signature = Buffer.from(token.slice(cut + 1))\n const [payload, stamp, extra] = signed.split('.')\n if (cut < 0 || stamp === undefined || extra !== undefined) return invalid\n const matches = keys.some((key) => {\n const expected = Buffer.from(mac(key, signed))\n return expected.length === signature.length && timingSafeEqual(expected, signature)\n })\n if (!matches) return invalid\n const issued = parseInt(stamp, 36)\n if (!Number.isFinite(issued)) return invalid\n if (verifyOptions.maxAge !== undefined && Date.now() - issued > verifyOptions.maxAge) {\n return { ok: false, reason: 'expired' }\n }\n try {\n const value = JSON.parse(Buffer.from(payload, 'base64url').toString()) as T\n return { ok: true, value, issuedAt: new Date(issued) }\n } catch {\n return invalid\n }\n },\n }\n}\n","import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\nimport { requestStore } from '../request-store'\n\nimport { randomHex } from '../../core/web-crypto'\n\n/**\n * W3C Trace Context header name.\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n */\nexport const TRACEPARENT_HEADER = 'traceparent'\n\n/** Regex for a valid W3C traceparent: {version}-{trace-id}-{parent-id}-{flags} */\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/\n\nexport interface TraceContextOptions {\n /**\n * When true, respond with a `traceresponse` header containing the trace ID.\n * Useful for debugging. Default: false.\n */\n propagateResponse?: boolean\n}\n\n/**\n * Parsed W3C trace context fields.\n */\nexport interface TraceContext {\n /** W3C traceparent version (usually '00') */\n version: string\n /** 32-hex-char distributed trace ID */\n traceId: string\n /** 16-hex-char parent span ID */\n parentSpanId: string\n /** 2-hex-char trace flags */\n flags: string\n}\n\n/**\n * Generate a random 32-hex-character trace ID.\n */\nfunction generateTraceId(): string {\n return randomHex(16)\n}\n\n/**\n * Generate a random 16-hex-character span ID.\n */\nfunction generateSpanId(): string {\n return randomHex(8)\n}\n\n/**\n * Parse a W3C traceparent header value.\n * Returns null if the format is invalid.\n */\nexport function parseTraceparent(header: string): TraceContext | null {\n const match = TRACEPARENT_RE.exec(header.trim().toLowerCase())\n if (!match) return null\n\n const version = match[1]\n const traceId = match[2]\n const parentSpanId = match[3]\n const flags = match[4]\n\n // W3C spec: version ff is invalid, all-zero trace-id and parent-id are invalid\n if (\n version === 'ff' ||\n traceId === '00000000000000000000000000000000' ||\n parentSpanId === '0000000000000000'\n ) {\n return null\n }\n\n return { version, traceId, parentSpanId, flags }\n}\n\n/**\n * Middleware that extracts W3C `traceparent` header and stores trace context\n * in the request's AsyncLocalStorage store.\n *\n * If no valid `traceparent` header is present, a new traceId is generated\n * so that every request always has a trace ID available for correlation.\n *\n * Must be mounted **after** `requestScopeMiddleware()` (which creates the store).\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [\n * requestScopeMiddleware(),\n * traceContext(), // extracts or generates traceId\n * requestLogger(),\n * express.json(),\n * ],\n * })\n * ```\n */\nexport function traceContext(options: TraceContextOptions = {}) {\n return (req: Request, res: Response, next: NextFunction) => {\n const store = requestStore.getStore()\n\n const traceparentHeader = req.headers[TRACEPARENT_HEADER]\n const raw = Array.isArray(traceparentHeader) ? traceparentHeader[0] : traceparentHeader\n const parsed = raw ? parseTraceparent(raw) : null\n\n const traceId = parsed?.traceId ?? generateTraceId()\n const spanId = generateSpanId()\n\n // Attach to the request store so logger + downstream code can access it\n if (store) {\n store.values.set('traceId', traceId)\n store.values.set('spanId', spanId)\n if (parsed) {\n store.values.set('parentSpanId', parsed.parentSpanId)\n store.values.set('traceFlags', parsed.flags)\n store.values.set('traceVersion', parsed.version)\n }\n }\n\n // Also expose on req for convenience\n ;(req as any).traceId = traceId\n ;(req as any).spanId = spanId\n\n if (options.propagateResponse) {\n res.setHeader('traceresponse', traceId)\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;shLA2BA,IAAa,WAAb,cAAgC,KAAsB,CASpD,MAAM,OAA8B,CAElC,OADA,KAAK,KAAK,MAAM,EACT,IACT,CACF,EA8BA,SAAgB,cAAc,GAAG,QAAuC,CACtE,IA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,QAA+B,CAAC,EAAG,CAC9D,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAM,MAAQ,aAAa,SAAS,EAE9B,kBAAoB,IAAI,QAAQ,oBAChC,IAAM,MAAM,QAAQ,iBAAiB,EAAI,kBAAkB,GAAK,kBAChE,OAAS,IAAM,iBAAiB,GAAG,EAAI,KAEvC,QAAU,QAAQ,SAAW,gBAAgB,EAC7C,OAAS,eAAe,EAG1B,QACF,MAAM,OAAO,IAAI,UAAW,OAAO,EACnC,MAAM,OAAO,IAAI,SAAU,MAAM,EAC7B,SACF,MAAM,OAAO,IAAI,eAAgB,OAAO,YAAY,EACpD,MAAM,OAAO,IAAI,aAAc,OAAO,KAAK,EAC3C,MAAM,OAAO,IAAI,eAAgB,OAAO,OAAO,IAKlD,IAAa,QAAU,QACvB,IAAa,OAAS,OAEnB,QAAQ,mBACV,IAAI,UAAU,gBAAiB,OAAO,EAGxC,KAAK,CACP,CACF"}
1
+ {"version":3,"file":"index.mjs","names":["\"_response\""],"sources":["../src/core/define-modules.ts","../src/core/circuit-breaker.ts","../src/core/define-plugin.ts","../src/http/cache-response.ts","../src/http/metrics.ts","../src/http/define-http-context-decorator.ts","../src/core/password.ts","../src/core/signing.ts","../src/http/middleware/trace-context.ts"],"sourcesContent":["import type { AppModuleEntry } from './app-module'\n\n/**\n * Chainable registry returned by {@link defineModules}. Extends\n * `Array<AppModuleEntry>` so it drops into `bootstrap({ modules })`\n * unchanged — the framework loader already iterates the array, so a\n * `ModuleList` IS a valid `modules` value with no special handling.\n *\n * The added affordance is `.mount(module)` returning `this` so\n * adopters can build the list fluently:\n *\n * ```ts\n * const modules = defineModules()\n * .mount(HelloModule())\n * .mount(AdminModule())\n *\n * bootstrap({ modules })\n * ```\n *\n * **Why not just use a plain array?** Two reasons. First, the\n * fluent shape reads more naturally for module-list construction —\n * adopters used to `definePlugin().scoped(...)` / `defineAdapter(...)`\n * see the same call-then-call pattern. Second, the registry is the\n * stable extension point: a future `.use(module)` for non-HTTP\n * modules (queues, cron, workers) lands as a method on `ModuleList`\n * without breaking the `Array<AppModuleEntry>` superclass contract.\n */\nexport class ModuleList extends Array<AppModuleEntry> {\n /**\n * Append a module to the list. Returns `this` for chaining.\n *\n * Accepts both class form (`SomeModule extends AppModule`) and\n * `defineModule` factory output — same as the underlying\n * `bootstrap({ modules })` array. The framework loader\n * discriminates `typeof entry === 'function'` at boot.\n */\n mount(module: AppModuleEntry): this {\n this.push(module)\n return this\n }\n}\n\n/**\n * Build a {@link ModuleList} for the application. Optional vararg\n * lets adopters seed the list inline; subsequent `.mount()` calls\n * append.\n *\n * @example\n * ```ts\n * import { bootstrap, defineModules } from '@forinda/kickjs'\n * import { HelloModule } from './modules/hello/hello.module'\n * import { AdminModule } from './modules/admin/admin.module'\n *\n * // Fluent — most common\n * const modules = defineModules()\n * .mount(HelloModule())\n * .mount(AdminModule())\n *\n * // Or seeded inline + chained\n * const modules2 = defineModules(HelloModule()).mount(AdminModule())\n *\n * await bootstrap({ modules })\n * ```\n *\n * The returned value is an `AppModuleEntry[]` subclass — `bootstrap`\n * accepts it directly without any special-casing. For conditional /\n * dynamic registration at bootstrap time (env flags, runtime config,\n * tenant lists), use the `setup(registry)` callback on `bootstrap`\n * instead — both surfaces compose.\n */\nexport function defineModules(...initial: AppModuleEntry[]): ModuleList {\n const list = new ModuleList()\n for (const entry of initial) list.push(entry)\n return list\n}\n","/**\n * Circuit Breaker pattern for external service calls.\n *\n * Protects your application from cascading failures when downstream\n * services are unhealthy by short-circuiting requests after a\n * configurable failure threshold.\n *\n * @example\n * ```ts\n * const breaker = new CircuitBreaker('payment-api', {\n * failureThreshold: 5,\n * resetTimeout: 30_000,\n * })\n *\n * const result = await breaker.execute(() => fetch('https://payment.example.com/charge'))\n * ```\n */\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half_open'\n\nexport interface CircuitBreakerOptions {\n /** Number of consecutive failures before the circuit opens. */\n failureThreshold: number\n /** Milliseconds to wait before transitioning from OPEN to HALF_OPEN. */\n resetTimeout: number\n /** Max requests allowed in HALF_OPEN state before deciding (default 1). */\n halfOpenMax?: number\n}\n\nexport interface CircuitBreakerStats {\n failures: number\n successes: number\n state: CircuitBreakerState\n lastFailure?: Date\n}\n\n/**\n * Error thrown when the circuit is open and calls are being rejected.\n */\nexport class CircuitOpenError extends Error {\n constructor(public readonly breakerName: string) {\n super(`Circuit breaker \"${breakerName}\" is open — request rejected`)\n this.name = 'CircuitOpenError'\n }\n}\n\nexport class CircuitBreaker {\n private state: CircuitBreakerState = 'closed'\n private failures = 0\n private successes = 0\n private halfOpenAttempts = 0\n private lastFailure?: Date\n private openedAt?: number\n\n private readonly failureThreshold: number\n private readonly resetTimeout: number\n private readonly halfOpenMax: number\n\n constructor(\n public readonly name: string,\n options: CircuitBreakerOptions,\n ) {\n this.failureThreshold = options.failureThreshold\n this.resetTimeout = options.resetTimeout\n this.halfOpenMax = options.halfOpenMax ?? 1\n }\n\n /**\n * Execute an async function through the circuit breaker.\n * Throws `CircuitOpenError` if the circuit is open.\n */\n async execute<T>(fn: () => Promise<T>): Promise<T> {\n this.maybeTransitionToHalfOpen()\n\n if (this.state === 'open') {\n throw new CircuitOpenError(this.name)\n }\n\n if (this.state === 'half_open' && this.halfOpenAttempts >= this.halfOpenMax) {\n throw new CircuitOpenError(this.name)\n }\n\n if (this.state === 'half_open') {\n this.halfOpenAttempts++\n }\n\n try {\n const result = await fn()\n this.onSuccess()\n return result\n } catch (error) {\n this.onFailure()\n throw error\n }\n }\n\n /** Returns the current circuit state. */\n getState(): CircuitBreakerState {\n this.maybeTransitionToHalfOpen()\n return this.state\n }\n\n /** Returns current statistics. */\n getStats(): CircuitBreakerStats {\n this.maybeTransitionToHalfOpen()\n return {\n failures: this.failures,\n successes: this.successes,\n state: this.state,\n ...(this.lastFailure ? { lastFailure: this.lastFailure } : {}),\n }\n }\n\n /** Manually reset the circuit breaker to CLOSED state. */\n reset(): void {\n this.state = 'closed'\n this.failures = 0\n this.successes = 0\n this.halfOpenAttempts = 0\n this.lastFailure = undefined\n this.openedAt = undefined\n }\n\n private onSuccess(): void {\n if (this.state === 'half_open') {\n // Recovery confirmed — close the circuit\n this.state = 'closed'\n this.failures = 0\n this.halfOpenAttempts = 0\n this.openedAt = undefined\n }\n this.successes++\n }\n\n private onFailure(): void {\n this.failures++\n this.lastFailure = new Date()\n\n if (this.state === 'half_open') {\n // Recovery failed — re-open\n this.state = 'open'\n this.openedAt = Date.now()\n this.halfOpenAttempts = 0\n } else if (this.state === 'closed' && this.failures >= this.failureThreshold) {\n this.state = 'open'\n this.openedAt = Date.now()\n }\n }\n\n private maybeTransitionToHalfOpen(): void {\n if (this.state === 'open' && this.openedAt != null) {\n if (Date.now() - this.openedAt >= this.resetTimeout) {\n this.state = 'half_open'\n this.halfOpenAttempts = 0\n }\n }\n }\n}\n","import type { Container } from './container'\nimport type { KickPlugin } from './plugin'\n\n/**\n * Options passed to {@link definePlugin}. Mirrors the spec in\n * `architecture.md` §21.3.1 + §21.2.2 (Phase A \"lite\").\n */\nexport interface DefinePluginOptions<TConfig> {\n /** Stable identity used for logging, `dependsOn` lookups, and `.scoped()` namespacing. */\n name: string\n\n /** Optional plugin version — surfaced to DevTools and `kick add` compatibility checks (Phase B). */\n version?: string\n\n /**\n * Peer-version ranges this plugin needs from the framework or other\n * plugins. Recorded as metadata; runtime enforcement lands in §21.4.4.\n */\n requires?: { kickjs?: string }\n\n /** Default config merged under any caller overrides. */\n defaults?: Partial<TConfig>\n\n /** Builds the underlying {@link KickPlugin} from the resolved config. */\n build(config: TConfig, ctx: BuildContext): Omit<KickPlugin, 'name'>\n}\n\n/**\n * Hook context handed to a plugin/adapter `build` function. `name` is the\n * resolved instance name (the bare definition name for the bare call,\n * or `${defName}:${scope}` for `.scoped()`). `scoped` is the discriminator\n * authors use to namespace DI tokens or resource keys.\n */\nexport interface BuildContext {\n name: string\n scoped: boolean\n}\n\n/**\n * Async-config form of a plugin or adapter — `inject` lists DI tokens to\n * resolve from the container, then `useFactory` produces the config.\n *\n * Plugins resolve this lazily inside `onReady`, so any module/adapter/\n * middleware/contributor a plugin contributes via `build` is **not\n * available** when `.async()` is used. Use the bare/`.scoped()` form for\n * plugins that need to register modules or middleware.\n */\nexport interface PluginAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link definePlugin}. Callable form is the singleton\n * (`AuthPlugin(config)`); `.scoped()` and `.async()` are the multi-instance\n * and deferred-config forms.\n */\nexport interface PluginFactory<TConfig> {\n (config?: Partial<TConfig>): KickPlugin\n scoped(scopeName: string, config?: Partial<TConfig>): KickPlugin\n async(opts: PluginAsyncOptions<TConfig>): KickPlugin\n /** Read-only access to the original definition — useful for DevTools introspection. */\n readonly definition: Readonly<DefinePluginOptions<TConfig>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build a {@link KickPlugin} factory from a typed definition. See\n * `architecture.md` §21.2.2 for the design rationale.\n *\n * @example\n * ```ts\n * const FlagsPlugin = definePlugin<FlagsConfig>({\n * name: 'FlagsPlugin',\n * defaults: { defaultTtl: 60_000 },\n * build(config) {\n * return {\n * register(container) {\n * container.registerInstance(FLAGS, makeProvider(config))\n * },\n * }\n * },\n * })\n *\n * bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })\n * ```\n */\nexport function definePlugin<TConfig = Record<string, unknown>>(\n options: DefinePluginOptions<TConfig>,\n): PluginFactory<TConfig> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): KickPlugin => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n const built = options.build(config, { name: instanceName, scoped }) as KickPlugin\n built.name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: PluginAsyncOptions<TConfig>): KickPlugin => {\n let inner: KickPlugin | undefined\n\n const ensureInner = async (container: Container): Promise<KickPlugin> => {\n if (inner) return inner\n const deps = (opts.inject ?? []).map((tok) => container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n return inner\n }\n\n return {\n name: instanceName,\n async onReady(container: Container) {\n const built = await ensureInner(container)\n // Run the inner plugin's register() now that we have the config —\n // late but better than never; `.async()` plugins skip the early\n // module/middleware contribution surface by design.\n built.register?.(container)\n await built.onReady?.(container)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as PluginFactory<TConfig>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: PluginAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n","/**\n * `@CacheResponse` — cache a route's whole response on the server, answer\n * `304` on a matching ETag, and serve a stale copy while a fresh one is built\n * in the background (stale-while-revalidate).\n *\n * The handler runs against a recording of the response: whatever it sends —\n * `ctx.json`, `ctx.send`, `ctx.html`, or a returned value — is captured,\n * replayed onto the real response, and stored when the status is 200. Entries\n * live in the {@link CacheProvider} (`setCacheProvider`), so a shared store\n * such as Redis serves every instance.\n *\n * Edge-safe: no node imports — shared by every runtime and the web entry.\n *\n * @module @forinda/kickjs/http/cache-response\n */\nimport { getCacheProvider } from '../core/cache'\nimport { waitUntil } from './background'\nimport type { RequestContext } from './context'\nimport { applyHandlerResult } from './reply'\nimport { stringifyJson, type RuntimeResponse } from './runtime'\n\nexport interface CacheResponseOptions {\n /** Seconds a stored response is served as fresh. */\n maxAge: number\n /**\n * Seconds past `maxAge` a stale response is still served, while one request\n * rebuilds it in the background. Default 0: past `maxAge` the next request waits.\n */\n swr?: number\n /**\n * Request headers that select a different response — `accept-language`, or\n * `authorization` for per-user responses. Their values are part of the key.\n * Every header the handler reads belongs here.\n *\n * A request that identifies its caller — `authorization`, `proxy-authorization`,\n * `x-api-key`, a `cookie`, or a signed-in `ctx.user` — skips the cache unless\n * that header is listed here: under a shared key, one user's response would\n * reach another.\n */\n varies?: string[]\n /**\n * A string is the key prefix — `@CacheEvict(prefix)` clears the route's\n * entries. Default: `kick:response:Controller.method`.\n *\n * A function decides the key per request, from the whole context — params,\n * `ctx.get('tenant')`, `ctx.user`. It owns the decision: the caller check\n * above doesn't apply, so include the user or tenant when the response\n * depends on them. Return `null` to skip the cache for that request.\n */\n key?: string | ((ctx: RequestContext) => string | null)\n}\n\n/** What a handler sent, enough to send it again. */\ninterface Recorded {\n status: number\n type?: string\n headers: Record<string, string | string[]>\n body: string\n /** `body` is base64 of bytes the handler sent. */\n binary?: boolean\n /** The handler used `ctx.res` directly: what it did there isn't recorded, so this is never stored. */\n native?: boolean\n}\n\ninterface Entry {\n recorded: Recorded\n storedAt: number\n}\n\n/** Requests that would otherwise each build the same response, by key. */\nconst inFlight = new Map<string, Promise<Recorded | null>>()\n\n/** Headers that identify the caller: a request carrying one is never cached under a shared key. */\nconst PERSONAL = ['authorization', 'proxy-authorization', 'x-api-key', 'cookie']\n\nexport function CacheResponse(options: CacheResponseOptions): MethodDecorator {\n const maxAgeMs = options.maxAge * 1000\n const swrMs = (options.swr ?? 0) * 1000\n const varies = (options.varies ?? []).map((h) => h.toLowerCase())\n\n return (target, propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value as (ctx: RequestContext, ...rest: unknown[]) => unknown\n const owner = typeof target === 'function' ? target.name : target.constructor?.name\n const prefix =\n typeof options.key === 'string'\n ? options.key\n : `kick:response:${owner ?? 'anonymous'}.${String(propertyKey)}`\n const keyOf = typeof options.key === 'function' ? options.key : undefined\n\n descriptor.value = async function (this: unknown, ctx: RequestContext, ...rest: unknown[]) {\n const req = ctx.req as { method?: string; url?: string; originalUrl?: string }\n const method = String(req.method ?? 'GET').toUpperCase()\n const headers = ctx.headers as Record<string, string | string[] | undefined>\n if ((method !== 'GET' && method !== 'HEAD') || maxAgeMs + swrMs <= 0) {\n return original.call(this, ctx, ...rest)\n }\n let identity: string\n if (keyOf) {\n const chosen = keyOf(ctx)\n if (chosen === null) return original.call(this, ctx, ...rest)\n identity = chosen\n } else {\n const personal =\n PERSONAL.some((h) => headers[h] !== undefined && !varies.includes(h)) ||\n (ctx.user !== undefined && !varies.some((h) => PERSONAL.includes(h)))\n if (personal) return original.call(this, ctx, ...rest)\n // The exact host the handler sees: one app serving several hosts answers\n // each differently, and a handler may put the host in the body. A host\n // that isn't `name[:port]` is never cached — nothing ambiguous in the key.\n const host = String(headers.host ?? '')\n if (!VALID_HOST.test(host)) return original.call(this, ctx, ...rest)\n identity = JSON.stringify([host.toLowerCase(), req.originalUrl ?? req.url ?? ''])\n }\n const varied = varies.map((h) => `${h}=${String(headers[h] ?? '')}`).join('&')\n const key = `${prefix}:${identity}|${varied}`\n const provider = getCacheProvider()\n const run = () => record(original, this, ctx, rest)\n const build = () => buildOnce(key, run)\n const store = async ({ recorded, shared }: Built) => {\n // The request that ran the handler stores it; the ones that waited don't again.\n if (!shared && recorded && cacheable(recorded)) {\n const entry: Entry = { recorded, storedAt: Date.now() }\n await provider.set(key, entry, maxAgeMs + swrMs)\n }\n }\n\n const entry = (await provider.get(key)) as Entry | null\n if (entry) {\n const age = Date.now() - entry.storedAt\n if (age < maxAgeMs + swrMs) {\n // Stale: answer now, rebuild for the next request.\n if (age >= maxAgeMs) waitUntil(build().then(store))\n replay(ctx, entry.recorded)\n return undefined\n }\n }\n\n const built = await build()\n await store(built)\n let recorded = built.recorded\n // A response that isn't shared — a cookie, a 404, ctx.res — belongs to the\n // request that produced it: one that only waited for it runs the handler itself.\n if (built.shared && !(recorded && cacheable(recorded))) recorded = await run()\n if (recorded) replay(ctx, recorded)\n return undefined\n }\n return descriptor\n }\n}\n\n/** `name[:port]` or `[ipv6][:port]` — no path, userinfo or whitespace. */\nconst VALID_HOST = /^(?:\\[[0-9a-f:.]+\\]|[a-z0-9-]+(?:\\.[a-z0-9-]+)*)(?::\\d{1,5})?$/i\n\n/** A build's result, and whether this request only waited for another one's. */\ninterface Built {\n recorded: Recorded | null\n shared: boolean\n}\n\n/** Concurrent misses on one key share a single build. */\nasync function buildOnce(key: string, run: () => Promise<Recorded | null>): Promise<Built> {\n const pending = inFlight.get(key)\n if (pending) return { recorded: await pending, shared: true }\n const load = run().finally(() => inFlight.delete(key))\n inFlight.set(key, load)\n return { recorded: await load, shared: false }\n}\n\n/** Only a 200 that sets no cookie, written through ctx alone, is shared. */\nfunction cacheable(recorded: Recorded): boolean {\n return recorded.status === 200 && !('set-cookie' in recorded.headers) && !recorded.native\n}\n\n/**\n * Run the handler against a context whose response is a recording. Null when\n * it sent nothing — the request then falls through as it would uncached.\n */\nasync function record(\n handler: (ctx: RequestContext, ...rest: unknown[]) => unknown,\n self: unknown,\n ctx: RequestContext,\n rest: unknown[],\n): Promise<Recorded | null> {\n const recorded: Recorded = { status: 200, headers: {}, body: '' }\n let sent = false\n const finish = (body: unknown) => {\n if (body instanceof Uint8Array) {\n recorded.body = toBase64(body)\n recorded.binary = true\n } else if (typeof body === 'string') {\n recorded.body = body\n } else if (body !== undefined && body !== null) {\n recorded.type ??= 'application/json; charset=utf-8'\n recorded.body = stringifyJson(body)\n }\n sent = true\n }\n const unsupported = (what: string) => () => {\n throw new Error(\n `@CacheResponse: the handler called ${what}. A cached route answers with ` +\n 'ctx.json / ctx.send / ctx.html or a returned value, not a stream or a template.',\n )\n }\n const response = {\n status(code: number) {\n recorded.status = code\n return response\n },\n type(contentType: string) {\n recorded.type = contentType\n return response\n },\n json(data: unknown) {\n recorded.type ??= 'application/json; charset=utf-8'\n recorded.body = stringifyJson(data)\n sent = true\n return response\n },\n send(data: unknown) {\n finish(data)\n return response\n },\n end(data?: unknown) {\n finish(data)\n return response\n },\n setHeader(name: string, value: string | number | readonly string[]) {\n recorded.headers[name.toLowerCase()] = Array.isArray(value)\n ? [...(value as readonly string[])]\n : String(value)\n },\n get headersSent() {\n return sent\n },\n once() {},\n render: unsupported('render()'),\n writeHead: unsupported('writeHead()'),\n flushHeaders: unsupported('flushHeaders()'),\n write: unsupported('write()'),\n }\n // `ctx.res` is the engine's own response: what a handler does to it directly\n // (a header, a cookie) isn't recorded, so any use of it marks the response unshareable.\n const native = new Proxy(ctx.res as object, {\n get(target, prop) {\n const value = Reflect.get(target, prop, target)\n if (typeof value !== 'function') return value\n return (...args: unknown[]) => {\n recorded.native = true\n return value.apply(target, args)\n }\n },\n set(target, prop, value) {\n recorded.native = true\n return Reflect.set(target, prop, value, target)\n },\n })\n // Everything else is the real request's: params, query, headers, metadata.\n const recordingCtx = Object.create(ctx, {\n _response: { value: response as unknown as RuntimeResponse },\n res: { value: native },\n }) as RequestContext\n const result = await handler.call(self, recordingCtx, ...rest)\n if (!sent) await applyHandlerResult(recordingCtx, result)\n return sent ? recorded : null\n}\n\n/** Send a recorded response — `304` when the client's copy is current. */\nfunction replay(ctx: RequestContext, recorded: Recorded): void {\n // The handler already answered through ctx.res itself.\n if (ctx['_response'].headersSent) return\n for (const [name, value] of Object.entries(recorded.headers)) {\n if (name !== 'etag' && name !== 'content-type') ctx.setHeader(name, value)\n }\n if (recorded.status === 200) {\n const etag = (recorded.headers.etag as string | undefined) ?? weakEtag(recorded.body)\n if (ctx.conditional({ etag })) return\n }\n const options = { status: recorded.status, type: recorded.type ?? 'text/plain; charset=utf-8' }\n ctx.send(recorded.binary ? fromBase64(recorded.body) : recorded.body, options)\n}\n\n/** A weak ETag from the body — FNV-1a, enough to tell versions apart. */\nfunction weakEtag(body: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < body.length; i++) {\n hash ^= body.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return `W/\"${body.length.toString(16)}-${(hash >>> 0).toString(16)}\"`\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(binary)\n}\n\nfunction fromBase64(text: string): Uint8Array {\n const binary = atob(text)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n","/**\n * `/metrics` in the Prometheus text format: a request-duration histogram per\n * route pattern, plus process health (memory, heap, event-loop lag).\n *\n * @module @forinda/kickjs/http/metrics\n */\nimport { monitorEventLoopDelay } from 'node:perf_hooks'\nimport type { AppAdapter, AdapterContext } from '../core/adapter'\nimport type { ResponseInfo } from '../core/observers'\nimport { matchesBearer } from '../core/web-crypto'\nimport type { RequestContext } from './context'\n\nexport interface MetricsOptions {\n /** Where to serve the metrics. Default `/metrics`. */\n path?: string\n /**\n * Require `Authorization: Bearer <token>` to read them. The endpoint is\n * mounted before the app's middleware (so a scraper doesn't need your\n * auth), which also means your auth doesn't cover it — set this unless\n * the port is only reachable by the scraper.\n */\n token?: string\n /** Histogram buckets, in seconds. Default: Prometheus' defaults, 5ms to 10s. */\n buckets?: number[]\n /**\n * Serve the metrics on the management port (`bootstrap({ management: { port } })`)\n * instead of the app's — reachable by the scraper, not the public. Without a\n * management port it stays on the app's.\n */\n management?: boolean\n}\n\nconst DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]\n\n/** Label values per the exposition format: backslash, quote and newline escaped. */\nconst label = (value: string) =>\n value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n')\n\ninterface Series {\n labels: string\n counts: number[]\n sum: number\n count: number\n}\n\n/** The request histogram, keyed by its label set. */\nexport class RequestHistogram {\n private readonly series = new Map<string, Series>()\n\n private readonly buckets: readonly number[]\n\n /**\n * Bounds in seconds — sorted and deduplicated here, since the exposition\n * format needs them strictly increasing; anything not a finite positive\n * number is rejected.\n */\n constructor(buckets: readonly number[] = DEFAULT_BUCKETS) {\n if (buckets.length === 0 || buckets.some((b) => !Number.isFinite(b) || b <= 0)) {\n throw new Error('metrics: buckets must be finite positive numbers (seconds)')\n }\n this.buckets = [...new Set(buckets)].toSorted((a, b) => a - b)\n }\n\n observe(info: Pick<ResponseInfo, 'method' | 'route' | 'status' | 'durationMs'>): void {\n // The route pattern, never the raw path: `/users/42` and `/users/43` are\n // one series, and a scan of random URLs adds one series (`unmatched`),\n // not one per URL.\n const labels =\n `method=\"${label(knownMethod(info.method))}\",route=\"${label(info.route ?? 'unmatched')}\",` +\n `status=\"${info.status}\"`\n let series = this.series.get(labels)\n if (!series) {\n series = { labels, counts: this.buckets.map(() => 0), sum: 0, count: 0 }\n this.series.set(labels, series)\n }\n const seconds = info.durationMs / 1000\n for (const [i, bound] of this.buckets.entries()) if (seconds <= bound) series.counts[i]++\n series.sum += seconds\n series.count++\n }\n\n render(): string {\n const name = 'http_request_duration_seconds'\n const lines = [\n `# HELP ${name} Time to answer an HTTP request, by route pattern.`,\n `# TYPE ${name} histogram`,\n ]\n for (const s of this.series.values()) {\n for (const [i, bound] of this.buckets.entries()) {\n lines.push(`${name}_bucket{${s.labels},le=\"${bound}\"} ${s.counts[i]}`)\n }\n lines.push(`${name}_bucket{${s.labels},le=\"+Inf\"} ${s.count}`)\n lines.push(`${name}_sum{${s.labels}} ${s.sum}`)\n lines.push(`${name}_count{${s.labels}} ${s.count}`)\n }\n return lines.join('\\n')\n }\n}\n\nconst METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'QUERY'])\n\n/**\n * The method as a label, or `OTHER`. Node only parses known methods, but a\n * fetch-based host (Bun, Deno) passes any token through, and each one would\n * start a series.\n */\nfunction knownMethod(method: string): string {\n const upper = method.toUpperCase()\n return METHODS.has(upper) ? upper : 'OTHER'\n}\n\nfunction gauge(name: string, help: string, value: number): string {\n return `# HELP ${name} ${help}\\n# TYPE ${name} gauge\\n${name} ${value}`\n}\n\n/**\n * Serve Prometheus metrics. Add it to `adapters`:\n *\n * ```ts\n * bootstrap({ modules, adapters: [metricsAdapter({ token: process.env.METRICS_TOKEN })] })\n * ```\n */\nexport function metricsAdapter(options: MetricsOptions = {}): AppAdapter {\n const path = options.path ?? '/metrics'\n const histogram = new RequestHistogram(options.buckets ?? DEFAULT_BUCKETS)\n let loop: ReturnType<typeof monitorEventLoopDelay> | undefined\n\n const render = () => {\n const memory = process.memoryUsage()\n const lag = loop && loop.count > 0 ? loop.mean / 1e9 : 0\n return [\n histogram.render(),\n gauge('process_resident_memory_bytes', 'Resident set size.', memory.rss),\n gauge('nodejs_heap_used_bytes', 'V8 heap in use.', memory.heapUsed),\n gauge('nodejs_heap_total_bytes', 'V8 heap allocated.', memory.heapTotal),\n gauge('nodejs_eventloop_lag_seconds', 'Mean event-loop delay since the last scrape.', lag),\n gauge('process_uptime_seconds', 'Seconds since the process started.', process.uptime()),\n ].join('\\n\\n')\n }\n\n return {\n name: 'MetricsAdapter',\n beforeMount({ http: appHttp, management }: AdapterContext) {\n const http = options.management && management ? management.http : appHttp\n loop = monitorEventLoopDelay({ resolution: 20 })\n loop.enable()\n http.route('GET', path, (ctx: RequestContext) => {\n const { token } = options\n if (token !== undefined && !matchesBearer(ctx.headers.authorization, token)) {\n ctx.setHeader('WWW-Authenticate', 'Bearer')\n ctx.json({ message: 'Unauthorized' }, 401)\n return\n }\n const body = render()\n // Lag is \"since the last scrape\": start the next window now.\n loop?.reset()\n ctx.setHeader('Cache-Control', 'no-store')\n ctx.send(`${body}\\n`, { type: 'text/plain; version=0.0.4; charset=utf-8' })\n })\n },\n onResponse(info: ResponseInfo) {\n // The scrape itself is not a request worth measuring.\n if (info.route === path) return\n histogram.observe(info)\n },\n shutdown() {\n loop?.disable()\n },\n }\n}\n","/**\n * HTTP-flavoured wrapper around {@link defineContextDecorator}.\n *\n * The core factory leaves `Ctx` defaulted to {@link ExecutionContext} so the\n * Context Contributor pipeline stays transport-agnostic — future WebSocket,\n * queue, and cron contexts share the same primitive. The cost is that the\n * vast majority of contributors (which are HTTP) have to spell the fourth\n * generic by hand to get `ctx.req` / `ctx.headers` typing:\n *\n * ```ts\n * // Verbose: spell every generic, including the params shape `P`.\n * defineContextDecorator<'tenant', Record<string, never>, Record<string, never>, RequestContext>({\n * key: 'tenant',\n * resolve: (ctx) => ({ id: ctx.req.headers['x-tenant-id'] as string }),\n * })\n * ```\n *\n * `defineHttpContextDecorator` removes that ceremony — the spec is typed\n * against `RequestContext` from the start, so resolvers can read `ctx.req`,\n * `ctx.headers`, `ctx.params`, etc. without a cast or generic dance:\n *\n * ```ts\n * import { defineHttpContextDecorator } from '@forinda/kickjs'\n *\n * const LoadTenant = defineHttpContextDecorator({\n * key: 'tenant',\n * resolve: (ctx) => ({ id: ctx.req.headers['x-tenant-id'] as string }),\n * })\n *\n * // Parameterised — the positional form forces you to also spell `K`\n * // and `D`, which loses automatic `deps` inference. Prefer the curried\n * // `.withParams<P>()` entry point below.\n * const LoadTenantParameterised = defineHttpContextDecorator<\n * 'tenant',\n * Record<string, never>,\n * { source: 'header' | 'subdomain' }\n * >({\n * key: 'tenant',\n * paramDefaults: { source: 'header' },\n * resolve: (ctx, _deps, params) => {\n * // params.source narrows inside `if` branches.\n * },\n * })\n *\n * // Parameterised + deps — only `P` is spelled; `K` and `D` infer from\n * // the spec, so `deps.repo` is fully typed in the resolver.\n * const LoadTenantWithRepo = defineHttpContextDecorator.withParams<{\n * source: 'header' | 'subdomain'\n * }>()({\n * key: 'tenant',\n * deps: { repo: TENANT_REPO },\n * paramDefaults: { source: 'header' },\n * resolve: (ctx, { repo }, params) =>\n * repo.findFor(ctx.req.headers['x-tenant-id'] as string, params.source),\n * })\n * ```\n *\n * Use {@link defineContextDecorator} directly when authoring contributors\n * for non-HTTP transports or when you want to share one contributor across\n * HTTP + WS + queue (the resolver then has to stick to the\n * `ExecutionContext` surface — `ctx.get` / `ctx.set` / `ctx.requestId`).\n */\n\nimport {\n defineContextDecorator,\n type ContextDecorator,\n type ContextDecoratorSpec,\n type ContextMetaKey,\n type DepValue,\n} from '../core/context-decorator'\nimport type { RequestContext } from './context'\n\n/**\n * Curried form returned by {@link DefineHttpContextDecoratorFn.withParams}.\n * Spell only the per-call params shape `P`; `K` and `D` are inferred\n * from the spec, and `Ctx` is locked to `RequestContext`.\n */\nexport interface DefineHttpContextDecoratorWithParams<P extends Record<string, unknown>> {\n <K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>>(\n spec: ContextDecoratorSpec<K, D, P, RequestContext>,\n ): ContextDecorator<K, D, P, RequestContext>\n}\n\n/**\n * Public shape of {@link defineHttpContextDecorator} — the positional\n * call signature plus the curried `.withParams<P>()` helper that fixes\n * partial-inference for the parameterised case.\n */\nexport interface DefineHttpContextDecoratorFn {\n <\n K extends ContextMetaKey,\n D extends Record<string, DepValue> = Record<string, never>,\n P extends Record<string, unknown> = Record<string, never>,\n >(\n spec: ContextDecoratorSpec<K, D, P, RequestContext>,\n ): ContextDecorator<K, D, P, RequestContext>\n\n /**\n * Curried entry point. Spell only `P`; `K` and `D` infer from the\n * spec. `Ctx` is locked to `RequestContext`.\n *\n * ```ts\n * const LoadTenant = defineHttpContextDecorator.withParams<{\n * source: 'header' | 'subdomain'\n * }>()({\n * key: 'tenant',\n * deps: { repo: TENANT_REPO }, // D inferred\n * paramDefaults: { source: 'header' },\n * resolve: (ctx, { repo }, params) => repo.findFor(ctx, params),\n * })\n * ```\n */\n withParams<P extends Record<string, unknown>>(): DefineHttpContextDecoratorWithParams<P>\n}\n\nfunction defineHttpContextDecoratorImpl<\n K extends ContextMetaKey,\n D extends Record<string, DepValue> = Record<string, never>,\n P extends Record<string, unknown> = Record<string, never>,\n>(spec: ContextDecoratorSpec<K, D, P, RequestContext>): ContextDecorator<K, D, P, RequestContext> {\n return defineContextDecorator<K, D, P, RequestContext>(spec)\n}\n\nexport const defineHttpContextDecorator: DefineHttpContextDecoratorFn = Object.freeze(\n Object.assign(defineHttpContextDecoratorImpl, {\n withParams: <P extends Record<string, unknown>>(): DefineHttpContextDecoratorWithParams<P> => {\n return <K extends ContextMetaKey, D extends Record<string, DepValue> = Record<string, never>>(\n spec: ContextDecoratorSpec<K, D, P, RequestContext>,\n ): ContextDecorator<K, D, P, RequestContext> => defineHttpContextDecoratorImpl<K, D, P>(spec)\n },\n }),\n) as DefineHttpContextDecoratorFn\n","/**\n * Password hashing with scrypt — salted, memory-hard, and self-describing,\n * so the cost can be raised later and old hashes upgrade on the next login:\n *\n * ```ts\n * const stored = await hashPassword(input) // at sign-up\n *\n * const { ok, needsRehash } = await verifyPassword(input, user?.passwordHash)\n * if (!ok) throw HttpException.unauthorized()\n * if (needsRehash) await users.update(user.id, { passwordHash: await hashPassword(input) })\n * ```\n *\n * Node only (`node:crypto` scrypt); not part of the web entry.\n *\n * @module @forinda/kickjs/core/password\n */\nimport { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from 'node:crypto'\n\n/** scrypt cost. Memory per hash is `128 * N * r` bytes. */\nexport interface PasswordHashOptions {\n /** CPU/memory cost, a power of two. Default `2 ** 14`. */\n N?: number\n /** Block size. Default `8`. */\n r?: number\n /** Parallelism. Default `5`. */\n p?: number\n}\n\n// OWASP's scrypt option with 16 MiB per hash (N=2^14, r=8, p=5); Django's\n// defaults too. Raising N later marks existing hashes `needsRehash`.\nconst DEFAULTS = { N: 2 ** 14, r: 8, p: 5 }\nconst SALT_BYTES = 16\nconst KEY_BYTES = 64\n\nfunction derive(password: string, salt: Buffer, cost: Required<PasswordHashOptions>) {\n // What OpenSSL allocates (128 * r * (N + p + 2)), plus slack; `256 * N * r`\n // alone is too little when p is large next to N.\n const options: ScryptOptions = {\n ...cost,\n maxmem: 128 * cost.r * (cost.N + cost.p + 2) + 1024 * 1024,\n }\n return new Promise<Buffer>((resolve, reject) =>\n // NFKC, as NIST 800-63B suggests: the same password typed on another\n // keyboard or OS (composed vs decomposed accents) still matches.\n scrypt(password.normalize('NFKC'), salt, KEY_BYTES, options, (err, key) =>\n err ? reject(err) : resolve(key),\n ),\n )\n}\n\nfunction costOf(options: PasswordHashOptions): Required<PasswordHashOptions> {\n const cost = { ...DEFAULTS, ...options }\n if (!Number.isInteger(Math.log2(cost.N)) || cost.N < 2) {\n throw new Error('hashPassword: N must be a power of two')\n }\n return cost\n}\n\n/**\n * Hash a password for storage: `scrypt$N$r$p$salt$hash`, salt and hash in\n * base64. The same password hashes differently every time.\n */\nexport async function hashPassword(\n password: string,\n options: PasswordHashOptions = {},\n): Promise<string> {\n const cost = costOf(options)\n const salt = randomBytes(SALT_BYTES)\n const key = await derive(password, salt, cost)\n const encoded = [salt, key].map((bytes) => bytes.toString('base64'))\n return ['scrypt', cost.N, cost.r, cost.p, ...encoded].join('$')\n}\n\n/** What {@link verifyPassword} returns. */\nexport interface PasswordCheck {\n /** The password matches. */\n ok: boolean\n /**\n * The hash was made with a different cost than `options` (the defaults):\n * hash the password again and store it. Only ever true when `ok` is.\n */\n needsRehash: boolean\n}\n\n/**\n * A hash format from before scrypt — bcrypt or argon2 rows imported from\n * another system. It still verifies; on success `needsRehash` is true, so the\n * account moves to scrypt at its next login.\n *\n * ```ts\n * import bcrypt from 'bcrypt'\n * const bcryptHashes: LegacyHasher = {\n * matches: (stored) => /^\\$2[aby]\\$/.test(stored),\n * verify: (password, stored) => bcrypt.compare(password, stored),\n * dummy: await bcrypt.hash('dummy', 12), // the cost your rows use\n * }\n * await verifyPassword(input, user?.passwordHash, { legacy: [bcryptHashes] })\n * ```\n */\nexport interface LegacyHasher {\n /** Whether `stored` is in this format — by prefix (`$2b$` for bcrypt, `$argon2id$`). */\n matches(stored: string): boolean\n /** Whether `password` matches `stored`: the library's own check. */\n verify(password: string, stored: string): boolean | Promise<boolean>\n /**\n * A hash in this format, of any password, at the cost the rows it\n * `matches` use. Every check runs scrypt once and each legacy hasher once —\n * against this when the account isn't in its format — so a login takes as\n * long for a scrypt account, an imported one or a missing one, and timing\n * can't tell them apart. Rows at several costs: one hasher per cost, each\n * matching its own (bcrypt's `$2b$10$` vs `$2b$12$`) with a dummy at that\n * cost; every login then runs all of them and takes the slowest's time.\n */\n dummy: string\n}\n\n/** {@link verifyPassword}'s options: the scrypt cost, and older formats that still verify. */\nexport interface VerifyPasswordOptions extends PasswordHashOptions {\n /** Formats besides scrypt, tried in order on a hash scrypt can't read. */\n legacy?: readonly LegacyHasher[]\n}\n\n// What a missing user is checked against: the same work as a real check.\nconst DUMMY_SALT = randomBytes(SALT_BYTES)\n\n/**\n * Check a password against a stored hash. Constant-time, and pass\n * `undefined` for a user that doesn't exist: the password is still hashed,\n * so a missing account takes as long to reject as a wrong password and the\n * timing doesn't reveal which accounts exist. A hash not in this format\n * (another algorithm, or corrupt) fails rather than throws, unless one of\n * `options.legacy` reads it.\n */\nexport async function verifyPassword(\n password: string,\n stored: string | null | undefined,\n options: VerifyPasswordOptions = {},\n): Promise<PasswordCheck> {\n const { legacy = [], ...scryptCost } = options\n const parsed = stored ? parse(stored) : undefined\n const older = !parsed && stored ? legacy.find((hasher) => matches(hasher, stored)) : undefined\n // The same work on every path: scrypt once, and each legacy hasher once —\n // on its dummy unless the account is in its format.\n const [scrypt, checks] = await Promise.all([\n // Costs OpenSSL still refuses (N >= 2^(16r) with a small r) fail, not throw.\n parsed\n ? derive(password, parsed.salt, parsed.cost).catch(() => undefined)\n : derive(password, DUMMY_SALT, costOf(scryptCost)),\n Promise.all(\n legacy.map((hasher) => check(hasher, password, hasher === older ? stored! : hasher.dummy)),\n ),\n ])\n if (older) {\n const ok = checks[legacy.indexOf(older)]!\n return { ok, needsRehash: ok }\n }\n // No such user, or a hash nobody here reads: the work is done, and it fails.\n if (!parsed || !scrypt) return { ok: false, needsRehash: false }\n const ok = scrypt.length === parsed.key.length && timingSafeEqual(scrypt, parsed.key)\n const wanted = costOf(scryptCost)\n const needsRehash =\n ok && (parsed.cost.N !== wanted.N || parsed.cost.r !== wanted.r || parsed.cost.p !== wanted.p)\n return { ok, needsRehash }\n}\n\n/** Whether `hasher` reads `stored`; a matcher that throws on a malformed row doesn't. */\nfunction matches(hasher: LegacyHasher, stored: string): boolean {\n try {\n return hasher.matches(stored) === true\n } catch {\n return false\n }\n}\n\n/** A legacy hasher's verdict: only `true` is a match; a throw (a malformed row) is not. */\nfunction check(hasher: LegacyHasher, password: string, hash: string): Promise<boolean> {\n return Promise.resolve()\n .then(() => hasher.verify(password, hash))\n .then(\n (result) => result === true,\n () => false,\n )\n}\n\nfunction parse(stored: string) {\n const [algorithm, N, r, pp, salt, key] = stored.split('$')\n if (algorithm !== 'scrypt' || key === undefined) return undefined\n const cost = { N: Number(N), r: Number(r), p: Number(pp) }\n // A hash from elsewhere can't make verification allocate gigabytes: at most\n // 256 MiB (128 * N * r), sixteen times the default.\n if (\n !Number.isInteger(Math.log2(cost.N)) ||\n cost.N < 2 ||\n !Number.isInteger(cost.r) ||\n cost.r < 1 ||\n cost.r > 32 ||\n !Number.isInteger(cost.p) ||\n cost.p < 1 ||\n cost.p > 16 ||\n 128 * cost.N * cost.r > 2 ** 28\n ) {\n return undefined\n }\n return { cost, salt: Buffer.from(salt, 'base64'), key: Buffer.from(key, 'base64') }\n}\n","/**\n * Signed, timestamped tokens — a password-reset link, an unsubscribe link,\n * an email-confirmation code — that the server can verify later without\n * storing them:\n *\n * ```ts\n * const resets = createSigner({ secret: process.env.SIGNING_SECRET!, salt: 'password-reset' })\n *\n * const token = resets.sign({ userId: user.id }) // put it in the link\n * const check = resets.verify<{ userId: string }>(token, { maxAge: 60 * 60_000 })\n * if (!check.ok) throw HttpException.badRequest(check.reason) // 'invalid' | 'expired'\n * ```\n *\n * The value is signed, not encrypted: anyone holding the token can read it.\n * Node only (`node:crypto` HMAC); not part of the web entry.\n *\n * @module @forinda/kickjs/core/signing\n */\nimport { createHmac, timingSafeEqual } from 'node:crypto'\n\nexport interface SignerOptions {\n /**\n * The signing secret. Pass a list to rotate: the first signs, every one\n * verifies. Drop the old one once its tokens have expired.\n */\n secret: string | string[]\n /**\n * What the tokens are for — `'password-reset'`, `'unsubscribe'`. Signers\n * with different salts reject each other's tokens even with the same\n * secret, so a token issued for one purpose can't be used for another.\n */\n salt: string\n}\n\nexport interface VerifyOptions {\n /** Reject tokens older than this, in milliseconds. */\n maxAge?: number\n}\n\n/** What {@link Signer.verify} returns. */\nexport type SignedCheck<T> =\n | { ok: true; value: T; issuedAt: Date }\n | { ok: false; reason: 'invalid' | 'expired' }\n\nexport interface Signer {\n /** Sign a JSON-serialisable value: `payload.timestamp.signature`, URL-safe. */\n sign(value: unknown): string\n /** Check a token's signature and, with `maxAge`, its age. Never throws. */\n verify<T = unknown>(token: string, options?: VerifyOptions): SignedCheck<T>\n}\n\n/** Create a signer for one purpose. */\nexport function createSigner(options: SignerOptions): Signer {\n const secrets = Array.isArray(options.secret) ? options.secret : [options.secret]\n if (secrets.length === 0 || secrets.some((s) => typeof s !== 'string' || s.length === 0)) {\n throw new Error('createSigner: `secret` must be a non-empty string or list of strings')\n }\n if (!options.salt) throw new Error('createSigner: `salt` names what the tokens are for')\n // One key per secret and purpose, so the raw secret never signs directly.\n const keys = secrets.map((secret) =>\n createHmac('sha256', secret).update(`kickjs.signing:${options.salt}`).digest(),\n )\n const mac = (key: Buffer, data: string) =>\n createHmac('sha256', key).update(data).digest('base64url')\n\n return {\n sign(value) {\n const json = JSON.stringify(value)\n if (json === undefined) throw new Error('signer.sign: the value must be JSON-serialisable')\n const payload = Buffer.from(json).toString('base64url')\n const signed = `${payload}.${Date.now().toString(36)}`\n return `${signed}.${mac(keys[0], signed)}`\n },\n verify<T>(token: string, verifyOptions: VerifyOptions = {}): SignedCheck<T> {\n const invalid = { ok: false, reason: 'invalid' } as const\n if (typeof token !== 'string') return invalid\n const cut = token.lastIndexOf('.')\n const signed = token.slice(0, cut)\n const signature = Buffer.from(token.slice(cut + 1))\n const [payload, stamp, extra] = signed.split('.')\n if (cut < 0 || stamp === undefined || extra !== undefined) return invalid\n const matches = keys.some((key) => {\n const expected = Buffer.from(mac(key, signed))\n return expected.length === signature.length && timingSafeEqual(expected, signature)\n })\n if (!matches) return invalid\n const issued = parseInt(stamp, 36)\n if (!Number.isFinite(issued)) return invalid\n if (verifyOptions.maxAge !== undefined && Date.now() - issued > verifyOptions.maxAge) {\n return { ok: false, reason: 'expired' }\n }\n try {\n const value = JSON.parse(Buffer.from(payload, 'base64url').toString()) as T\n return { ok: true, value, issuedAt: new Date(issued) }\n } catch {\n return invalid\n }\n },\n }\n}\n","import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\nimport { requestStore } from '../request-store'\n\nimport { randomHex } from '../../core/web-crypto'\n\n/**\n * W3C Trace Context header name.\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n */\nexport const TRACEPARENT_HEADER = 'traceparent'\n\n/** Regex for a valid W3C traceparent: {version}-{trace-id}-{parent-id}-{flags} */\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/\n\nexport interface TraceContextOptions {\n /**\n * When true, respond with a `traceresponse` header containing the trace ID.\n * Useful for debugging. Default: false.\n */\n propagateResponse?: boolean\n}\n\n/**\n * Parsed W3C trace context fields.\n */\nexport interface TraceContext {\n /** W3C traceparent version (usually '00') */\n version: string\n /** 32-hex-char distributed trace ID */\n traceId: string\n /** 16-hex-char parent span ID */\n parentSpanId: string\n /** 2-hex-char trace flags */\n flags: string\n}\n\n/**\n * Generate a random 32-hex-character trace ID.\n */\nfunction generateTraceId(): string {\n return randomHex(16)\n}\n\n/**\n * Generate a random 16-hex-character span ID.\n */\nfunction generateSpanId(): string {\n return randomHex(8)\n}\n\n/**\n * Parse a W3C traceparent header value.\n * Returns null if the format is invalid.\n */\nexport function parseTraceparent(header: string): TraceContext | null {\n const match = TRACEPARENT_RE.exec(header.trim().toLowerCase())\n if (!match) return null\n\n const version = match[1]\n const traceId = match[2]\n const parentSpanId = match[3]\n const flags = match[4]\n\n // W3C spec: version ff is invalid, all-zero trace-id and parent-id are invalid\n if (\n version === 'ff' ||\n traceId === '00000000000000000000000000000000' ||\n parentSpanId === '0000000000000000'\n ) {\n return null\n }\n\n return { version, traceId, parentSpanId, flags }\n}\n\n/**\n * Middleware that extracts W3C `traceparent` header and stores trace context\n * in the request's AsyncLocalStorage store.\n *\n * If no valid `traceparent` header is present, a new traceId is generated\n * so that every request always has a trace ID available for correlation.\n *\n * Must be mounted **after** `requestScopeMiddleware()` (which creates the store).\n *\n * @example\n * ```ts\n * bootstrap({\n * middlewares: [\n * requestScopeMiddleware(),\n * traceContext(), // extracts or generates traceId\n * requestLogger(),\n * express.json(),\n * ],\n * })\n * ```\n */\nexport function traceContext(options: TraceContextOptions = {}) {\n return (req: Request, res: Response, next: NextFunction) => {\n const store = requestStore.getStore()\n\n const traceparentHeader = req.headers[TRACEPARENT_HEADER]\n const raw = Array.isArray(traceparentHeader) ? traceparentHeader[0] : traceparentHeader\n const parsed = raw ? parseTraceparent(raw) : null\n\n const traceId = parsed?.traceId ?? generateTraceId()\n const spanId = generateSpanId()\n\n // Attach to the request store so logger + downstream code can access it\n if (store) {\n store.values.set('traceId', traceId)\n store.values.set('spanId', spanId)\n if (parsed) {\n store.values.set('parentSpanId', parsed.parentSpanId)\n store.values.set('traceFlags', parsed.flags)\n store.values.set('traceVersion', parsed.version)\n }\n }\n\n // Also expose on req for convenience\n ;(req as any).traceId = traceId\n ;(req as any).spanId = spanId\n\n if (options.propagateResponse) {\n res.setHeader('traceresponse', traceId)\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;ulLA2BA,IAAa,WAAb,cAAgC,KAAsB,CASpD,MAAM,OAA8B,CAElC,OADA,KAAK,KAAK,MAAM,EACT,IACT,CACF,EA8BA,SAAgB,cAAc,GAAG,QAAuC,CACtE,IAAM,KAAO,IAAI,WACjB,IAAK,IAAM,SAAS,QAAS,KAAK,KAAK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C1D,IAAM,MAAQ,aAAa,SAAS,EAE9B,kBAAoB,IAAI,QAAQ,oBAChC,IAAM,MAAM,QAAQ,iBAAiB,EAAI,kBAAkB,GAAK,kBAChE,OAAS,IAAM,iBAAiB,GAAG,EAAI,KAEvC,QAAU,QAAQ,SAAW,gBAAgB,EAC7C,OAAS,eAAe,EAG1B,QACF,MAAM,OAAO,IAAI,UAAW,OAAO,EACnC,MAAM,OAAO,IAAI,SAAU,MAAM,EAC7B,SACF,MAAM,OAAO,IAAI,eAAgB,OAAO,YAAY,EACpD,MAAM,OAAO,IAAI,aAAc,OAAO,KAAK,EAC3C,MAAM,OAAO,IAAI,eAAgB,OAAO,OAAO,IAKlD,IAAa,QAAU,QACvB,IAAa,OAAS,OAEnB,QAAQ,mBACV,IAAI,UAAU,gBAAiB,OAAO,EAGxC,KAAK,CACP,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.11.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  function isProduction(){let env=typeof process<`u`?process.env?.NODE_ENV:void 0;return env!==`development`&&env!==`test`}export{isProduction as t};
12
- //# sourceMappingURL=is-production-BYwEumHI.mjs.map
12
+ //# sourceMappingURL=is-production-et6gyyxF.mjs.map