@forinda/kickjs 10.1.0 → 10.2.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 (210) hide show
  1. package/dist/adapter-C5I5e_-i.d.mts +4866 -0
  2. package/dist/adapter-C5I5e_-i.d.mts.map +1 -0
  3. package/dist/allowed-hosts-D6qcuK5I.d.mts +46 -0
  4. package/dist/allowed-hosts-D6qcuK5I.d.mts.map +1 -0
  5. package/dist/{app-module-DCA65GZZ.d.mts → app-module-Ftz6m7SO.d.mts} +8 -2
  6. package/dist/app-module-Ftz6m7SO.d.mts.map +1 -0
  7. package/dist/application-Ch5jT4fj.mjs +14 -0
  8. package/dist/application-Ch5jT4fj.mjs.map +1 -0
  9. package/dist/bootstrap-D56HIq1N.mjs +12 -0
  10. package/dist/{bootstrap-BdyBlBMe.mjs.map → bootstrap-D56HIq1N.mjs.map} +1 -1
  11. package/dist/bounded-counters-B9dzk5o_.mjs +12 -0
  12. package/dist/bounded-counters-B9dzk5o_.mjs.map +1 -0
  13. package/dist/breach-padding-C-Dnq8CS.d.mts +39 -0
  14. package/dist/breach-padding-C-Dnq8CS.d.mts.map +1 -0
  15. package/dist/{client-ip-BbLDp03S.mjs → client-ip-lYnBU2PR.mjs} +2 -2
  16. package/dist/{client-ip-BbLDp03S.mjs.map → client-ip-lYnBU2PR.mjs.map} +1 -1
  17. package/dist/config/index.d.mts +1 -1
  18. package/dist/config/index.mjs +2 -2
  19. package/dist/config-BfImCyaG.mjs +12 -0
  20. package/dist/{config-CJiGeOca.mjs.map → config-BfImCyaG.mjs.map} +1 -1
  21. package/dist/{container-CS9v9UFU.mjs → container-C2aTj8Cb.mjs} +3 -3
  22. package/dist/{container-CS9v9UFU.mjs.map → container-C2aTj8Cb.mjs.map} +1 -1
  23. package/dist/context-C6iKf9hN.mjs +12 -0
  24. package/dist/context-C6iKf9hN.mjs.map +1 -0
  25. package/dist/{context-errors-7C5TBYn7.mjs → context-errors-6psUheqc.mjs} +2 -2
  26. package/dist/{context-errors-7C5TBYn7.mjs.map → context-errors-6psUheqc.mjs.map} +1 -1
  27. package/dist/{contributor-runner-DBpRR5dl.mjs → contributor-runner-Bn-ipSS5.mjs} +3 -3
  28. package/dist/{contributor-runner-DBpRR5dl.mjs.map → contributor-runner-Bn-ipSS5.mjs.map} +1 -1
  29. package/dist/core/adapter.d.mts +1 -1
  30. package/dist/core/adapter.mjs +1 -1
  31. package/dist/core/app-module.d.mts +1 -1
  32. package/dist/core/app-module.mjs +1 -1
  33. package/dist/core/cache.mjs +1 -1
  34. package/dist/core/container.mjs +2 -2
  35. package/dist/core/cron.mjs +2 -2
  36. package/dist/core/decorators.d.mts +1 -1
  37. package/dist/core/decorators.mjs +2 -2
  38. package/dist/core/errors.mjs +2 -2
  39. package/dist/core/errors.mjs.map +1 -1
  40. package/dist/core/interfaces.mjs +1 -1
  41. package/dist/core/logger.mjs +1 -1
  42. package/dist/core/path.mjs +1 -1
  43. package/dist/core/plugin.d.mts +1 -1
  44. package/dist/core/plugin.mjs +1 -1
  45. package/dist/core/reactivity.mjs +1 -1
  46. package/dist/core-CFXpwc7m.mjs +12 -0
  47. package/dist/{core-B0JmdBvX.mjs.map → core-CFXpwc7m.mjs.map} +1 -1
  48. package/dist/{cors-CsibNTQ6.d.mts → cors-2Bwhyhpt.d.mts} +4 -1
  49. package/dist/{cors-CsibNTQ6.d.mts.map → cors-2Bwhyhpt.d.mts.map} +1 -1
  50. package/dist/csrf-C3RRSCMs.mjs +12 -0
  51. package/dist/csrf-C3RRSCMs.mjs.map +1 -0
  52. package/dist/{csrf-C73UkRgc.d.mts → csrf-Cy1meSpf.d.mts} +27 -3
  53. package/dist/csrf-Cy1meSpf.d.mts.map +1 -0
  54. package/dist/decorate-DkxaoRo5.mjs +13 -0
  55. package/dist/decorate-DkxaoRo5.mjs.map +1 -0
  56. package/dist/{decorators-BxNSz9Qt.d.mts → decorators-DaQUNXOn.d.mts} +2 -2
  57. package/dist/{decorators-BxNSz9Qt.d.mts.map → decorators-DaQUNXOn.d.mts.map} +1 -1
  58. package/dist/{define-adapter-BLKlUbSL.mjs → define-adapter-BRJ6lXkV.mjs} +2 -2
  59. package/dist/{define-adapter-BLKlUbSL.mjs.map → define-adapter-BRJ6lXkV.mjs.map} +1 -1
  60. package/dist/{disposables-CuY2S3bw.mjs → disposables-5nFqc1aC.mjs} +2 -2
  61. package/dist/{disposables-CuY2S3bw.mjs.map → disposables-5nFqc1aC.mjs.map} +1 -1
  62. package/dist/errors-By6UueCm.d.mts.map +1 -1
  63. package/dist/handler-Dl_1fGxE.mjs +12 -0
  64. package/dist/handler-Dl_1fGxE.mjs.map +1 -0
  65. package/dist/{helmet-C2QEU6S-.d.mts → helmet-CEOmo516.d.mts} +4 -1
  66. package/dist/helmet-CEOmo516.d.mts.map +1 -0
  67. package/dist/host-DTQ5pZgg.mjs +12 -0
  68. package/dist/host-DTQ5pZgg.mjs.map +1 -0
  69. package/dist/http/application.d.mts +2 -2
  70. package/dist/http/application.mjs +2 -2
  71. package/dist/http/bootstrap.d.mts +1 -1
  72. package/dist/http/bootstrap.mjs +2 -2
  73. package/dist/http/context.d.mts +2 -2
  74. package/dist/http/context.mjs +2 -2
  75. package/dist/http/middleware/allowed-hosts.d.mts +3 -0
  76. package/dist/http/middleware/allowed-hosts.mjs +12 -0
  77. package/dist/http/middleware/allowed-hosts.mjs.map +1 -0
  78. package/dist/http/middleware/breach-padding.d.mts +3 -0
  79. package/dist/http/middleware/breach-padding.mjs +12 -0
  80. package/dist/http/middleware/breach-padding.mjs.map +1 -0
  81. package/dist/http/middleware/cors.d.mts +1 -1
  82. package/dist/http/middleware/cors.mjs +2 -2
  83. package/dist/http/middleware/cors.mjs.map +1 -1
  84. package/dist/http/middleware/csrf.d.mts +2 -2
  85. package/dist/http/middleware/csrf.mjs +2 -2
  86. package/dist/http/middleware/error-handler.d.mts +1 -1
  87. package/dist/http/middleware/error-handler.mjs +2 -2
  88. package/dist/http/middleware/error-handler.mjs.map +1 -1
  89. package/dist/http/middleware/helmet.d.mts +1 -1
  90. package/dist/http/middleware/helmet.mjs +2 -2
  91. package/dist/http/middleware/helmet.mjs.map +1 -1
  92. package/dist/http/middleware/rate-limit.d.mts +2 -2
  93. package/dist/http/middleware/rate-limit.mjs +2 -2
  94. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  95. package/dist/http/middleware/request-id.mjs +2 -2
  96. package/dist/http/middleware/request-id.mjs.map +1 -1
  97. package/dist/http/middleware/request-logger.mjs +2 -2
  98. package/dist/http/middleware/session.d.mts +2 -2
  99. package/dist/http/middleware/session.mjs +2 -2
  100. package/dist/http/middleware/session.mjs.map +1 -1
  101. package/dist/http/middleware/spa.d.mts +1 -1
  102. package/dist/http/middleware/spa.mjs +2 -2
  103. package/dist/http/middleware/upload.d.mts +1 -1
  104. package/dist/http/middleware/upload.mjs +2 -2
  105. package/dist/http/middleware/validate.d.mts +2 -2
  106. package/dist/http/middleware/validate.mjs +2 -2
  107. package/dist/http/middleware/validate.mjs.map +1 -1
  108. package/dist/http/middleware/views.d.mts +1 -1
  109. package/dist/http/middleware/views.mjs +2 -2
  110. package/dist/http/query/index.mjs +2 -2
  111. package/dist/http/router-builder.d.mts +1 -1
  112. package/dist/http/router-builder.mjs +2 -2
  113. package/dist/http/runtimes/fastify.d.mts +5 -1
  114. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  115. package/dist/http/runtimes/fastify.mjs +3 -3
  116. package/dist/http/runtimes/fastify.mjs.map +1 -1
  117. package/dist/http/runtimes/h3-web.mjs +1 -1
  118. package/dist/http/runtimes/h3.d.mts +1 -1
  119. package/dist/http/runtimes/h3.d.mts.map +1 -1
  120. package/dist/http/runtimes/h3.mjs +2 -2
  121. package/dist/http/runtimes/h3.mjs.map +1 -1
  122. package/dist/{index-CNHSbZTE.d.mts → index-CuiWSnZL.d.mts} +3 -2
  123. package/dist/index-CuiWSnZL.d.mts.map +1 -0
  124. package/dist/index.d.mts +16 -18
  125. package/dist/index.mjs +6 -2
  126. package/dist/index.mjs.map +1 -1
  127. package/dist/is-production-tnFh6NCj.mjs +12 -0
  128. package/dist/is-production-tnFh6NCj.mjs.map +1 -0
  129. package/dist/{jobs-BQ4t3TAb.mjs → jobs-lLcPhIqq.mjs} +3 -3
  130. package/dist/{jobs-BQ4t3TAb.mjs.map → jobs-lLcPhIqq.mjs.map} +1 -1
  131. package/dist/kv-stores-_wz4DEiw.mjs +12 -0
  132. package/dist/kv-stores-_wz4DEiw.mjs.map +1 -0
  133. package/dist/{metadata-zvd6AWkE.mjs → metadata-Tc6jhIBi.mjs} +2 -2
  134. package/dist/{metadata-zvd6AWkE.mjs.map → metadata-Tc6jhIBi.mjs.map} +1 -1
  135. package/dist/{observers-DZgs48UM.mjs → observers-IGga6yut.mjs} +2 -2
  136. package/dist/{observers-DZgs48UM.mjs.map → observers-IGga6yut.mjs.map} +1 -1
  137. package/dist/{query-B_k9qn0R.mjs → query-AnbWMCd6.mjs} +2 -2
  138. package/dist/{query-B_k9qn0R.mjs.map → query-AnbWMCd6.mjs.map} +1 -1
  139. package/dist/{rate-limit-Bwed3jOV.d.mts → rate-limit-BgoeahE5.d.mts} +17 -2
  140. package/dist/rate-limit-BgoeahE5.d.mts.map +1 -0
  141. package/dist/reply-DjysdCPI.mjs +12 -0
  142. package/dist/reply-DjysdCPI.mjs.map +1 -0
  143. package/dist/respond-vPZlRnZR.mjs +12 -0
  144. package/dist/respond-vPZlRnZR.mjs.map +1 -0
  145. package/dist/{route-flag-BWuvJsGZ.mjs → route-flag-BjRpxryx.mjs} +3 -3
  146. package/dist/{route-flag-BWuvJsGZ.mjs.map → route-flag-BjRpxryx.mjs.map} +1 -1
  147. package/dist/{route-policy-B3vM6bSf.mjs → route-policy-Pffte5M1.mjs} +2 -2
  148. package/dist/{route-policy-B3vM6bSf.mjs.map → route-policy-Pffte5M1.mjs.map} +1 -1
  149. package/dist/{router-builder-JvMTp50k.mjs → router-builder-CrWKq6O2.mjs} +3 -3
  150. package/dist/router-builder-CrWKq6O2.mjs.map +1 -0
  151. package/dist/{session-B4hOZj90.d.mts → session-ChXx7jG5.d.mts} +31 -4
  152. package/dist/session-ChXx7jG5.d.mts.map +1 -0
  153. package/dist/settings-C8VKewNS.d.mts +119 -0
  154. package/dist/settings-C8VKewNS.d.mts.map +1 -0
  155. package/dist/settings-CFtEAQUs.mjs +14 -0
  156. package/dist/settings-CFtEAQUs.mjs.map +1 -0
  157. package/dist/{upload-config-Dz2INCaa.mjs → upload-config-DLgt4l7F.mjs} +2 -2
  158. package/dist/{upload-config-Dz2INCaa.mjs.map → upload-config-DLgt4l7F.mjs.map} +1 -1
  159. package/dist/url-for-Cyh7pJCb.mjs +12 -0
  160. package/dist/url-for-Cyh7pJCb.mjs.map +1 -0
  161. package/dist/validate-CzjCbRUn.d.mts +53 -0
  162. package/dist/validate-CzjCbRUn.d.mts.map +1 -0
  163. package/dist/web.d.mts +19 -19
  164. package/dist/web.d.mts.map +1 -1
  165. package/dist/web.mjs +2 -2
  166. package/dist/web.mjs.map +1 -1
  167. package/package.json +14 -1
  168. package/dist/adapter-ClEh-Oos.d.mts +0 -2134
  169. package/dist/adapter-ClEh-Oos.d.mts.map +0 -1
  170. package/dist/app-module-DCA65GZZ.d.mts.map +0 -1
  171. package/dist/application-Dv514EeR.mjs +0 -12
  172. package/dist/application-Dv514EeR.mjs.map +0 -1
  173. package/dist/application-oIPzgjfk.d.mts +0 -1589
  174. package/dist/application-oIPzgjfk.d.mts.map +0 -1
  175. package/dist/bootstrap-BdyBlBMe.mjs +0 -12
  176. package/dist/config-CJiGeOca.mjs +0 -12
  177. package/dist/context-CtL9RxXp.mjs +0 -12
  178. package/dist/context-CtL9RxXp.mjs.map +0 -1
  179. package/dist/core-B0JmdBvX.mjs +0 -12
  180. package/dist/csrf--1t4qDov.mjs +0 -12
  181. package/dist/csrf--1t4qDov.mjs.map +0 -1
  182. package/dist/csrf-C73UkRgc.d.mts.map +0 -1
  183. package/dist/decorate-BHkdkV4l.mjs +0 -11
  184. package/dist/env-BwzF9MkZ.mjs +0 -13
  185. package/dist/env-BwzF9MkZ.mjs.map +0 -1
  186. package/dist/error-handler-BB9wAElm.d.mts +0 -63
  187. package/dist/error-handler-BB9wAElm.d.mts.map +0 -1
  188. package/dist/handler-zKfIgNo4.mjs +0 -13
  189. package/dist/handler-zKfIgNo4.mjs.map +0 -1
  190. package/dist/helmet-C2QEU6S-.d.mts.map +0 -1
  191. package/dist/index-CNHSbZTE.d.mts.map +0 -1
  192. package/dist/kv-stores-Co5k2PYA.d.mts +0 -367
  193. package/dist/kv-stores-Co5k2PYA.d.mts.map +0 -1
  194. package/dist/kv-stores-DsfVy2fk.mjs +0 -12
  195. package/dist/kv-stores-DsfVy2fk.mjs.map +0 -1
  196. package/dist/module-registry-Daf_P2oD.mjs +0 -12
  197. package/dist/module-registry-Daf_P2oD.mjs.map +0 -1
  198. package/dist/rate-limit-Bwed3jOV.d.mts.map +0 -1
  199. package/dist/reply-BDK9xt7Z.mjs +0 -12
  200. package/dist/reply-BDK9xt7Z.mjs.map +0 -1
  201. package/dist/respond-DFRj2-7q.mjs +0 -12
  202. package/dist/respond-DFRj2-7q.mjs.map +0 -1
  203. package/dist/router-builder-JvMTp50k.mjs.map +0 -1
  204. package/dist/router-builder-zWuVIOmd.d.mts +0 -56
  205. package/dist/router-builder-zWuVIOmd.d.mts.map +0 -1
  206. package/dist/session-B4hOZj90.d.mts.map +0 -1
  207. package/dist/upload-CiMtdXWD.d.mts +0 -104
  208. package/dist/upload-CiMtdXWD.d.mts.map +0 -1
  209. package/dist/validate-DMYpUnrf.d.mts +0 -25
  210. package/dist/validate-DMYpUnrf.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"h3.mjs","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"sourcesContent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// Targets h3 v2: the web-standard line where `event.req` is a WHATWG Request,\n// handlers return values/Responses, and `app.fetch(request)` is the universal\n// entry. h3 v1 is not supported; loading it fails fast with upgrade guidance.\n//\n// The request pipeline runs through the shared web driver pair\n// (`../web/driver`, `../web/handler`) — the same code path the\n// `@forinda/kickjs/web` edge entry uses, so node bootstrap and edge deploys\n// exercise identical request semantics.\n//\n// Unmatched requests: behind a node host that passed `next` (`kick dev`'s\n// Vite server, `app.handle(req, res, next)`), they are handed back to it\n// like the Fastify runtime does, unless `notFoundFallthrough: false`;\n// everywhere else kick's notFound handler answers them.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { compileWebRoute, readThrough, type WebRouteHooks } from '../web/handler'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger, describeError } from '../../core/logger'\n\nconst log = createLogger('H3Runtime')\n\nconst peerRequire = createRequire(import.meta.url)\n\nconst NOTFOUND_MW = Symbol('kickjs.h3web.notFoundMw')\nconst ERROR_MW = Symbol('kickjs.h3web.errorMw')\nconst ASSEMBLED = Symbol('kickjs.h3web.assembled')\nconst NOOP_NEXT = (): void => {}\n/** The host's `next`, stashed on the node request by `nodeHandler`. */\nconst NEXT = Symbol('kickjs.h3web.next')\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.h3web.noFallthrough')\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\n/** h3 v2's \"the node response was handled elsewhere\" return value. */\nconst H3_HANDLED = Symbol.for('h3.handled')\n\n// Minimal structural surface of h3 v2 we depend on.\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n use(...args: unknown[]): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request & { runtime?: { node?: { req: IncomingMessage; res: ServerResponse } } }\n url: URL\n context: { params?: Record<string, string> }\n}\n\ninterface H3v2Module {\n H3: new (config?: unknown) => H3AppLike\n toNodeHandler: (app: H3AppLike) => (req: IncomingMessage, res: ServerResponse) => void\n fromNodeHandler: (mw: unknown) => unknown\n}\n\nexport interface H3RuntimeOptions {\n /**\n * Pre-imported h3 module, for when the app's `h3` is not the one this\n * package resolves (a linked checkout, a bundler):\n * `h3Runtime({ h3: await import('h3') })`.\n * Omitted → the installed `h3` peer.\n */\n h3?: unknown\n}\n\n/** An h3 module as `import()` or `require()` hands it over, ESM interop unwrapped. */\nfunction unwrapH3Module(mod: unknown): Record<string, unknown> {\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n return m && m.__esModule && m.default ? { ...m.default, ...m } : m\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n const resolved = unwrapH3Module(injected ?? peerRequire('h3')) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs: h3Runtime() requires h3 v2, but the installed h3 has no H3 class — that is the v1 line, ' +\n 'which this version of KickJS no longer supports. Upgrade: `pnpm add h3@^2`.',\n )\n }\n return resolved\n}\n\n/**\n * Bridge a connect-style terminal middleware (kick's notFound / error\n * handlers) onto the web driver pair, returning the produced Response.\n */\nasync function runConnectTerminal(\n mw: ConnectMiddleware | undefined,\n event: H3EventLike,\n err?: unknown,\n): Promise<Response> {\n const shim = new WebRequestShim(event.req, event.url)\n // What the app's connect middleware set (session, an adapter's slot) is\n // visible to the error / not-found handler, as on the route itself.\n const carry = event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req\n const req = carry ? readThrough(shim, carry) : shim\n const driver = new WebResponseDriver(event.req.signal)\n if (mw) {\n const returned =\n err !== undefined\n ? (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n : (mw as (rq: unknown, rs: unknown, n: () => void) => unknown)(req, driver, NOOP_NEXT)\n // An async handler answers after an await: wait for it before deciding\n // nothing answered. One that rejects is an error in its own right.\n if (typeof (returned as PromiseLike<void> | undefined)?.then === 'function') {\n try {\n await returned\n } catch (handlerErr) {\n if (!driver.settled) {\n log.error(\n handlerErr,\n `h3: the ${err !== undefined ? 'error' : 'not-found'} handler failed`,\n )\n driver.status(500).json({ error: 'Internal Server Error' })\n }\n }\n }\n }\n if (!driver.settled) {\n if (err !== undefined) {\n // The configured error handler ran but didn't settle the response\n // (or there wasn't one). Emitting a bare 500 with no log entry\n // makes this failure invisible on both sides — log it here, since\n // by definition nothing downstream will.\n log.error(err, `h3: error handler did not settle the response — ${describeError(err)}`)\n driver.status(500).json({\n error: 'Internal Server Error',\n ...(typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'\n ? {}\n : { message: describeError(err) }),\n })\n } else {\n driver.status(404).json({ error: 'Not Found' })\n }\n }\n return driver.ready\n}\n\n// ── Connect middleware on the fetch path ─────────────────────────────────\n//\n// `app.fetch(request)` (edge, Bun, Deno, a serverless function) carries no\n// node req/res, and h3's `fromNodeHandler` throws without one. Connect\n// middleware there runs against the web driver pair instead: one request shim\n// per event (so `req.requestId` set by one middleware is seen by the next) and\n// one header bag per event that is merged into whatever Response comes back.\n// The merge is ours rather than h3's `event.res.headers` because h3 skips\n// prepared headers on non-2xx responses, and a 404/422/500 must still carry\n// helmet's headers and the request id, exactly as on node.\n\ninterface FetchConnectState {\n req: WebRequestShim\n headers: Headers\n}\n\nconst FETCH_CONNECT = new WeakMap<object, FetchConnectState>()\n\nfunction fetchConnectState(event: H3EventLike): FetchConnectState {\n let state = FETCH_CONNECT.get(event)\n if (!state) {\n state = { req: new WebRequestShim(event.req, event.url), headers: new Headers() }\n FETCH_CONNECT.set(event, state)\n }\n return state\n}\n\n/**\n * Add the headers connect middleware set to `response`. The response's own\n * headers win — a later `setHeader` overrides an earlier one on node too.\n * Consumed once, so every middleware layer can call it on the way out.\n */\nfunction withConnectHeaders(event: H3EventLike, response: Response): Response {\n const state = FETCH_CONNECT.get(event)\n if (!state) return response\n const missing = [...state.headers].filter(\n ([name]) => name === 'set-cookie' || !response.headers.has(name),\n )\n state.headers = new Headers()\n if (missing.length === 0) return response\n try {\n for (const [name, value] of missing) response.headers.append(name, value)\n return response\n } catch {\n // Immutable headers (a Response from fetch) — rebuild around the body.\n const headers = new Headers(response.headers)\n for (const [name, value] of missing) headers.append(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n}\n\n/**\n * The node `res` surface connect middleware uses, over the web driver:\n * headers go to the per-event bag, `statusCode`, and `finish`/`close`\n * emitted once the response exists.\n */\nclass FetchConnectResponse extends WebResponseDriver {\n private code = 200\n private listeners: Array<[string, (...args: unknown[]) => void]> = []\n\n constructor(\n private readonly prepared: Headers,\n signal: AbortSignal,\n ) {\n super(signal)\n }\n\n get statusCode(): number {\n return this.code\n }\n\n set statusCode(code: number) {\n this.status(code)\n }\n\n override status(code: number): this {\n this.code = code\n return super.status(code)\n }\n\n override writeHead(code: number, headers?: Record<string, string | number | string[]>): this {\n this.code = code\n return super.writeHead(code, headers)\n }\n\n override setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.prepared.delete(name)\n for (const v of value) this.prepared.append(name, String(v))\n } else {\n this.prepared.set(name, String(value))\n }\n return this\n }\n\n getHeader(name: string): string | undefined {\n return this.prepared.get(name) ?? undefined\n }\n\n hasHeader(name: string): boolean {\n return this.prepared.has(name)\n }\n\n removeHeader(name: string): void {\n this.prepared.delete(name)\n }\n\n override once(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners.push([event, listener])\n return this\n }\n\n on(event: string, listener: (...args: unknown[]) => void): this {\n return this.once(event, listener)\n }\n\n removeListener(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners = this.listeners.filter(([e, l]) => e !== event || l !== listener)\n return this\n }\n\n off(event: string, listener: (...args: unknown[]) => void): this {\n return this.removeListener(event, listener)\n }\n\n /**\n * The response exists (or the request failed): fire `finish` then `close`.\n * Runs before `withConnectHeaders` merges this response's headers into the\n * route's, so a `finish` listener can still set one — the cookie session\n * store writes its cookie there.\n */\n done(): void {\n for (const event of ['finish', 'close']) {\n for (const [e, listener] of this.listeners) if (e === event) listener()\n this.listeners = this.listeners.filter(([e]) => e !== event)\n }\n }\n}\n\nfunction runConnectOnFetch(\n mw: ConnectMiddleware,\n event: H3EventLike,\n next: () => unknown,\n): Promise<unknown> {\n const state = fetchConnectState(event)\n const res = new FetchConnectResponse(state.headers, event.req.signal)\n\n return new Promise((resolve, reject) => {\n const respond = (response: Response): void => {\n res.done()\n resolve(withConnectHeaders(event, response))\n }\n const fail = (err: unknown): void => {\n res.done()\n reject(err)\n }\n\n // The middleware answered itself (`res.end`, `res.json`, `writeHead`).\n void res.ready.then(respond)\n\n const connectNext = (err?: unknown): void => {\n if (err) return fail(err)\n if (res.settled) return\n // The route builds its request store from the inbound header; hand it the\n // id requestScope/requestId settled on so body, logs and header agree.\n const id = state.req.requestId\n if (id && event.req.headers.get('x-request-id') !== id) {\n try {\n event.req.headers.set('x-request-id', id)\n } catch {\n // Immutable request headers on some runtimes — the route mints its own id.\n }\n }\n let downstream: unknown\n try {\n // Synchronous, so downstream work starts inside any AsyncLocalStorage\n // scope this middleware opened (requestScopeMiddleware).\n downstream = next()\n } catch (e) {\n return fail(e)\n }\n Promise.resolve(downstream).then((value) => {\n if (value instanceof Response) return respond(value)\n res.done()\n resolve(value)\n }, fail)\n }\n\n try {\n ;(mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => void)(\n state.req,\n res,\n connectNext,\n )\n } catch (err) {\n fail(err)\n }\n })\n}\n\n/**\n * Terminal catch-all AFTER all mounted routes: kick's own notFound handler\n * answers unmatched paths (h3 v2's default 404 never fires). rou3 ranks `/**`\n * below every concrete route, so registration time does not matter.\n */\nfunction assembleCatchAll(app: H3AppLike): void {\n const state = app as unknown as Record<symbol, unknown>\n if (state[ASSEMBLED]) return\n state[ASSEMBLED] = true\n app.all('/**', (event: H3EventLike) => {\n const node = event.req.runtime?.node\n const next = (node?.req as (IncomingMessage & { [NEXT]?: () => void }) | undefined)?.[NEXT]\n if (node && next && !state[NO_FALLTHROUGH]) {\n // Hand the request back to the host and tell h3 the node response is\n // taken care of; srvx then leaves the already-written response alone.\n return new Promise((resolve) => {\n const done = () => resolve(H3_HANDLED)\n node.res.once('finish', done)\n node.res.once('close', done)\n next()\n })\n }\n const mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n}\n\ntype ProxyTrust = (address: string, hop: number) => boolean\n\n/**\n * The `trustProxy` forms h3 can honour without an address-matching library:\n * `true` (every hop), a hop count, or a predicate — Express's semantics for\n * each. Address and subnet lists are not supported here; they are refused\n * with a warning and the socket address is kept, so a misread rule never\n * trusts a header it should not.\n */\nfunction proxyTrust(option: RuntimeAppOptions['trustProxy']): ProxyTrust | undefined {\n if (option === undefined || option === false) return undefined\n if (option === true) return () => true\n if (typeof option === 'number') return (_address, hop) => hop < option\n if (typeof option === 'function') return option\n log.warn(\n 'h3: trustProxy as an address or subnet list is not supported; client IPs ' +\n 'use the socket address. Use a hop count or a function instead.',\n )\n return undefined\n}\n\n/**\n * Express's `proxy-addr` walk: from the socket outward through\n * `x-forwarded-for`, stop at the first address the rule does not trust.\n */\nfunction forwardedClientIp(req: IncomingMessage, trust: ProxyTrust): string | undefined {\n const socket = req.socket?.remoteAddress\n if (!socket) return undefined\n const header = req.headers['x-forwarded-for']\n const forwarded = (Array.isArray(header) ? header.join(',') : (header ?? ''))\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n .toReversed()\n const chain = [socket, ...forwarded]\n for (let hop = 0; hop < chain.length - 1; hop++) {\n if (!trust(chain[hop]!, hop)) return chain[hop]\n }\n return chain[chain.length - 1]\n}\n\n/**\n * A middleware mounted at a path sees `req.url` relative to that path, as on\n * Express — `serve-static` mounted at `/files` must look up\n * `/nested/a.txt`, not `/files/nested/a.txt`. h3 v2 leaves the URL whole, so\n * strip the prefix for the call and restore it when the middleware passes on.\n * `req.originalUrl` keeps the full URL, as Express sets it.\n */\nfunction stripMountPrefix(path: string, mw: ConnectMiddleware): ConnectMiddleware {\n const prefix = path.endsWith('/') ? path.slice(0, -1) : path\n if (prefix === '') return mw\n return ((\n req: IncomingMessage & { originalUrl?: string },\n res: unknown,\n next: (err?: unknown) => void,\n ) => {\n const url = req.url ?? '/'\n const rest = url.startsWith(prefix) ? url.slice(prefix.length) : null\n if (rest === null || (rest !== '' && rest[0] !== '/' && rest[0] !== '?')) {\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n next,\n )\n }\n req.originalUrl ??= url\n req.url = rest.startsWith('/') ? rest : `/${rest}`\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n (err?: unknown) => {\n req.url = url\n next(err)\n },\n )\n }) as unknown as ConnectMiddleware\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3Runtime(options: H3RuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const holder: { app?: H3AppLike } = {}\n const app = new H3({\n // Engine-level errors (middleware throws outside the kick pipeline)\n // dispatch to the kick error handler once setErrorHandler stashes it.\n onError: (error: unknown, event: H3EventLike) => {\n const mw = (holder.app as unknown as Record<symbol, ConnectMiddleware | undefined>)?.[\n ERROR_MW\n ]\n return runConnectTerminal(mw, event, error).then((response) =>\n withConnectHeaders(event, response),\n )\n },\n })\n holder.app = app\n ;(app as unknown as Record<symbol, unknown>)[NO_FALLTHROUGH] =\n options.notFoundFallthrough === false\n ;(app as unknown as Record<symbol, unknown>)[TRUST_PROXY] = proxyTrust(options.trustProxy)\n return app\n },\n\n nodeHandler(app) {\n assembleCatchAll(app)\n const listener = toNodeHandler(app)\n const trust = (app as unknown as Record<symbol, unknown>)[TRUST_PROXY] as\n | ProxyTrust\n | undefined\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n // Express and Fastify derive `req.ip` from their trust-proxy settings;\n // this is h3's equivalent, off unless the app opts in, because an\n // unverified `x-forwarded-for` is client-controllable. Without it every\n // caller behind a proxy shares the proxy's address (one rate-limit bucket).\n if (trust && !(req as { ip?: string }).ip) {\n const ip = forwardedClientIp(req, trust)\n if (ip) (req as { ip?: string }).ip = ip\n }\n // h3 v2 adds 'close' / 'finish' listeners for every connect middleware\n // and keeps them until the response ends, so an ordinary middleware\n // stack crosses Node's default of 10 and warns about a leak on every\n // request. They go away with the response; no limit is needed.\n res.setMaxListeners(0)\n try {\n const result = listener(req, res) as unknown\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n void (result as Promise<unknown>).catch((err) => next?.(err))\n }\n } catch (err) {\n next?.(err)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const hooks: WebRouteHooks = {\n onError: async (err, req, driver) => {\n const mw = (app as unknown as Record<symbol, ConnectMiddleware | undefined>)[ERROR_MW]\n if (!mw) return\n // Awaited: an async handler answers after its await, and the\n // pipeline falls back to its own answer once this returns.\n try {\n await (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } catch (handlerErr) {\n if (!driver.settled) {\n log.error(handlerErr, 'h3: the error handler failed')\n driver.status(500).json({ error: 'Internal Server Error' })\n }\n }\n },\n }\n const run = compileWebRoute(entry, hooks)\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n carry: event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req,\n }),\n )\n }\n }\n },\n\n useConnect(app, rawMw: ConnectMiddleware, opts?: UseConnectOptions) {\n const path = opts?.path\n // A list mounts each member, as Express does.\n if (Array.isArray(path)) {\n for (const member of path) this.useConnect!(app, rawMw, { path: member })\n return\n }\n const mw = typeof path === 'string' ? stripMountPrefix(path, rawMw) : rawMw\n // Behind a node server (toNodeHandler) the event carries node req/res and\n // h3's own bridge runs the middleware unchanged. Called through\n // `app.fetch(request)` there is none and fromNodeHandler would throw, so\n // the middleware runs against the web driver pair instead.\n const viaNode = fromNodeHandler(mw) as (event: H3EventLike) => unknown\n const handler = (event: H3EventLike, next: () => unknown) =>\n event.req.runtime?.node?.res ? viaNode(event) : runConnectOnFetch(mw, event, next)\n if (path instanceof RegExp) {\n // h3 routes by string pattern only; test the pathname per request.\n // Like Express, a pattern mount leaves `req.url` whole.\n app.use((event: H3EventLike, next: () => unknown) =>\n path.test(event.url.pathname) ? handler(event, next) : next(),\n )\n } else if (typeof path === 'string') {\n // h3 `use` is exact-match; `/**` covers the subtree.\n app.use(joinPath(path, '/**'), handler)\n } else {\n app.use(handler)\n }\n },\n\n serveStatic(app, prefix, dir) {\n // serve-static bridged like any other connect middleware (node only).\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[NOTFOUND_MW] = mw\n // Here as well as in nodeHandler: an app only ever called through\n // `app.fetch` never reaches nodeHandler, and would answer h3's own 404.\n assembleCatchAll(app)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n // srvx's node adapter writes HTTP/2 compat responses (it branches on\n // httpVersion \"2.0\"), so the node path serves `server.http2` too.\n http2: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types, for the `kick/runtime` typegen\n * augmentation. Mirrors `ExpressRuntimeTypes`.\n */\nexport interface H3RuntimeTypes {\n request: Request\n response: Response\n app: typeof import('h3') extends { H3: new (...args: never[]) => infer A } ? A : unknown\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n\n/** @deprecated Use {@link h3Runtime} — the same runtime. Removed in the next major. */\nexport const h3WebRuntime = h3Runtime\n/** @deprecated Use {@link H3RuntimeOptions}. */\nexport type H3WebRuntimeOptions = H3RuntimeOptions\n/** @deprecated Use {@link H3RuntimeTypes}. */\nexport type H3WebRuntimeTypes = H3RuntimeTypes\n"],"mappings":";;;;;;;;;;8NA8BA,MAAM,IAAM,aAAa,WAAW,EAE9B,YAAc,cAAc,YAAY,GAAG,EAE3C,YAAc,OAAO,yBAAyB,EAC9C,SAAW,OAAO,sBAAsB,EACxC,UAAY,OAAO,wBAAwB,EAC3C,cAAwB,CAAC,EAEzB,KAAO,OAAO,mBAAmB,EAEjC,eAAiB,OAAO,4BAA4B,EACpD,YAAc,OAAO,sBAAsB,EAE3C,WAAa,OAAO,IAAI,YAAY,EAgC1C,SAAS,eAAe,IAAuC,CAC7D,IAAM,EAAI,IAIV,OAAO,GAAK,EAAE,YAAc,EAAE,QAAU,CAAE,GAAG,EAAE,QAAS,GAAG,CAAE,EAAI,CACnE,CAGA,SAAS,SAAS,SAAgC,CAChD,IAAM,SAAW,eAAe,UAAY,YAAY,IAAI,CAAC,EAC7D,GAAI,OAAO,SAAS,IAAO,WACzB,MAAU,MACR,sLAEF,EAEF,OAAO,QACT,CAMA,eAAe,mBACb,GACA,MACA,I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EAAG,CACvB,IAAK,IAAM,UAAU,KAAM,KAAK,WAAY,IAAK,MAAO,CAAE,KAAM,MAAO,CAAC,EACxE,MACF,CACA,IAAM,GAAK,OAAO,MAAS,SAAW,iBAAiB,KAAM,KAAK,EAAI,MAKhE,QAAU,gBAAgB,EAAE,EAC5B,SAAW,MAAoB,OACnC,MAAM,IAAI,SAAS,MAAM,IAAM,QAAQ,KAAK,EAAI,kBAAkB,GAAI,MAAO,IAAI,EAC/E,gBAAgB,OAGlB,IAAI,KAAK,MAAoB,OAC3B,KAAK,KAAK,MAAM,IAAI,QAAQ,EAAI,QAAQ,MAAO,IAAI,EAAI,KAAK,CAC9D,EACS,OAAO,MAAS,SAEzB,IAAI,IAAI,SAAS,KAAM,KAAK,EAAG,OAAO,EAEtC,IAAI,IAAI,OAAO,CAEnB,EAEA,YAAY,IAAK,OAAQ,IAAK,CAE5B,IAAM,YAAc,YAAY,cAAc,EAC9C,KAAK,WAAW,IAAK,YAAY,GAAG,EAAwB,CAAE,KAAM,MAAO,CAAC,CAC9E,EAEA,YAAY,IAAK,GAAuB,CACrC,IAAsD,aAAe,GAGtE,iBAAiB,GAAG,CACtB,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAAsD,UAAY,EACrE,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GAGnB,MAAO,EACT,CACF,CACF,CAaA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C,CAGA,MAAa,aAAe"}
1
+ {"version":3,"file":"h3.mjs","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"sourcesContent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// Targets h3 v2: the web-standard line where `event.req` is a WHATWG Request,\n// handlers return values/Responses, and `app.fetch(request)` is the universal\n// entry. h3 v1 is not supported; loading it fails fast with upgrade guidance.\n//\n// The request pipeline runs through the shared web driver pair\n// (`../web/driver`, `../web/handler`) — the same code path the\n// `@forinda/kickjs/web` edge entry uses, so node bootstrap and edge deploys\n// exercise identical request semantics.\n//\n// Unmatched requests: behind a node host that passed `next` (`kick dev`'s\n// Vite server, `app.handle(req, res, next)`), they are handed back to it\n// like the Fastify runtime does, unless `notFoundFallthrough: false`;\n// everywhere else kick's notFound handler answers them.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\nimport { compileWebRoute, readThrough, type WebRouteHooks } from '../web/handler'\nimport { WebRequestShim, WebResponseDriver } from '../web/driver'\nimport { createLogger } from '../../core/logger'\nimport { errorHandler, notFoundHandler } from '../middleware/error-handler'\n\nconst builtInError = errorHandler()\nconst builtInNotFound = notFoundHandler()\nconst log = createLogger('H3Runtime')\n\nconst peerRequire = createRequire(import.meta.url)\n\nconst NOTFOUND_MW = Symbol('kickjs.h3web.notFoundMw')\nconst ERROR_MW = Symbol('kickjs.h3web.errorMw')\nconst ASSEMBLED = Symbol('kickjs.h3web.assembled')\nconst NOOP_NEXT = (): void => {}\n/** The host's `next`, stashed on the node request by `nodeHandler`. */\nconst NEXT = Symbol('kickjs.h3web.next')\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.h3web.noFallthrough')\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\nconst BODY_LIMIT = Symbol('kickjs.h3.bodyLimit')\n/** h3 v2's \"the node response was handled elsewhere\" return value. */\nconst H3_HANDLED = Symbol.for('h3.handled')\n\n// Minimal structural surface of h3 v2 we depend on.\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n use(...args: unknown[]): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request & { runtime?: { node?: { req: IncomingMessage; res: ServerResponse } } }\n url: URL\n context: { params?: Record<string, string> }\n}\n\ninterface H3v2Module {\n H3: new (config?: unknown) => H3AppLike\n toNodeHandler: (app: H3AppLike) => (req: IncomingMessage, res: ServerResponse) => void\n fromNodeHandler: (mw: unknown) => unknown\n}\n\nexport interface H3RuntimeOptions {\n /**\n * Pre-imported h3 module, for when the app's `h3` is not the one this\n * package resolves (a linked checkout, a bundler):\n * `h3Runtime({ h3: await import('h3') })`.\n * Omitted → the installed `h3` peer.\n */\n h3?: unknown\n}\n\n/** An h3 module as `import()` or `require()` hands it over, ESM interop unwrapped. */\nfunction unwrapH3Module(mod: unknown): Record<string, unknown> {\n const m = mod as { __esModule?: boolean; default?: Record<string, unknown> } & Record<\n string,\n unknown\n >\n return m && m.__esModule && m.default ? { ...m.default, ...m } : m\n}\n\n/** Resolve h3 (injected or peer-required) and fail fast unless it is v2. */\nfunction loadH3v2(injected?: unknown): H3v2Module {\n const resolved = unwrapH3Module(injected ?? peerRequire('h3')) as unknown as H3v2Module\n if (typeof resolved.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs: h3Runtime() requires h3 v2, but the installed h3 has no H3 class — that is the v1 line, ' +\n 'which this version of KickJS no longer supports. Upgrade: `pnpm add h3@^2`.',\n )\n }\n return resolved\n}\n\n/**\n * Bridge a connect-style terminal middleware (kick's notFound / error\n * handlers) onto the web driver pair, returning the produced Response.\n */\nasync function runConnectTerminal(\n mw: ConnectMiddleware | undefined,\n event: H3EventLike,\n err?: unknown,\n): Promise<Response> {\n const shim = new WebRequestShim(event.req, event.url)\n // What the app's connect middleware set (session, an adapter's slot) is\n // visible to the error / not-found handler, as on the route itself.\n const carry = event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req\n const req = carry ? readThrough(shim, carry) : shim\n const driver = new WebResponseDriver(event.req.signal)\n // A failing handler is an error in its own right: answered as one below.\n let failure = err\n if (mw) {\n const returned =\n err !== undefined\n ? (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n : (mw as (rq: unknown, rs: unknown, n: () => void) => unknown)(req, driver, NOOP_NEXT)\n // An async handler answers after an await: wait for it before deciding\n // nothing answered. One that rejects is an error in its own right.\n if (typeof (returned as PromiseLike<void> | undefined)?.then === 'function') {\n try {\n await returned\n } catch (handlerErr) {\n log.error(handlerErr, `h3: the ${err !== undefined ? 'error' : 'not-found'} handler failed`)\n failure ??= handlerErr\n }\n }\n }\n if (!driver.settled) {\n // The configured handler didn't answer (or there wasn't one): the\n // built-in handlers answer, in the shape every other engine uses. The\n // built-in error handler logs, so the failure still leaves a trace.\n if (failure !== undefined) await builtInError(failure, req, driver, NOOP_NEXT)\n else builtInNotFound(req, driver, NOOP_NEXT)\n }\n return driver.ready\n}\n\n// ── Connect middleware on the fetch path ─────────────────────────────────\n//\n// `app.fetch(request)` (edge, Bun, Deno, a serverless function) carries no\n// node req/res, and h3's `fromNodeHandler` throws without one. Connect\n// middleware there runs against the web driver pair instead: one request shim\n// per event (so `req.requestId` set by one middleware is seen by the next) and\n// one header bag per event that is merged into whatever Response comes back.\n// The merge is ours rather than h3's `event.res.headers` because h3 skips\n// prepared headers on non-2xx responses, and a 404/422/500 must still carry\n// helmet's headers and the request id, exactly as on node.\n\ninterface FetchConnectState {\n req: WebRequestShim\n headers: Headers\n}\n\nconst FETCH_CONNECT = new WeakMap<object, FetchConnectState>()\n\nfunction fetchConnectState(event: H3EventLike): FetchConnectState {\n let state = FETCH_CONNECT.get(event)\n if (!state) {\n state = { req: new WebRequestShim(event.req, event.url), headers: new Headers() }\n FETCH_CONNECT.set(event, state)\n }\n return state\n}\n\n/**\n * Add the headers connect middleware set to `response`. The response's own\n * headers win — a later `setHeader` overrides an earlier one on node too.\n * Consumed once, so every middleware layer can call it on the way out.\n */\nfunction withConnectHeaders(event: H3EventLike, response: Response): Response {\n const state = FETCH_CONNECT.get(event)\n if (!state) return response\n const missing = [...state.headers].filter(\n ([name]) => name === 'set-cookie' || !response.headers.has(name),\n )\n state.headers = new Headers()\n if (missing.length === 0) return response\n try {\n for (const [name, value] of missing) response.headers.append(name, value)\n return response\n } catch {\n // Immutable headers (a Response from fetch) — rebuild around the body.\n const headers = new Headers(response.headers)\n for (const [name, value] of missing) headers.append(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }\n}\n\n/**\n * The node `res` surface connect middleware uses, over the web driver:\n * headers go to the per-event bag, `statusCode`, and `finish`/`close`\n * emitted once the response exists.\n */\nclass FetchConnectResponse extends WebResponseDriver {\n private code = 200\n private listeners: Array<[string, (...args: unknown[]) => void]> = []\n\n constructor(\n private readonly prepared: Headers,\n signal: AbortSignal,\n ) {\n super(signal)\n }\n\n get statusCode(): number {\n return this.code\n }\n\n set statusCode(code: number) {\n this.status(code)\n }\n\n override status(code: number): this {\n this.code = code\n return super.status(code)\n }\n\n override writeHead(code: number, headers?: Record<string, string | number | string[]>): this {\n this.code = code\n return super.writeHead(code, headers)\n }\n\n override setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.prepared.delete(name)\n for (const v of value) this.prepared.append(name, String(v))\n } else {\n this.prepared.set(name, String(value))\n }\n return this\n }\n\n getHeader(name: string): string | undefined {\n return this.prepared.get(name) ?? undefined\n }\n\n hasHeader(name: string): boolean {\n return this.prepared.has(name)\n }\n\n removeHeader(name: string): void {\n this.prepared.delete(name)\n }\n\n override once(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners.push([event, listener])\n return this\n }\n\n on(event: string, listener: (...args: unknown[]) => void): this {\n return this.once(event, listener)\n }\n\n removeListener(event: string, listener: (...args: unknown[]) => void): this {\n this.listeners = this.listeners.filter(([e, l]) => e !== event || l !== listener)\n return this\n }\n\n off(event: string, listener: (...args: unknown[]) => void): this {\n return this.removeListener(event, listener)\n }\n\n /**\n * The response exists (or the request failed): fire `finish` then `close`.\n * Runs before `withConnectHeaders` merges this response's headers into the\n * route's, so a `finish` listener can still set one — the cookie session\n * store writes its cookie there.\n */\n done(): void {\n for (const event of ['finish', 'close']) {\n for (const [e, listener] of this.listeners) if (e === event) listener()\n this.listeners = this.listeners.filter(([e]) => e !== event)\n }\n }\n}\n\nfunction runConnectOnFetch(\n mw: ConnectMiddleware,\n event: H3EventLike,\n next: () => unknown,\n): Promise<unknown> {\n const state = fetchConnectState(event)\n const res = new FetchConnectResponse(state.headers, event.req.signal)\n\n return new Promise((resolve, reject) => {\n const respond = (response: Response): void => {\n res.done()\n resolve(withConnectHeaders(event, response))\n }\n const fail = (err: unknown): void => {\n res.done()\n reject(err)\n }\n\n // The middleware answered itself (`res.end`, `res.json`, `writeHead`).\n void res.ready.then(respond)\n\n const connectNext = (err?: unknown): void => {\n if (err) return fail(err)\n if (res.settled) return\n // The route builds its request store from the inbound header; hand it the\n // id requestScope/requestId settled on so body, logs and header agree.\n const id = state.req.requestId\n if (id && event.req.headers.get('x-request-id') !== id) {\n try {\n event.req.headers.set('x-request-id', id)\n } catch {\n // Immutable request headers on some runtimes — the route mints its own id.\n }\n }\n let downstream: unknown\n try {\n // Synchronous, so downstream work starts inside any AsyncLocalStorage\n // scope this middleware opened (requestScopeMiddleware).\n downstream = next()\n } catch (e) {\n return fail(e)\n }\n Promise.resolve(downstream).then((value) => {\n if (value instanceof Response) return respond(value)\n res.done()\n resolve(value)\n }, fail)\n }\n\n try {\n ;(mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => void)(\n state.req,\n res,\n connectNext,\n )\n } catch (err) {\n fail(err)\n }\n })\n}\n\n/**\n * Terminal catch-all AFTER all mounted routes: kick's own notFound handler\n * answers unmatched paths (h3 v2's default 404 never fires). rou3 ranks `/**`\n * below every concrete route, so registration time does not matter.\n */\nfunction assembleCatchAll(app: H3AppLike): void {\n const state = app as unknown as Record<symbol, unknown>\n if (state[ASSEMBLED]) return\n state[ASSEMBLED] = true\n app.all('/**', (event: H3EventLike) => {\n const node = event.req.runtime?.node\n const next = (node?.req as (IncomingMessage & { [NEXT]?: () => void }) | undefined)?.[NEXT]\n if (node && next && !state[NO_FALLTHROUGH]) {\n // Hand the request back to the host and tell h3 the node response is\n // taken care of; srvx then leaves the already-written response alone.\n return new Promise((resolve) => {\n const done = () => resolve(H3_HANDLED)\n node.res.once('finish', done)\n node.res.once('close', done)\n next()\n })\n }\n const mw = state[NOTFOUND_MW] as ConnectMiddleware | undefined\n return runConnectTerminal(mw, event)\n })\n}\n\ntype ProxyTrust = (address: string, hop: number) => boolean\n\n/**\n * The `trustProxy` forms h3 can honour without an address-matching library:\n * `true` (every hop), a hop count, or a predicate — Express's semantics for\n * each. Address and subnet lists are not supported here; they are refused\n * with a warning and the socket address is kept, so a misread rule never\n * trusts a header it should not.\n */\nfunction proxyTrust(option: RuntimeAppOptions['trustProxy']): ProxyTrust | undefined {\n if (option === undefined || option === false) return undefined\n if (option === true) return () => true\n if (typeof option === 'number') return (_address, hop) => hop < option\n if (typeof option === 'function') return option\n log.warn(\n 'h3: trustProxy as an address or subnet list is not supported; client IPs ' +\n 'use the socket address. Use a hop count or a function instead.',\n )\n return undefined\n}\n\n/**\n * Express's `proxy-addr` walk: from the socket outward through\n * `x-forwarded-for`, stop at the first address the rule does not trust.\n */\nfunction forwardedClientIp(req: IncomingMessage, trust: ProxyTrust): string | undefined {\n const socket = req.socket?.remoteAddress\n if (!socket) return undefined\n const header = req.headers['x-forwarded-for']\n const forwarded = (Array.isArray(header) ? header.join(',') : (header ?? ''))\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n .toReversed()\n const chain = [socket, ...forwarded]\n for (let hop = 0; hop < chain.length - 1; hop++) {\n if (!trust(chain[hop]!, hop)) return chain[hop]\n }\n return chain[chain.length - 1]\n}\n\n/**\n * A middleware mounted at a path sees `req.url` relative to that path, as on\n * Express — `serve-static` mounted at `/files` must look up\n * `/nested/a.txt`, not `/files/nested/a.txt`. h3 v2 leaves the URL whole, so\n * strip the prefix for the call and restore it when the middleware passes on.\n * `req.originalUrl` keeps the full URL, as Express sets it.\n */\nfunction stripMountPrefix(path: string, mw: ConnectMiddleware): ConnectMiddleware {\n const prefix = path.endsWith('/') ? path.slice(0, -1) : path\n if (prefix === '') return mw\n return ((\n req: IncomingMessage & { originalUrl?: string },\n res: unknown,\n next: (err?: unknown) => void,\n ) => {\n const url = req.url ?? '/'\n const rest = url.startsWith(prefix) ? url.slice(prefix.length) : null\n if (rest === null || (rest !== '' && rest[0] !== '/' && rest[0] !== '?')) {\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n next,\n )\n }\n req.originalUrl ??= url\n req.url = rest.startsWith('/') ? rest : `/${rest}`\n return (mw as (rq: unknown, rs: unknown, n: (err?: unknown) => void) => unknown)(\n req,\n res,\n (err?: unknown) => {\n req.url = url\n next(err)\n },\n )\n }) as unknown as ConnectMiddleware\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * Requires the h3 v2 peer; fails fast with guidance when v1 is installed.\n */\nexport function h3Runtime(options: H3RuntimeOptions = {}): HttpRuntime<H3AppLike> {\n const { H3, toNodeHandler, fromNodeHandler } = loadH3v2(options.h3)\n\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const holder: { app?: H3AppLike } = {}\n const app = new H3({\n // Engine-level errors (middleware throws outside the kick pipeline)\n // dispatch to the kick error handler once setErrorHandler stashes it.\n onError: (error: unknown, event: H3EventLike) => {\n const mw = (holder.app as unknown as Record<symbol, ConnectMiddleware | undefined>)?.[\n ERROR_MW\n ]\n return runConnectTerminal(mw, event, error).then((response) =>\n withConnectHeaders(event, response),\n )\n },\n })\n holder.app = app\n ;(app as unknown as Record<symbol, unknown>)[NO_FALLTHROUGH] =\n options.notFoundFallthrough === false\n ;(app as unknown as Record<symbol, unknown>)[TRUST_PROXY] = proxyTrust(options.trustProxy)\n ;(app as unknown as Record<symbol, unknown>)[BODY_LIMIT] = options.bodyLimit\n return app\n },\n\n nodeHandler(app) {\n assembleCatchAll(app)\n const listener = toNodeHandler(app)\n const trust = (app as unknown as Record<symbol, unknown>)[TRUST_PROXY] as\n | ProxyTrust\n | undefined\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n // Express and Fastify derive `req.ip` from their trust-proxy settings;\n // this is h3's equivalent, off unless the app opts in, because an\n // unverified `x-forwarded-for` is client-controllable. Without it every\n // caller behind a proxy shares the proxy's address (one rate-limit bucket).\n if (trust && !(req as { ip?: string }).ip) {\n const ip = forwardedClientIp(req, trust)\n if (ip) (req as { ip?: string }).ip = ip\n }\n // h3 v2 adds 'close' / 'finish' listeners for every connect middleware\n // and keeps them until the response ends, so an ordinary middleware\n // stack crosses Node's default of 10 and warns about a leak on every\n // request. They go away with the response; no limit is needed.\n res.setMaxListeners(0)\n try {\n const result = listener(req, res) as unknown\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n void (result as Promise<unknown>).catch((err) => next?.(err))\n }\n } catch (err) {\n next?.(err)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const hooks: WebRouteHooks = {\n onError: async (err, req, driver) => {\n const mw = (app as unknown as Record<symbol, ConnectMiddleware | undefined>)[ERROR_MW]\n if (!mw) return\n // Awaited: an async handler answers after its await, and the\n // pipeline falls back to its own answer once this returns.\n try {\n await (mw as (e: unknown, rq: unknown, rs: unknown, n: () => void) => unknown)(\n err,\n req,\n driver,\n NOOP_NEXT,\n )\n } catch (handlerErr) {\n log.error(handlerErr, 'h3: the error handler failed')\n if (!driver.settled) await builtInError(err, req, driver, NOOP_NEXT)\n }\n },\n }\n const run = compileWebRoute(entry, hooks, {\n bodyLimit: (app as unknown as Record<symbol, number | undefined>)[BODY_LIMIT],\n })\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n carry: event.req.runtime?.node?.req ?? FETCH_CONNECT.get(event)?.req,\n }),\n )\n }\n }\n },\n\n useConnect(app, rawMw: ConnectMiddleware, opts?: UseConnectOptions) {\n const path = opts?.path\n // A list mounts each member, as Express does.\n if (Array.isArray(path)) {\n for (const member of path) this.useConnect!(app, rawMw, { path: member })\n return\n }\n const mw = typeof path === 'string' ? stripMountPrefix(path, rawMw) : rawMw\n // Behind a node server (toNodeHandler) the event carries node req/res and\n // h3's own bridge runs the middleware unchanged. Called through\n // `app.fetch(request)` there is none and fromNodeHandler would throw, so\n // the middleware runs against the web driver pair instead.\n const viaNode = fromNodeHandler(mw) as (event: H3EventLike) => unknown\n const handler = (event: H3EventLike, next: () => unknown) =>\n event.req.runtime?.node?.res ? viaNode(event) : runConnectOnFetch(mw, event, next)\n if (path instanceof RegExp) {\n // h3 routes by string pattern only; test the pathname per request.\n // Like Express, a pattern mount leaves `req.url` whole.\n app.use((event: H3EventLike, next: () => unknown) =>\n path.test(event.url.pathname) ? handler(event, next) : next(),\n )\n } else if (typeof path === 'string') {\n // h3 `use` is exact-match; `/**` covers the subtree.\n app.use(joinPath(path, '/**'), handler)\n } else {\n app.use(handler)\n }\n },\n\n serveStatic(app, prefix, dir) {\n // serve-static bridged like any other connect middleware (node only).\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[NOTFOUND_MW] = mw\n // Here as well as in nodeHandler: an app only ever called through\n // `app.fetch` never reaches nodeHandler, and would answer h3's own 404.\n assembleCatchAll(app)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as unknown as Record<symbol, ConnectMiddleware>)[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n // srvx's node adapter writes HTTP/2 compat responses (it branches on\n // httpVersion \"2.0\"), so the node path serves `server.http2` too.\n http2: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types, for the `kick/runtime` typegen\n * augmentation. Mirrors `ExpressRuntimeTypes`.\n */\nexport interface H3RuntimeTypes {\n request: Request\n response: Response\n app: typeof import('h3') extends { H3: new (...args: never[]) => infer A } ? A : unknown\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n\n/** @deprecated Use {@link h3Runtime} — the same runtime. Removed in the next major. */\nexport const h3WebRuntime = h3Runtime\n/** @deprecated Use {@link H3RuntimeOptions}. */\nexport type H3WebRuntimeOptions = H3RuntimeOptions\n/** @deprecated Use {@link H3RuntimeTypes}. */\nexport type H3WebRuntimeTypes = H3RuntimeTypes\n"],"mappings":";;;;;;;;;;0RA+BA,MAAM,aAAe,aAAa,EAC5B,gBAAkB,gBAAgB,EAClC,IAAM,aAAa,WAAW,EAE9B,YAAc,cAAc,YAAY,GAAG,EAE3C,YAAc,OAAO,yBAAyB,EAC9C,SAAW,OAAO,sBAAsB,EACxC,UAAY,OAAO,wBAAwB,EAC3C,cAAwB,CAAC,EAEzB,KAAO,OAAO,mBAAmB,EAEjC,eAAiB,OAAO,4BAA4B,EACpD,YAAc,OAAO,sBAAsB,EAC3C,WAAa,OAAO,qBAAqB,EAEzC,WAAa,OAAO,IAAI,YAAY,EAgC1C,SAAS,eAAe,IAAuC,CAC7D,IAAM,EAAI,IAIV,OAAO,GAAK,EAAE,YAAc,EAAE,QAAU,CAAE,GAAG,EAAE,QAA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ferSchemaOutput } from "@forinda/kickjs-schema";
4
5
  import { z } from "zod";
5
6
  //#region src/config/env.d.ts
@@ -310,4 +311,4 @@ declare function createConfigService<T extends z.ZodObject<any>>(schema: T): {
310
311
  };
311
312
  //#endregion
312
313
  export { baseEnvSchema as a, loadEnv as c, resetEnvCache as d, withEnv as f, Env as i, loadEnvFromSchema as l, TypedConfigService as n, defineEnv as o, createConfigService as r, getEnv as s, ConfigService as t, reloadEnv as u };
313
- //# sourceMappingURL=index-CNHSbZTE.d.mts.map
314
+ //# sourceMappingURL=index-CuiWSnZL.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-CuiWSnZL.d.mts","names":[],"sources":["../src/config/env.ts","../src/config/config-service.ts"],"mappings":";;;;;;;;;;;iBAuOS,sBAAkB,EAAA;;;;;;;;GAQ1B,EAAA,KAAA;;KAGW,gBAAgB,kBAAkB;;;;;;;;;;;cAsBjC,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6DZ,UAAU,UAAU,EAAE,aACpC,SAAS,aAAa,kBAAkB,EAAE,UAAU,KACnD,EAAE,iBAAiB,cAAc,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;iBAgC5B,QAAQ,UAAU,EAAE,gBAAgB,QAAQ,IAAI,EAAE,MAAM;iBACxD,YAAY,0BAA0B,MAAM;;;;;;;;;;;;;;;;;;;;iBAoC5C,OAAO,UAAU,QAAQ,KAAK,IAAI,QAAQ;iBAC1C,OAAO,UAAU,QAC/B,KAAK,GACL,UAAU,YAAY,QAAQ,MAC7B,YAAY,QAAQ;;;;;;;;iBAqCD,QAAQ,GAC5B,WAAW,yBACX,UAAU,IAAI,QAAQ,KACrB,QAAQ;;;;;;;;;;;;;;;;iBA2BK;;;;;;;iBA8BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+CA,kBAAkB,SAChC,QAAQ,0BACS,UAAU,0BAA0B,kBAAkB;;;;;;;;KAqE7D;EACV;EACA;EACA;;;;;;;;;;;KC9lBG,UAAU,qBAAqB,0BAA0B,IAAI,IAAI;;;;;;;KAQjE,YAAY,kBAAkB,KAAK,UAAU,SAAS,QAAQ,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;cA2B3D;;;;;;;;;;;;;;cAcC;;;;;;;;;;EAaZ,IAAI,kBAAkB,SAAS,KAAK,UAAU,KAAK,YAAY,GAAG;;EAElE,IAAI,kBAAkB,SACpB,KAAK,UAAU,IACf,UAAU,YAAY,YAAY,GAAG,MACpC,YAAY,YAAY,GAAG;;;;;;EAU9B,WAAW,0BAA0B,SAAS,uBAAuB,SAAS;;EAK9E;EAMA;EAIA;EAIA;;;;;;UASe,mBAAmB,aAAa;EAC/C,IAAI,yBAAyB,MAAM,KAAK,IAAI,KAAK;EACjD,IAAI,yBAAyB,MAAM,KAAK,GAAG,UAAU,YAAY,KAAK,MAAM,YAAY,KAAK;EAC7F,UAAU,SAAS;EACnB;EACA;EACA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Bc,oBAAoB,UAAU,EAAE,gBAAgB,QAAQ;UAuC5D,mBAAkB,EAAA,MAAA"}
package/dist/index.d.mts CHANGED
@@ -1,29 +1,27 @@
1
1
 
2
- import { a as METADATA, c as Scope, i as Constructor, l as ServiceOptions, n as BuilderOf, o as MaybePromise, r as ClassKind, s as PostConstructStatus, t as Buildable } from "./interfaces-C1hCSoLD.mjs";
3
2
  import { a as tokenName, c as createToken, i as KickJsRegistry, l as isInjectionToken, n as ContainerChangeEvent, o as INJECTION_TOKEN, r as ContainerChangeListener, s as InjectionToken, t as Container } from "./container-Dpvd66Yt.mjs";
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-BxNSz9Qt.mjs";
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-CNHSbZTE.mjs";
6
- import { $ as setInMetaRecord, B as SourcedRegistration, C as RuntimeTypeMap, Ct as reportResponse, D as RequestContext, E as DeepReadonly, F as RunContributorsOptions, G as getMetaRecord, H as getClassMeta, I as runContributors, J as hasClassMeta, K as getMethodMeta, L as BuildPipelineOptions, M as AdapterFactory, N as DefineAdapterOptions, O as RouteShape, P as defineAdapter, Q as setInMetaMap, R as ContributorPipeline, S as RuntimeResponse, St as reportError, T as Ctx, U as getClassMetaOrUndefined, V as buildPipeline, W as getMetaMap, X as pushMethodMeta, Y as pushClassMeta, Z as setClassMeta, _ as RouteMeta, _t as IntrospectionKind, a as KickServer, at as defineModule, b as RuntimeAppOptions, bt as ErrorSource, c as ActiveRuntime, ct as PluginAsyncOptions, d as CtxHandler, dt as KickPlugin, et as setMethodMeta, f as ExpressRuntimeTypes, ft as ModuleRegistry, g as RouteEntry, gt as IntrospectFn, h as MatchedRoute, ht as KickJsPluginRegistry, i as AppAdapterClass, it as ModuleFactory, j as AdapterAsyncOptions, k as SseHandler, l as AdapterHttp, lt as PluginFactory, m as KickRuntimeRegister, mt as KickJsPluginName, n as AdapterMiddleware, nt as defineModules, o as MiddlewarePath, ot as BuildContext, p as HttpRuntime, pt as MutableModuleRegistry, q as getMethodMetaOrUndefined, r as AppAdapter, rt as DefineModuleOptions, s as MiddlewarePhase, st as DefinePluginOptions, t as AdapterContext, tt as ModuleList, u as ConnectMiddleware, ut as definePlugin, v as RouteMethod, vt as IntrospectionSnapshot, w as UseConnectOptions, x as RuntimeCapabilities, xt as ResponseInfo, y as RouteTable, yt as ErrorInfo, z as ContributorSource } from "./adapter-ClEh-Oos.mjs";
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-C8VKewNS.mjs";
4
+ import { a as METADATA, c as Scope, i as Constructor, l as ServiceOptions, n as BuilderOf, o as MaybePromise, r as ClassKind, s as PostConstructStatus, t as Buildable } from "./interfaces-C1hCSoLD.mjs";
5
+ 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-DaQUNXOn.mjs";
6
+ 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-CuiWSnZL.mjs";
7
+ import { $n as ContributorPipeline, $r as BuildContext, $t as ConditionalOutcome, A as SseHandler, An as StartupTimelineSnapshot, Ar as disposeAll, At as PasswordHashOptions, B as ViewAdapter, Bn as AdapterAsyncOptions, Br as NoJobHandlerError, Bt as HANDLER_CHANNEL, C as RuntimeResponse, Cn as reply, Cr as setInMetaRecord, Ct as buildRouteTable, D as DeepReadonly, Dn as StartupCheckError, Dr as KickErrorInit, Dt as VerifyOptions, E as Ctx, En as StartupCheck, Er as KickError, Et as SignerOptions, F as UrlForArgs, Fn as AssetKeyStrategy, Fr as Job, Ft as isClusterPrimary, G as parseTraceparent, Gn as MissingMountDepError, Gr as registerJobContext, Gt as KickCronAdapter, H as TRACEPARENT_HEADER, Hn as DefineAdapterOptions, Hr as ProcessDefinition, Ht as RESPONSE_CHANNEL, I as UrlQuery, In as GroupAssetKeysOptions, Ir as JobContextCarrier, It as KickHandler, J as buildUploadMiddleware, Jn as MountSortItem, Jr as ModuleList, Jt as settleBackgroundWork, K as traceContext, Kn as MountCycleError, Kr as runJob, Kt as RAW_BODY, L as SpaAdapter, Ln as GroupAssetKeysResult, Lr as JobDispatcher, Lt as createHandler, M as ROUTE_URLS, Mn as bindRoutePolicy, Mr as JOB_CONTEXT_FIELD, Mt as verifyPassword, N as RouteName, Nn as offerRoutePolicy, Nr as JOB_DISPATCHER, Nt as defineHttpContextDecorator, O as RequestContext, On as defineCheck, Or as formatKickError, Ot as createSigner, P as UrlBuilder, Pn as AssetKeyPair, Pr as JOB_META, Pt as ClusterOptions, Qn as BuildPipelineOptions, Qr as defineModule, Qt as metricsAdapter, R as SpaAdapterOptions, Rn as groupAssetKeys, Rr as JobHandler, Rt as bootstrap, S as RuntimeCapabilities, Si as onPackage, Sn as isRespondable, Sr as setInMetaMap, T as UseConnectOptions, Tn as CheckMessage, Tr as FormatKickErrorOptions, Tt as Signer, U as TraceContext, Un as defineAdapter, Ur as listJobHandlers, Ut as CRON_WORKER_ENV, V as ViewAdapterOptions, Vn as AdapterFactory, Vr as Process, Vt as HandlerTraceContext, W as TraceContextOptions, Wn as DuplicateMountNameError, Wr as listJobQueues, Wt as CronAdapterOptions, X as upload, Xn as RunContributorsOptions, Xr as DefineModuleOptions, Xt as MetricsOptions, Y as cleanupFiles, Yn as mountSort, Yr as defineModules, Yt as waitUntil, Zn as runContributors, Zr as ModuleFactory, Zt as RequestHistogram, _ as RouteEntry, _i as FailureAdvice, _n as RESPOND, _r as getMethodMetaOrUndefined, _t as buildRoutes, a as KickServer, ai as ModuleRegistry, an as ConfigOrigins, ar as MissingContextValueError, at as KvSessionStore, b as RouteTable, bi as allOf, bn as applyHandlerResult, br as pushMethodMeta, bt as BuildRoutesOptions, c as ActiveRuntime, ci as KickJsPluginRegistry, cn as ServerOptions, cr as CircuitBreakerOptions, ct as rateLimitGuard, d as CtxHandler, di as IntrospectionSnapshot, dn as HealthCheckResult, dr as CircuitOpenError, dt as notFoundHandler, ei as DefinePluginOptions, en as Validators, er as ContributorSource, f as ExpressRuntimeTypes, fi as ErrorInfo, fn as HealthController, fr as getClassMeta, ft as requestScopeMiddleware, g as RouteContributor, gi as reportResponse, gn as InferHandlerResponse, gr as getMethodMeta, gt as requestStore, h as MatchedRoute, hi as reportError, hn as healthModule, hr as getMetaRecord, ht as getRequestValue, i as AppAdapterClass, ii as KickPlugin, in as ConfigDescription, ir as DuplicateContributorError, it as KvRateLimitStoreOptions, jn as RoutePolicyTable, jr as registerDisposable, jt as hashPassword, k as RouteShape, kn as StartupStep, kr as Disposable, kt as PasswordCheck, l as AdapterHttp, li as IntrospectFn, lr as CircuitBreakerState, m as KickRuntimeRegister, mi as ResponseInfo, mn as HealthProbe, mr as getMetaMap, mt as getRequestStore, n as AdapterMiddleware, ni as PluginFactory, nn as Application, nr as buildPipeline, nt as KvLike, o as MiddlewarePath, oi as MutableModuleRegistry, on as MiddlewareEntry, or as MissingContributorError, ot as KvSessionStoreOptions, p as HttpRuntime, pi as ErrorSource, pn as HealthModuleConfig, pr as getClassMetaOrUndefined, pt as RequestStore, q as UploadOptions, qn as MountKind, qr as stampJobContext, qt as PlatformContext, r as AppAdapter, ri as definePlugin, rn as ApplicationOptions, rr as ContributorCycleError, rt as KvRateLimitStore, s as MiddlewarePhase, si as KickJsPluginName, sn as MountedRouteInfo, sr as CircuitBreaker, st as RateLimitGuardOptions, t as AdapterContext, ti as PluginAsyncOptions, tn as evaluatePreconditions, tr as SourcedRegistration, tt as resolveMimeTypes, u as ConnectMiddleware, ui as IntrospectionKind, un as HEALTH_PROBE, ur as CircuitBreakerStats, ut as errorHandler, v as RouteMeta, vi as AdapterCondition, vn as Reply, vr as hasClassMeta, vt as expressRuntime, w as RuntimeTypeMap, wn as CheckContext, wr as setMethodMeta, wt as SignedCheck, x as RuntimeAppOptions, xi as onEnv, xn as isReply, xr as setClassMeta, y as RouteMethod, yi as ConditionOutcome, yn as Respondable, yr as pushClassMeta, yt as materializeRouter, zn as stripExt, zr as JobLike, zt as ERROR_CHANNEL } from "./adapter-C5I5e_-i.mjs";
7
8
  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";
8
- 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-DCA65GZZ.mjs";
9
+ 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-Ftz6m7SO.mjs";
9
10
  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";
10
- import { A as listJobHandlers, C as JobContextCarrier, D as NoJobHandlerError, E as JobLike, M as registerJobContext, N as runJob, O as Process, P as stampJobContext, S as Job, T as JobHandler, _ as settleBackgroundWork, a as KvSessionStoreOptions, b as JOB_DISPATCHER, c as InferHandlerResponse, d as Respondable, f as applyHandlerResult, g as PlatformContext, h as reply, i as KvSessionStore, j as listJobQueues, k as ProcessDefinition, l as RESPOND, m as isRespondable, n as KvRateLimitStore, o as RateLimitGuardOptions, p as isReply, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as Reply, v as waitUntil, w as JobDispatcher, x as JOB_META, y as JOB_CONTEXT_FIELD } from "./kv-stores-Co5k2PYA.mjs";
11
11
  import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider } from "./cache-C0qL0NSD.mjs";
12
12
  import { a as describeError, i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "./logger-xE9qI_FS.mjs";
13
- import { $ as MissingMountDepError, A as defineHttpContextDecorator, B as CRON_WORKER_ENV, C as RequestStore, D as buildRoutes, E as requestStore, F as bootstrap, G as offerRoutePolicy, H as KickCronAdapter, I as ERROR_CHANNEL, J as GroupAssetKeysOptions, K as AssetKeyPair, L as HANDLER_CHANNEL, M as isClusterPrimary, N as KickHandler, O as expressRuntime, P as createHandler, Q as DuplicateMountNameError, R as HandlerTraceContext, S as requestScopeMiddleware, T as getRequestValue, U as RoutePolicyTable, V as CronAdapterOptions, W as bindRoutePolicy, X as groupAssetKeys, Y as GroupAssetKeysResult, Z as stripExt, _ as TRACEPARENT_HEADER, _t as Disposable, at as DuplicateContributorError, b as parseTraceparent, c as HealthController, ct as CircuitBreaker, d as healthModule, dt as CircuitBreakerStats, et as MountCycleError, f as SpaAdapter, ft as CircuitOpenError, g as ViewAdapterOptions, gt as formatKickError, h as ViewAdapter, ht as KickErrorInit, i as ServerOptions, it as ContributorCycleError, j as ClusterOptions, k as materializeRouter, l as HealthModuleConfig, lt as CircuitBreakerOptions, mt as KickError, n as ApplicationOptions, nt as MountSortItem, o as HEALTH_PROBE, ot as MissingContextValueError, p as SpaAdapterOptions, pt as FormatKickErrorOptions, q as AssetKeyStrategy, r as MiddlewareEntry, rt as mountSort, s as HealthCheckResult, st as MissingContributorError, t as Application, tt as MountKind, u as HealthProbe, ut as CircuitBreakerState, v as TraceContext, vt as disposeAll, w as getRequestStore, x as traceContext, y as TraceContextOptions, yt as registerDisposable, z as RESPONSE_CHANNEL } from "./application-oIPzgjfk.mjs";
14
13
  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";
15
14
  import { n as joinPaths, r as normalizePath, t as buildMountPath } from "./path-CMwIHsdv.mjs";
16
15
  import { a as isRef, c as toRefs, i as computed, l as unref, n as Ref, o as reactive, r as WatchOptions, s as ref, t as ComputedRef, u as watch } from "./reactivity-BkMNA0kp.mjs";
17
- import { a as session, i as SessionStore, n as SessionData, r as SessionOptions, t as Session } from "./session-B4hOZj90.mjs";
18
- import { C as SortItem, S as QueryFieldConfig, T as TypedParsedQuery, _ as FilterOperator, a as getQueryParsingDefaults, b as ParsedQuery, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as FilterItem, h as FieldsOf, i as buildQueryParams, l as parseSearchQuery, m as FILTER_OPERATORS, n as QueryRejectReason, o as parseFilters, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as PaginatedResponse, x as QueryBuilderAdapter, y as PaginationParams } from "./index-BfT5KZ-M.mjs";
19
- import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-zWuVIOmd.mjs";
16
+ import { a as validate, i as defaultValidationError, n as ValidationFailure, t as ValidationErrorFactory } from "./validate-CzjCbRUn.mjs";
17
+ import { n as allowedHosts, t as AllowedHostsOptions } from "./allowed-hosts-D6qcuK5I.mjs";
20
18
  import { n as requestId, t as REQUEST_ID_HEADER } from "./request-id-CVzJ1uHD.mjs";
21
- import { n as validate } from "./validate-DMYpUnrf.mjs";
22
- import { n as errorHandler, r as notFoundHandler } from "./error-handler-BB9wAElm.mjs";
23
- import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-C73UkRgc.mjs";
19
+ import { i as csrfGuard, n as CsrfOptions, r as csrf, t as CsrfGuardOptions } from "./csrf-Cy1meSpf.mjs";
24
20
  import { i as requestLogger, n as LoggedResponse, r as RequestLoggerOptions, t as LoggedRequest } from "./request-logger-TgcKRNDD.mjs";
25
- import { n as HelmetOptions, r as helmet } from "./helmet-C2QEU6S-.mjs";
26
- import { n as cors, t as CorsOptions } from "./cors-CsibNTQ6.mjs";
27
- import { n as RateLimitStore, r as rateLimit, t as RateLimitOptions } from "./rate-limit-Bwed3jOV.mjs";
28
- import { i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-CiMtdXWD.mjs";
29
- export { ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, Autowired, type BareRouteFlag, type BaseUploadOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CRON_WORKER_ENV, CacheEvict, type CacheOptions, type CacheProvider, Cacheable, type CallSiteParams, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, ConfigService, type ConnectMiddleware, 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 CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, 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, type ExpressRuntimeTypes, FILTER_OPERATORS, 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 LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, type MatchedRoute, type MaybePromise, MemoryCacheProvider, type MetaValue, 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, MutableModuleRegistry, type NegatedRouteFlagName, NoJobHandlerError, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, Patch, type PlatformContext, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Process, type ProcessDefinition, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, REQUEST_ID_HEADER, RESPOND, RESPONSE_CHANNEL, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type Reply, Repository, RequestContext, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type Respondable, type ResponseInfo, 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, 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 SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UseConnectOptions, type ValidationError, Value, type ValuedRouteFlag, ViewAdapter, type ViewAdapterOptions, type WatchOptions, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, bindRoutePolicy, bootstrap, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createToken, cronScheduleId, csrf, csrfGuard, defaultProblemTitle, defineAdapter, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, defineRouteFlag, describeError, disposeAll, errorHandler, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, getRouteFlags, groupAssetKeys, hasClassMeta, healthModule, helmet, isClusterPrimary, isCronJobEnabled, isInjectionToken, isRef, isReply, isRespondable, joinPaths, listCronJobs, listJobHandlers, listJobQueues, loadEnv, loadEnvFromSchema, matchesFlagTest, materializeRouter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, offerRoutePolicy, 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, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, waitUntil, watch, withBuilder, withEnv };
21
+ import { n as HelmetOptions, r as helmet } from "./helmet-CEOmo516.mjs";
22
+ import { n as breachPadding, t as BreachPaddingOptions } from "./breach-padding-C-Dnq8CS.mjs";
23
+ import { n as cors, t as CorsOptions } from "./cors-2Bwhyhpt.mjs";
24
+ import { i as rateLimit, n as RateLimitOptions, r as RateLimitStore } from "./rate-limit-BgoeahE5.mjs";
25
+ import { a as SessionStore, i as SessionOptions, n as Session, o as session, r as SessionData } from "./session-ChXx7jG5.mjs";
26
+ import { C as SortItem, S as QueryFieldConfig, T as TypedParsedQuery, _ as FilterOperator, a as getQueryParsingDefaults, b as ParsedQuery, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as FilterItem, h as FieldsOf, i as buildQueryParams, l as parseSearchQuery, m as FILTER_OPERATORS, n as QueryRejectReason, o as parseFilters, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as PaginatedResponse, x as QueryBuilderAdapter, y as PaginationParams } from "./index-BfT5KZ-M.mjs";
27
+ export { 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, 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, 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 ConnectMiddleware, 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 CsrfGuardOptions, type CsrfOptions, type Ctx, type CtxHandler, 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, type ExpressRuntimeTypes, 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 LoggedRequest, type LoggedResponse, Logger, type LoggerProvider, METADATA, 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 Reply, 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 UrlBuilder, type UrlForArgs, type UrlQuery, type UseConnectOptions, type ValidationError, type ValidationErrorFactory, type ValidationFailure, type Validators, Value, type ValueOrigin, type ValuedRouteFlag, type VarOrigin, type VerifyOptions, ViewAdapter, type ViewAdapterOptions, type WatchOptions, allOf, allowedHosts, applyHandlerResult, assertFlagTest, assets, baseEnvSchema, bindRoutePolicy, bootstrap, breachPadding, buildMountPath, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createHandler, createLogger, createSigner, createToken, cronScheduleId, csrf, csrfGuard, 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, 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, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, verifyPassword, waitUntil, watch, withBuilder, withEnv };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.1.0
2
+ * @forinda/kickjs v10.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,9 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{a as loadEnvFromSchema,c as withEnv,i as loadEnv,n as defineEnv,o as reloadEnv,r as getEnv,s as resetEnvCache,t as baseEnvSchema}from"./env-BwzF9MkZ.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,d as KickError,f as formatKickError,i as createToken,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-CS9v9UFU.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.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-zvd6AWkE.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{a as HEALTH_PROBE,c as ERROR_CHANNEL,d as DuplicateMountNameError,f as MissingMountDepError,h as defineModule,i as materializeRouter,l as HANDLER_CHANNEL,m as mountSort,n as buildRoutes,o as HealthController,p as MountCycleError,r as expressRuntime,s as healthModule,t as Application,u as RESPONSE_CHANNEL}from"./application-Dv514EeR.mjs";import{t as MutableModuleRegistry}from"./module-registry-Daf_P2oD.mjs";import{i as reportResponse,r as reportError}from"./observers-DZgs48UM.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-BQ4t3TAb.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-CuY2S3bw.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,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-BWuvJsGZ.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-B0JmdBvX.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-7C5TBYn7.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-JvMTp50k.mjs";import{t as runContributors}from"./contributor-runner-DBpRR5dl.mjs";import{t as defineAdapter}from"./define-adapter-BLKlUbSL.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-B3vM6bSf.mjs";import{a as reply,i as isRespondable,l as requestScopeMiddleware,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-BDK9xt7Z.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{c as waitUntil,d as requestStore,l as getRequestStore,s as settleBackgroundWork,t as RequestContext,u as getRequestValue}from"./context-CtL9RxXp.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.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-B_k9qn0R.mjs";import{validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-Dz2INCaa.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-BdyBlBMe.mjs";import{n as csrfGuard,r as randomHex,t as csrf}from"./csrf--1t4qDov.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.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-DsfVy2fk.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-CJiGeOca.mjs";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}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),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{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CRON_WORKER_ENV,CacheEvict,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,REQUEST_ID_HEADER,RESPOND,RESPONSE_CHANNEL,Repository,RequestContext,RoutePolicyTable,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,applyHandlerResult,assertFlagTest,assets,baseEnvSchema,bindRoutePolicy,bootstrap,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createHandler,createLogger,createToken,cronScheduleId,csrf,csrfGuard,defaultProblemTitle,defineAdapter,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,defineRouteFlag,describeError,disposeAll,errorHandler,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,getRouteFlags,groupAssetKeys,hasClassMeta,healthModule,helmet,isClusterPrimary,isCronJobEnabled,isInjectionToken,isRef,isReply,isRespondable,joinPaths,listCronJobs,listJobHandlers,listJobQueues,loadEnv,loadEnvFromSchema,matchesFlagTest,materializeRouter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,offerRoutePolicy,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,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,waitUntil,watch,withBuilder,withEnv};
11
+ import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"./decorate-DkxaoRo5.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,d as KickError,f as formatKickError,i as createToken,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-C2aTj8Cb.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.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-Tc6jhIBi.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{_ as MissingMountDepError,a as HEALTH_PROBE,b as defineModule,c as StartupCheckError,d as onEnv,f as onPackage,g as DuplicateMountNameError,h as RESPONSE_CHANNEL,i as materializeRouter,l as defineCheck,m as HANDLER_CHANNEL,n as buildRoutes,o as HealthController,p as ERROR_CHANNEL,r as expressRuntime,s as healthModule,t as Application,u as allOf,v as MountCycleError,y as mountSort}from"./application-Ch5jT4fj.mjs";import{r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-Cyh7pJCb.mjs";import{i as reportResponse,r as reportError}from"./observers-IGga6yut.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-lLcPhIqq.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-5nFqc1aC.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{buildMountPath,joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,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-BjRpxryx.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-CFXpwc7m.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-6psUheqc.mjs";import{i as buildPipeline,r as buildRouteTable}from"./router-builder-CrWKq6O2.mjs";import{t as runContributors}from"./contributor-runner-Bn-ipSS5.mjs";import{t as defineAdapter}from"./define-adapter-BRJ6lXkV.mjs";import{n as bindRoutePolicy,r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-Pffte5M1.mjs";import{a as reply,d as RAW_BODY,i as isRespondable,l as requestScopeMiddleware,n as applyHandlerResult,r as isReply,t as RESPOND}from"./reply-DjysdCPI.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{a as evaluatePreconditions,c as settleBackgroundWork,d as getRequestValue,f as requestStore,l as waitUntil,t as RequestContext,u as getRequestStore}from"./context-C6iKf9hN.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{a as originsOf,i as loadSettings,n as defineSettings}from"./settings-CFtEAQUs.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-AnbWMCd6.mjs";import{defaultValidationError,validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-DLgt4l7F.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{a as safeEqual,i as randomHex,n as csrfGuard,t as csrf}from"./csrf-C3RRSCMs.mjs";import{a as KickCronAdapter,i as CRON_WORKER_ENV,n as createHandler,r as isClusterPrimary,t as bootstrap}from"./bootstrap-D56HIq1N.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-_wz4DEiw.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-BfImCyaG.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 DEFAULT_BUCKETS=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],label=value=>value.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`
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
+ `)}};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),expected=options.token===void 0?void 0:`Bearer ${options.token}`,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
+
15
+ `)};return{name:`MetricsAdapter`,beforeMount({http}){loop=monitorEventLoopDelay({resolution:20}),loop.enable(),http.route(`GET`,path,ctx=>{let auth=ctx.headers.authorization;if(expected&&(typeof auth!=`string`||!safeEqual(auth,expected))){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 parsed=stored?parse(stored):void 0;if(!parsed)return await derive(password,DUMMY_SALT,costOf(options)),{ok:!1,needsRehash:!1};let key=await derive(password,parsed.salt,parsed.cost).catch(()=>void 0);if(!key)return{ok:!1,needsRehash:!1};let ok=key.length===parsed.key.length&&timingSafeEqual(key,parsed.key),wanted=costOf(options);return{ok,needsRehash:ok&&(parsed.cost.N!==wanted.N||parsed.cost.r!==wanted.r||parsed.cost.p!==wanted.p)}}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{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CRON_WORKER_ENV,CacheEvict,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,bindRoutePolicy,bootstrap,breachPadding,buildMountPath,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createHandler,createLogger,createSigner,createToken,cronScheduleId,csrf,csrfGuard,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,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,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,verifyPassword,waitUntil,watch,withBuilder,withEnv};
12
16
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/core/define-modules.ts","../src/core/circuit-breaker.ts","../src/core/define-plugin.ts","../src/http/define-http-context-decorator.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 * 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","import type { Request, Response, NextFunction } from 'express'\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":";;;;;;;;;;+tJA2BA,IAAa,WAAb,cAAgC,KAAsB,CASpD,MAAM,OAA8B,CAElC,OADA,KAAK,K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AgB,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":[],"sources":["../src/core/define-modules.ts","../src/core/circuit-breaker.ts","../src/core/define-plugin.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 * `/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 { safeEqual } 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\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 const expected = options.token === undefined ? undefined : `Bearer ${options.token}`\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 }: AdapterContext) {\n loop = monitorEventLoopDelay({ resolution: 20 })\n loop.enable()\n http.route('GET', path, (ctx: RequestContext) => {\n const auth = ctx.headers.authorization\n if (expected && (typeof auth !== 'string' || !safeEqual(auth, expected))) {\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// 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.\n */\nexport async function verifyPassword(\n password: string,\n stored: string | null | undefined,\n options: PasswordHashOptions = {},\n): Promise<PasswordCheck> {\n const parsed = stored ? parse(stored) : undefined\n if (!parsed) {\n // At the cost real hashes are checked at (`options`, not the defaults),\n // and one derivation, so \"no such user\" takes as long as \"wrong password\".\n await derive(password, DUMMY_SALT, costOf(options))\n return { ok: false, needsRehash: false }\n }\n // Costs OpenSSL still refuses (N >= 2^(16r) with a small r) fail, not throw.\n const key = await derive(password, parsed.salt, parsed.cost).catch(() => undefined)\n if (!key) return { ok: false, needsRehash: false }\n const ok = key.length === parsed.key.length && timingSafeEqual(key, parsed.key)\n const wanted = costOf(options)\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\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 { Request, Response, NextFunction } from 'express'\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":";;;;;;;;;;0tKA2BA,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,KAAK,EAC5C,OAAO,IACT,CCnCA,IAAa,iBAAb,cAAsC,KAAM,CACd,YAA5B,YAAY,YAAqC,CAC/C,MAAM,oBAAoB,YAAY,6BAA6B,EADzC,KAAA,YAAA,YAE1B,KAAK,K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AGF,CAAE,QAAS,QAAS,aAAc,KAAM,CACjD,CAuBA,SAAgB,aAAa,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"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs v10.2.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ function isProduction(){return typeof process<`u`&&process.env?.NODE_ENV===`production`}export{isProduction as t};
12
+ //# sourceMappingURL=is-production-tnFh6NCj.mjs.map