@forinda/kickjs 10.7.0 → 10.8.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 (189) hide show
  1. package/dist/{adapter-9sPr_5xt.d.mts → adapter-B0Q8PzQ3.d.mts} +13 -7
  2. package/dist/adapter-B0Q8PzQ3.d.mts.map +1 -0
  3. package/dist/{app-module-Cuu-Ma_E.d.mts → app-module-Bk3glnPP.d.mts} +3 -3
  4. package/dist/{app-module-Cuu-Ma_E.d.mts.map → app-module-Bk3glnPP.d.mts.map} +1 -1
  5. package/dist/{application-BZjDmsWb.d.mts → application-BND5VDje.d.mts} +45 -12
  6. package/dist/application-BND5VDje.d.mts.map +1 -0
  7. package/dist/application-CWPS2sst.mjs +14 -0
  8. package/dist/application-CWPS2sst.mjs.map +1 -0
  9. package/dist/{background-BJjLKrnK.mjs → background-D8VpVDrH.mjs} +3 -3
  10. package/dist/{background-BJjLKrnK.mjs.map → background-D8VpVDrH.mjs.map} +1 -1
  11. package/dist/{reply-BVdki3Z4.mjs → body-policy-DAoHt4Cr.mjs} +3 -3
  12. package/dist/body-policy-DAoHt4Cr.mjs.map +1 -0
  13. package/dist/{bootstrap-Dxax6Mcp.mjs → bootstrap-BpRQ1_KV.mjs} +3 -3
  14. package/dist/{bootstrap-Dxax6Mcp.mjs.map → bootstrap-BpRQ1_KV.mjs.map} +1 -1
  15. package/dist/{bounded-counters-_6sdDRhT.mjs → bounded-counters-BMHzTpuZ.mjs} +2 -2
  16. package/dist/{bounded-counters-_6sdDRhT.mjs.map → bounded-counters-BMHzTpuZ.mjs.map} +1 -1
  17. package/dist/{cache-C0qL0NSD.d.mts → cache-CdRHSXow.d.mts} +10 -7
  18. package/dist/cache-CdRHSXow.d.mts.map +1 -0
  19. package/dist/{client-ip-CrO5ktYs.mjs → client-ip-COnqHbaF.mjs} +2 -2
  20. package/dist/{client-ip-CrO5ktYs.mjs.map → client-ip-COnqHbaF.mjs.map} +1 -1
  21. package/dist/config/index.d.mts +1 -1
  22. package/dist/config/index.mjs +2 -2
  23. package/dist/{config-CWKj0Z66.mjs → config-Cq6_Qr4r.mjs} +3 -3
  24. package/dist/config-Cq6_Qr4r.mjs.map +1 -0
  25. package/dist/{context-BlJRkMyq.mjs → context-CX0TLa4H.mjs} +3 -3
  26. package/dist/{context-BlJRkMyq.mjs.map → context-CX0TLa4H.mjs.map} +1 -1
  27. package/dist/{context-errors-ykpXYECS.mjs → context-errors-Chi6ESHh.mjs} +2 -2
  28. package/dist/{context-errors-ykpXYECS.mjs.map → context-errors-Chi6ESHh.mjs.map} +1 -1
  29. package/dist/{contributor-runner-BM-5Wr19.mjs → contributor-runner-Da7v9Whk.mjs} +3 -3
  30. package/dist/{contributor-runner-BM-5Wr19.mjs.map → contributor-runner-Da7v9Whk.mjs.map} +1 -1
  31. package/dist/core/adapter.d.mts +1 -1
  32. package/dist/core/adapter.mjs +1 -1
  33. package/dist/core/app-module.d.mts +1 -1
  34. package/dist/core/app-module.mjs +1 -1
  35. package/dist/core/cache.d.mts +1 -1
  36. package/dist/core/cache.mjs +2 -2
  37. package/dist/core/cache.mjs.map +1 -1
  38. package/dist/core/container.mjs +2 -2
  39. package/dist/core/cron.mjs +2 -2
  40. package/dist/core/decorators.d.mts +1 -1
  41. package/dist/core/decorators.mjs +2 -2
  42. package/dist/core/decorators.mjs.map +1 -1
  43. package/dist/core/errors.mjs +1 -1
  44. package/dist/core/interfaces.mjs +1 -1
  45. package/dist/core/logger.mjs +1 -1
  46. package/dist/core/path.mjs +1 -1
  47. package/dist/core/plugin.d.mts +1 -1
  48. package/dist/core/plugin.mjs +1 -1
  49. package/dist/core/reactivity.d.mts +2 -2
  50. package/dist/core/reactivity.mjs +2 -2
  51. package/dist/core/reactivity.mjs.map +1 -1
  52. package/dist/core-CiwDroJ7.mjs +12 -0
  53. package/dist/{core-DlrlhjF4.mjs.map → core-CiwDroJ7.mjs.map} +1 -1
  54. package/dist/{csrf-ZFOrJZhJ.d.mts → csrf-w5bc-PGs.d.mts} +2 -2
  55. package/dist/{csrf-ZFOrJZhJ.d.mts.map → csrf-w5bc-PGs.d.mts.map} +1 -1
  56. package/dist/{decorate-BHhpOfEF.mjs → decorate-DdzHOAA1.mjs} +4 -4
  57. package/dist/{decorate-BHhpOfEF.mjs.map → decorate-DdzHOAA1.mjs.map} +1 -1
  58. package/dist/{decorators-Dvy0JZ5L.d.mts → decorators-DxNb5mWw.d.mts} +15 -2
  59. package/dist/{decorators-Dvy0JZ5L.d.mts.map → decorators-DxNb5mWw.d.mts.map} +1 -1
  60. package/dist/{define-adapter-CF-DJRq9.mjs → define-adapter-DJnPaqbo.mjs} +2 -2
  61. package/dist/{define-adapter-CF-DJRq9.mjs.map → define-adapter-DJnPaqbo.mjs.map} +1 -1
  62. package/dist/{di-hooks-CCKeiLT-.mjs → di-hooks-rXw3zCor.mjs} +3 -3
  63. package/dist/{di-hooks-CCKeiLT-.mjs.map → di-hooks-rXw3zCor.mjs.map} +1 -1
  64. package/dist/{disposables-bnkL4rG7.mjs → disposables-Cpde_0BE.mjs} +1 -1
  65. package/dist/{error-handler-CH4PPZCK.d.mts → error-handler-C1I8a4wY.d.mts} +2 -2
  66. package/dist/{error-handler-CH4PPZCK.d.mts.map → error-handler-C1I8a4wY.d.mts.map} +1 -1
  67. package/dist/express-fiMFHEPO.mjs +12 -0
  68. package/dist/express-fiMFHEPO.mjs.map +1 -0
  69. package/dist/{express-lazy-D9MZnma8.mjs → express-lazy-DxQzDeza.mjs} +3 -3
  70. package/dist/{express-lazy-D9MZnma8.mjs.map → express-lazy-DxQzDeza.mjs.map} +1 -1
  71. package/dist/handler-D5QS_90y.mjs +12 -0
  72. package/dist/handler-D5QS_90y.mjs.map +1 -0
  73. package/dist/{host-CtpcIKcA.mjs → host-D7vw6t1i.mjs} +2 -2
  74. package/dist/{host-CtpcIKcA.mjs.map → host-D7vw6t1i.mjs.map} +1 -1
  75. package/dist/http/application.d.mts +1 -1
  76. package/dist/http/application.mjs +2 -2
  77. package/dist/http/bootstrap.d.mts +1 -1
  78. package/dist/http/bootstrap.mjs +2 -2
  79. package/dist/http/context.d.mts +2 -2
  80. package/dist/http/context.mjs +2 -2
  81. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  82. package/dist/http/middleware/breach-padding.mjs +1 -1
  83. package/dist/http/middleware/cors.mjs +1 -1
  84. package/dist/http/middleware/csrf.d.mts +1 -1
  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/helmet.mjs +1 -1
  89. package/dist/http/middleware/rate-limit.mjs +2 -2
  90. package/dist/http/middleware/request-id.mjs +1 -1
  91. package/dist/http/middleware/request-logger.mjs +2 -2
  92. package/dist/http/middleware/session.mjs +2 -2
  93. package/dist/http/middleware/spa.d.mts +1 -1
  94. package/dist/http/middleware/spa.mjs +2 -2
  95. package/dist/http/middleware/upload.d.mts +2 -2
  96. package/dist/http/middleware/upload.mjs +2 -2
  97. package/dist/http/middleware/upload.mjs.map +1 -1
  98. package/dist/http/middleware/validate.mjs +1 -1
  99. package/dist/http/middleware/views.d.mts +1 -1
  100. package/dist/http/middleware/views.mjs +2 -2
  101. package/dist/http/query/index.mjs +2 -2
  102. package/dist/http/router-builder.d.mts +1 -1
  103. package/dist/http/router-builder.mjs +2 -2
  104. package/dist/http/runtimes/express.d.mts +2 -2
  105. package/dist/http/runtimes/express.d.mts.map +1 -1
  106. package/dist/http/runtimes/express.mjs +2 -2
  107. package/dist/http/runtimes/fastify.d.mts +4 -2
  108. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  109. package/dist/http/runtimes/fastify.mjs +3 -3
  110. package/dist/http/runtimes/fastify.mjs.map +1 -1
  111. package/dist/http/runtimes/h3-web.mjs +1 -1
  112. package/dist/http/runtimes/h3.d.mts +1 -1
  113. package/dist/http/runtimes/h3.mjs +2 -2
  114. package/dist/{index-B4aOLoId.d.mts → index-CNBYZDto.d.mts} +4 -4
  115. package/dist/{index-B4aOLoId.d.mts.map → index-CNBYZDto.d.mts.map} +1 -1
  116. package/dist/index.d.mts +15 -15
  117. package/dist/index.mjs +3 -3
  118. package/dist/index.mjs.map +1 -1
  119. package/dist/{is-production-BfIKY2Sw.mjs → is-production-C7DJ7c5k.mjs} +2 -2
  120. package/dist/{is-production-BfIKY2Sw.mjs.map → is-production-C7DJ7c5k.mjs.map} +1 -1
  121. package/dist/{jobs-BJfIOWUT.mjs → jobs-Bdqz5n21.mjs} +3 -3
  122. package/dist/{jobs-BJfIOWUT.mjs.map → jobs-Bdqz5n21.mjs.map} +1 -1
  123. package/dist/{kv-stores-BeDHfiyW.mjs → kv-stores-BM5Fcds2.mjs} +3 -3
  124. package/dist/{kv-stores-BeDHfiyW.mjs.map → kv-stores-BM5Fcds2.mjs.map} +1 -1
  125. package/dist/{kv-stores-C1sQs2Rb.d.mts → kv-stores-CISRYh_H.d.mts} +3 -3
  126. package/dist/{kv-stores-C1sQs2Rb.d.mts.map → kv-stores-CISRYh_H.d.mts.map} +1 -1
  127. package/dist/{lazy-serve-static-BUMcYDMn.mjs → lazy-serve-static-D2pf9ODr.mjs} +3 -3
  128. package/dist/{lazy-serve-static-BUMcYDMn.mjs.map → lazy-serve-static-D2pf9ODr.mjs.map} +1 -1
  129. package/dist/{metadata-x0eCJRTl.mjs → metadata-Ck5f9CNm.mjs} +1 -1
  130. package/dist/{observers-Ss6-7Si7.mjs → observers-BV435fEL.mjs} +2 -2
  131. package/dist/{observers-Ss6-7Si7.mjs.map → observers-BV435fEL.mjs.map} +1 -1
  132. package/dist/{precompressed-BBXQUDXp.mjs → precompressed-DPESwDxf.mjs} +2 -2
  133. package/dist/{precompressed-BBXQUDXp.mjs.map → precompressed-DPESwDxf.mjs.map} +1 -1
  134. package/dist/{query-DIS_2QiJ.mjs → query-Bs9mU4bx.mjs} +2 -2
  135. package/dist/{query-DIS_2QiJ.mjs.map → query-Bs9mU4bx.mjs.map} +1 -1
  136. package/dist/{reactivity-BkMNA0kp.d.mts → reactivity-DZrc3Yhu.d.mts} +50 -15
  137. package/dist/reactivity-DZrc3Yhu.d.mts.map +1 -0
  138. package/dist/reply-BmNC0SFg.mjs +12 -0
  139. package/dist/reply-BmNC0SFg.mjs.map +1 -0
  140. package/dist/{request-scope-BTdpkAqv.mjs → request-scope-DFf8XH5R.mjs} +3 -3
  141. package/dist/{request-scope-BTdpkAqv.mjs.map → request-scope-DFf8XH5R.mjs.map} +1 -1
  142. package/dist/{respond-BUWP_L0Y.mjs → respond-DbgwV87J.mjs} +2 -2
  143. package/dist/{respond-BUWP_L0Y.mjs.map → respond-DbgwV87J.mjs.map} +1 -1
  144. package/dist/{rolldown-runtime-Dp0gGuQG.mjs → rolldown-runtime-BIVYCGx6.mjs} +1 -1
  145. package/dist/{route-flag-p89Wzt0D.mjs → route-flag-Dm1NxMbJ.mjs} +3 -3
  146. package/dist/{route-flag-p89Wzt0D.mjs.map → route-flag-Dm1NxMbJ.mjs.map} +1 -1
  147. package/dist/{route-policy-DJMiiTrD.mjs → route-policy-CdBgPlft.mjs} +2 -2
  148. package/dist/{route-policy-DJMiiTrD.mjs.map → route-policy-CdBgPlft.mjs.map} +1 -1
  149. package/dist/{router-builder-dCWA4pdK.mjs → router-builder-BM9t-xGP.mjs} +3 -3
  150. package/dist/router-builder-BM9t-xGP.mjs.map +1 -0
  151. package/dist/{router-builder-BfbEdxew.d.mts → router-builder-CwPowg4s.d.mts} +2 -2
  152. package/dist/{router-builder-BfbEdxew.d.mts.map → router-builder-CwPowg4s.d.mts.map} +1 -1
  153. package/dist/{settings-BnE75hnr.d.mts → settings-BFQisfqG.d.mts} +2 -2
  154. package/dist/{settings-BnE75hnr.d.mts.map → settings-BFQisfqG.d.mts.map} +1 -1
  155. package/dist/{settings-BHYpcj_p.mjs → settings-CPQhWD12.mjs} +3 -3
  156. package/dist/{settings-BHYpcj_p.mjs.map → settings-CPQhWD12.mjs.map} +1 -1
  157. package/dist/token-0ZP--xsp.d.mts +3 -0
  158. package/dist/{token-Cz4YKuL-.mjs → token-tL_r-ZPP.mjs} +2 -2
  159. package/dist/{upload-Jgs9BFC4.d.mts → upload-DDDboa_F.d.mts} +3 -3
  160. package/dist/upload-DDDboa_F.d.mts.map +1 -0
  161. package/dist/upload-config-DCm8AFEW.mjs +12 -0
  162. package/dist/upload-config-DCm8AFEW.mjs.map +1 -0
  163. package/dist/{url-for-CDxa8ik-.mjs → url-for-DAVOWiQ_.mjs} +3 -3
  164. package/dist/{url-for-CDxa8ik-.mjs.map → url-for-DAVOWiQ_.mjs.map} +1 -1
  165. package/dist/{web-crypto-Bijc63tB.mjs → web-crypto-BMaKs6M0.mjs} +2 -2
  166. package/dist/{web-crypto-Bijc63tB.mjs.map → web-crypto-BMaKs6M0.mjs.map} +1 -1
  167. package/dist/web.d.mts +5 -5
  168. package/dist/web.d.mts.map +1 -1
  169. package/dist/web.mjs +2 -2
  170. package/dist/web.mjs.map +1 -1
  171. package/package.json +2 -2
  172. package/dist/adapter-9sPr_5xt.d.mts.map +0 -1
  173. package/dist/application-BSzwuTQ6.mjs +0 -14
  174. package/dist/application-BSzwuTQ6.mjs.map +0 -1
  175. package/dist/application-BZjDmsWb.d.mts.map +0 -1
  176. package/dist/cache-C0qL0NSD.d.mts.map +0 -1
  177. package/dist/config-CWKj0Z66.mjs.map +0 -1
  178. package/dist/core-DlrlhjF4.mjs +0 -12
  179. package/dist/express-4fvuMB5q.mjs +0 -12
  180. package/dist/express-4fvuMB5q.mjs.map +0 -1
  181. package/dist/handler-TzaD8jPN.mjs +0 -12
  182. package/dist/handler-TzaD8jPN.mjs.map +0 -1
  183. package/dist/reactivity-BkMNA0kp.d.mts.map +0 -1
  184. package/dist/reply-BVdki3Z4.mjs.map +0 -1
  185. package/dist/router-builder-dCWA4pdK.mjs.map +0 -1
  186. package/dist/token-D6jfTQLA.d.mts +0 -3
  187. package/dist/upload-Jgs9BFC4.d.mts.map +0 -1
  188. package/dist/upload-config-CkMQ5bW5.mjs +0 -12
  189. package/dist/upload-config-CkMQ5bW5.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.8.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{createToken as n,isInjectionToken as r,INJECTION_TOKEN as t}from"@forinda/kickjs-di";
11
+ export{isInjectionToken as i,createToken as n,ctn as r,INJECTION_TOKEN as t}from"@forinda/kickjs-di";
@@ -1,6 +1,6 @@
1
1
 
2
- import { g as FileUploadConfig, o as BaseUploadOptions } from "./decorators-Dvy0JZ5L.mjs";
3
- import { j as UploadStorageEngine } from "./adapter-9sPr_5xt.mjs";
2
+ import { g as FileUploadConfig, o as BaseUploadOptions } from "./decorators-DxNb5mWw.mjs";
3
+ import { j as UploadStorageEngine } from "./adapter-B0Q8PzQ3.mjs";
4
4
  import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse } from "./connect-BlIamapT.mjs";
5
5
  //#region src/http/middleware/upload.d.ts
6
6
  /**
@@ -52,4 +52,4 @@ declare const upload: {
52
52
  };
53
53
  //#endregion
54
54
  export { upload as i, buildUploadMiddleware as n, cleanupFiles as r, UploadOptions as t };
55
- //# sourceMappingURL=upload-Jgs9BFC4.d.mts.map
55
+ //# sourceMappingURL=upload-DDDboa_F.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-DDDboa_F.d.mts","names":["RequestHandler","Request","Response","NextFunction"],"sources":["../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;;UA+DiB,sBAAsB;;EAErC,UAAU;;EAEV;;iBAkMO,OAAO,mBAAmB,UAAS,gBAAqBA;;;;iBAcxD,MAAM,mBAAmB,mBAAe,UAAS,gBAAqBA;;;;iBAiBtE,KAAK,UAAS,gBAAqBA;;;;;;;;;;;;;;;iBAoB5B,iBAAY,KACbC,gBAAO,KAAOC,iBAAQ,MAAQC;;;;;;iBA+B7B,sBAAsB,QAAQ,mBAAmBH;;cAoBpD"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs v10.8.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{HttpException,HttpStatus}from"./core/errors.mjs";const MIME_MAP={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,bmp:`image/bmp`,ico:`image/x-icon`,tiff:`image/tiff`,tif:`image/tiff`,avif:`image/avif`,pdf:`application/pdf`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,txt:`text/plain`,csv:`text/csv`,zip:`application/zip`,gz:`application/gzip`,tar:`application/x-tar`,rar:`application/vnd.rar`,"7z":`application/x-7z-compressed`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,flac:`audio/flac`,aac:`audio/aac`,mp4:`video/mp4`,webm:`video/webm`,avi:`video/x-msvideo`,mov:`video/quicktime`,mkv:`video/x-matroska`,json:`application/json`,xml:`application/xml`,html:`text/html`};function resolveMimeTypes(types){return types.map(t=>{let lower=t.toLowerCase().replace(/^\./,``);return MIME_MAP[lower]??t})}function buildFileTypeFilter(allowedTypes,customMimeMap){if(!allowedTypes)return()=>!0;if(typeof allowedTypes==`function`)return allowedTypes;let mimeMap=customMimeMap?{...MIME_MAP,...customMimeMap}:MIME_MAP,resolved=allowedTypes.map(t=>mimeMap[t.toLowerCase().replace(/^\./,``)]??t);return mimetype=>resolved.some(type=>type.endsWith(`/*`)?mimetype.startsWith(type.replace(`/*`,`/`)):mimetype===type)}const DEFAULT_MAX_SIZE=5242880;function normalizeOriginalName(name){return(name.normalize(`NFC`).split(/[\\/]/).pop()??``).replace(/[\u0000-\u001f\u007f]/g,``).trim()}function matchingExtension(name,mimetype,customMimeMap){let dot=name.lastIndexOf(`.`);if(dot<=0)return``;let ext=name.slice(dot+1).toLowerCase(),type=mimetype.split(`;`)[0].trim().toLowerCase();return(customMimeMap?.[ext]??MIME_MAP[ext])===type?`.${ext}`:``}function serverFileName(file,options={}){let{rename,customMimeMap}=options;if(!rename){let ext=matchingExtension(file.originalname,file.mimetype,customMimeMap);return`${globalThis.crypto.randomUUID()}${ext}`}let name=rename(file);if(typeof name!=`string`||name===``||name===`.`||name===`..`||name.length>255||/[\\/\0]/.test(name))throw Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`);return name}const UPLOAD_FIELDS_ALLOWANCE=1048576,MAX_UPLOAD_FIELDS=1e3;function uploadLimits(config){let fileSize=config.maxSize??DEFAULT_MAX_SIZE,files=config.mode===`none`?0:config.mode===`single`?1:config.maxCount??10;return{fileSize,files,total:fileSize*files+UPLOAD_FIELDS_ALLOWANCE}}function tooManyFiles(limit){return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`Too many files: at most ${limit}`)}function applyUploadConfig(parts,config){if(config.mode===`none`)return{};let field=config.fieldName??`file`,maxSize=config.maxSize??DEFAULT_MAX_SIZE,typeAllowed=buildFileTypeFilter(config.allowedTypes,config.customMimeMap),files=parts.filter(p=>p.fieldname===field).map(p=>{if(!typeAllowed(p.mimetype,p.filename))throw new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${p.mimetype} is not allowed`);if(p.buffer.length>maxSize)throw new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${p.filename} exceeds the ${maxSize}-byte limit`);let named={fieldname:p.fieldname,originalname:normalizeOriginalName(p.filename),mimetype:p.mimetype,size:p.buffer.length};return{...named,filename:serverFileName(named,config),encoding:`7bit`,buffer:p.buffer}});if(config.mode===`single`)return{file:files[0]};let maxCount=config.maxCount??10;return{files:files.slice(0,maxCount)}}export{normalizeOriginalName as a,tooManyFiles as c,buildFileTypeFilter as i,uploadLimits as l,UPLOAD_FIELDS_ALLOWANCE as n,resolveMimeTypes as o,applyUploadConfig as r,serverFileName as s,MAX_UPLOAD_FIELDS as t};
12
+ //# sourceMappingURL=upload-config-DCm8AFEW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-config-DCm8AFEW.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;;;;;;;;;wDAUA,MAAa,SAAmC,CAE9C,IAAK,aACL,KAAM,aACN,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,gBACL,IAAK,YACL,IAAK,eACL,KAAM,aACN,IAAK,aACL,KAAM,aAEN,IAAK,kBACL,IAAK,qBACL,KAAM,0EACN,IAAK,2BACL,KAAM,oEACN,IAAK,gCACL,KAAM,4EACN,IAAK,0CACL,IAAK,iDACL,IAAK,kDACL,IAAK,kBACL,IAAK,aACL,IAAK,WAEL,IAAK,kBACL,GAAI,mBACJ,IAAK,oBACL,IAAK,sBACL,KAAM,8BAEN,IAAK,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,KAAM,EAAE,OAAO,MACjB,EACA,MAAO,CACL,GAAG,MACH,SAAU,eAAe,MAAO,MAAM,EACtC,SAAU,OACV,OAAQ,EAAE,MACZ,CACF,CAAC,EAED,GAAI,OAAO,OAAS,SAAU,MAAO,CAAE,KAAM,MAAM,EAAG,EACtD,IAAM,SAAW,OAAO,UAAY,GACpC,MAAO,CAAE,MAAO,MAAM,MAAM,EAAG,QAAQ,CAAE,CAC3C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.8.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as createToken}from"./token-Cz4YKuL-.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);let path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
12
- //# sourceMappingURL=url-for-CDxa8ik-.mjs.map
11
+ import{n as createToken}from"./token-tL_r-ZPP.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);let path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
12
+ //# sourceMappingURL=url-for-DAVOWiQ_.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"url-for-CDxa8ik-.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\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 an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N>, query?: UrlQuery]\n : [params: ParamsOf<N>, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | undefined, query)\n }\n\n build(name: string, params?: Record<string, unknown>, query?: UrlQuery): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = params?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":";;;;;;;;;;mDAkEA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA4CxE,SAAgB,aACd,QACgC,CAChC,GAAwB,OAAO,SAAY,WAAvC,QACF,MAAU,UACR,8FAEF,EAEF,GAAI,OAAO,QAAQ,MAAS,UAAY,QAAQ,KAAK,SAAW,EAAG,CACjE,IAAM,IAAM,OAAO,QAAQ,MAAS,SAAW,KAAO,OAAO,QAAQ,KACrE,MAAU,UACR,8DAA8D,IAAI,0IAGpE,CACF,CACA,GAAI,OAAO,QAAQ,OAAU,WAC3B,MAAU,UACR,gBAAgB,QAAQ,KAAK,2DACnB,OAAO,QAAQ,MAAM,6HAEjC,EAGF,IAAM,WACJ,aACA,OACA,YACuB,CACvB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAYlE,OANA,OAAO,eAAe,MAAO,eAAgB,CAC3C,MAAO,aACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACM,KACT,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GAYvC,MAVA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,OAAO,eAAe,QAAS,aAAc,CAC3C,MAAO,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Q,KAAK,EAAI,MAAQ,CAAC,KAAK,EAAG,OAAO,OAAO,IAAK,OAAO,CAAC,CAAC,EAEtF,IAAM,GAAK,OAAO,SAAS,EAC3B,OAAO,GAAK,GAAG,KAAK,GAAG,KAAO,IAChC,CACF"}
1
+ {"version":3,"file":"url-for-DAVOWiQ_.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\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 an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N>, query?: UrlQuery]\n : [params: ParamsOf<N>, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | undefined, query)\n }\n\n build(name: string, params?: Record<string, unknown>, query?: UrlQuery): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = params?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":";;;;;;;;;;mDAkEA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA4CxE,SAAgB,aACd,QACgC,CAChC,GAAwB,OAAO,SAAY,WAAvC,QACF,MAAU,UACR,8FAEF,EAEF,GAAI,OAAO,QAAQ,MAAS,UAAY,QAAQ,KAAK,SAAW,EAAG,CACjE,IAAM,IAAM,OAAO,QAAQ,MAAS,SAAW,KAAO,OAAO,QAAQ,KACrE,MAAU,UACR,8DAA8D,IAAI,0IAGpE,CACF,CACA,GAAI,OAAO,QAAQ,OAAU,WAC3B,MAAU,UACR,gBA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0B,CAC9E,IAAM,QAAU,KAAK,MAAM,IAAI,IAAI,EACnC,GAAI,UAAY,IAAA,GACd,MAAU,MAAM,2BAA2B,KAAK,iCAAiC,EAEnF,IAAM,KAAO,QAAQ,QAAQ,qBAAsB,EAAG,MAAgB,CACpE,IAAM,MAAQ,SAAS,KACvB,GAAI,OAAiC,MAAQ,QAAU,GACrD,MAAU,MAAM,WAAW,KAAK,qBAAqB,IAAI,SAAS,QAAQ,EAAE,EAE9E,OAAO,mBAAmB,OAAO,KAAK,CAAC,CACzC,CAAC,EACD,GAAI,CAAC,MAAO,OAAO,KACnB,IAAM,OAAS,IAAI,gBACnB,IAAK,GAAM,CAAC,IAAK,SAAU,OAAO,QAAQ,KAAK,EAC7C,IAAK,IAAM,KAAK,MAAM,QAAQ,KAAK,EAAI,MAAQ,CAAC,KAAK,EAAG,OAAO,OAAO,IAAK,OAAO,CAAC,CAAC,EAEtF,IAAM,GAAK,OAAO,SAAS,EAC3B,OAAO,GAAK,GAAG,KAAK,GAAG,KAAO,IAChC,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.8.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  function randomHex(bytes){let buf=crypto.getRandomValues(new Uint8Array(bytes));return Array.from(buf,b=>b.toString(16).padStart(2,`0`)).join(``)}function safeEqual(a,b){let length=Math.max(a.length,b.length),diff=a.length^b.length;for(let i=0;i<length;i++)diff|=a.charCodeAt(i)^b.charCodeAt(i);return diff===0}function matchesBearer(header,secret){return typeof header==`string`&&typeof secret==`string`&&secret.length>0&&safeEqual(header,`Bearer ${secret}`)}export{randomHex as n,safeEqual as r,matchesBearer as t};
12
- //# sourceMappingURL=web-crypto-Bijc63tB.mjs.map
12
+ //# sourceMappingURL=web-crypto-BMaKs6M0.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-crypto-Bijc63tB.mjs","names":[],"sources":["../src/core/web-crypto.ts"],"sourcesContent":["/**\n * Web Crypto helpers — portable across node/bun/deno/workers via\n * `globalThis.crypto`. The Web Crypto migration lives here so the request\n * path never imports `node:crypto` (edge-runtime portability).\n */\n\n/** Random hex string — replacement for `randomBytes(n).toString('hex')`. */\nexport function randomHex(bytes: number): string {\n const buf = crypto.getRandomValues(new Uint8Array(bytes))\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Constant-time string comparison for secrets and tokens — the portable\n * counterpart of `timingSafeEqual`. Walks the longer input and folds the\n * length difference in, so it doesn't stop at the first wrong character and\n * a guess's contents don't show in the timing. The loop runs over the longer\n * input, so the time can still reveal the expected value's length.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const length = Math.max(a.length, b.length)\n let diff = a.length ^ b.length\n // Past the end, charCodeAt is NaN, which `^` treats as 0.\n for (let i = 0; i < length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <secret>` header against a\n * shared secret — a cron trigger, a metrics scrape, a webhook. `false` for a\n * missing or non-string header, and for an empty secret (an unset env var\n * must not let `Authorization: Bearer ` through). Pass\n * `ctx.headers.authorization` as is.\n */\nexport function matchesBearer(header: unknown, secret: string): boolean {\n return (\n typeof header === 'string' &&\n typeof secret === 'string' &&\n secret.length > 0 &&\n safeEqual(header, `Bearer ${secret}`)\n )\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,UAAU,MAAuB,CAC/C,IAAM,IAAM,OAAO,gBAAgB,IAAI,WAAW,KAAK,CAAC,EACxD,OAAO,MAAM,KAAK,IAAM,GAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CACxE,CASA,SAAgB,UAAU,EAAW,EAAoB,CACvD,IAAM,OAAS,KAAK,IAAI,EAAE,OAAQ,EAAE,MAAM,EACtC,KAAO,EAAE,OAAS,EAAE,OAExB,IAAK,IAAI,EAAI,EAAG,EAAI,OAAQ,IAAK,MAAQ,EAAE,WAAW,CAAC,EAAI,EAAE,WAAW,CAAC,EACzE,OAAO,OAAS,CAClB,CASA,SAAgB,cAAc,OAAiB,OAAyB,CACtE,OACE,OAAO,QAAW,UAClB,OAAO,QAAW,UAClB,OAAO,OAAS,GAChB,UAAU,OAAQ,UAAU,QAAQ,CAExC"}
1
+ {"version":3,"file":"web-crypto-BMaKs6M0.mjs","names":[],"sources":["../src/core/web-crypto.ts"],"sourcesContent":["/**\n * Web Crypto helpers — portable across node/bun/deno/workers via\n * `globalThis.crypto`. The Web Crypto migration lives here so the request\n * path never imports `node:crypto` (edge-runtime portability).\n */\n\n/** Random hex string — replacement for `randomBytes(n).toString('hex')`. */\nexport function randomHex(bytes: number): string {\n const buf = crypto.getRandomValues(new Uint8Array(bytes))\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Constant-time string comparison for secrets and tokens — the portable\n * counterpart of `timingSafeEqual`. Walks the longer input and folds the\n * length difference in, so it doesn't stop at the first wrong character and\n * a guess's contents don't show in the timing. The loop runs over the longer\n * input, so the time can still reveal the expected value's length.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const length = Math.max(a.length, b.length)\n let diff = a.length ^ b.length\n // Past the end, charCodeAt is NaN, which `^` treats as 0.\n for (let i = 0; i < length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <secret>` header against a\n * shared secret — a cron trigger, a metrics scrape, a webhook. `false` for a\n * missing or non-string header, and for an empty secret (an unset env var\n * must not let `Authorization: Bearer ` through). Pass\n * `ctx.headers.authorization` as is.\n */\nexport function matchesBearer(header: unknown, secret: string): boolean {\n return (\n typeof header === 'string' &&\n typeof secret === 'string' &&\n secret.length > 0 &&\n safeEqual(header, `Bearer ${secret}`)\n )\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,UAAU,MAAuB,CAC/C,IAAM,IAAM,OAAO,gBAAgB,IAAI,WAAW,KAAK,CAAC,EACxD,OAAO,MAAM,KAAK,IAAM,GAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CACxE,CASA,SAAgB,UAAU,EAAW,EAAoB,CACvD,IAAM,OAAS,KAAK,IAAI,EAAE,OAAQ,EAAE,MAAM,EACtC,KAAO,EAAE,OAAS,EAAE,OAExB,IAAK,IAAI,EAAI,EAAG,EAAI,OAAQ,IAAK,MAAQ,EAAE,WAAW,CAAC,EAAI,EAAE,WAAW,CAAC,EACzE,OAAO,OAAS,CAClB,CASA,SAAgB,cAAc,OAAiB,OAAyB,CACtE,OACE,OAAO,QAAW,UAClB,OAAO,QAAW,UAClB,OAAO,OAAS,GAChB,UAAU,OAAQ,UAAU,QAAQ,CAExC"}
package/dist/web.d.mts CHANGED
@@ -1,10 +1,10 @@
1
1
 
2
- import { i as SettingsDeclaration } from "./settings-BnE75hnr.mjs";
3
- import { x as MiddlewareHandler } from "./decorators-Dvy0JZ5L.mjs";
4
- import { O as SseHandler, h as RouteEntry, x as RuntimeResponse } from "./adapter-9sPr_5xt.mjs";
5
- import { m as ContributorRegistrations, r as AppModuleEntry } from "./app-module-Cuu-Ma_E.mjs";
2
+ import { i as SettingsDeclaration } from "./settings-BFQisfqG.mjs";
3
+ import { x as MiddlewareHandler } from "./decorators-DxNb5mWw.mjs";
4
+ import { O as SseHandler, h as RouteEntry, x as RuntimeResponse } from "./adapter-B0Q8PzQ3.mjs";
5
+ import { m as ContributorRegistrations, r as AppModuleEntry } from "./app-module-Bk3glnPP.mjs";
6
6
  import { f as runCronJobs, o as CronRun } from "./cron-BTGytNg-.mjs";
7
- import { E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, S as JOB_CONTEXT_FIELD, a as KvSessionStoreOptions, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, x as reply, y as isReply } from "./kv-stores-C1sQs2Rb.mjs";
7
+ import { E as JobContextCarrier, F as registerJobContext, I as runJob, L as stampJobContext, S as JOB_CONTEXT_FIELD, a as KvSessionStoreOptions, c as matchesBearer, d as waitUntil, f as InferHandlerResponse, g as ReplyOptions, h as ReplyHeaders, i as KvSessionStore, k as JobLike, l as PlatformContext, m as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, x as reply, y as isReply } from "./kv-stores-CISRYh_H.mjs";
8
8
  import { t as ValidationErrorFactory } from "./validate-D4Poe2EE.mjs";
9
9
  //#region src/http/web/driver.d.ts
10
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"web.d.mts","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts","../src/web.ts"],"mappings":";;;;;;;;;;;;;;;;qBAgBa;WACF;WACA;;WAEA,SAAS;EAClB;EACA,QAAQ;EACR,OAAO;EACP;EACA;EACA;GAGC;mBAEgB;EAEjB,YAAY,SAAS,SAAS,KAAK;;EAmBnC,KAAK,eAAe;;EAMpB,GAAG,eAAe;;qBA6BP,6BAA6B;mBAYX;;WAVpB,OAAO,QAAQ;;EAExB;UAEQ;mBACS;UACT;UACA;UACA;EAER,YAA6B,SAAS;EAMtC,OAAO;EAKP,KAAK;EAML,KAAK;EAYL,KAAK;;EAML,UAAU;EAQV,UAAU,cAAc;EAUxB;EAIA,UAAU,oBAAoB,UAAU;EASxC;EAKA,MAAM;EAQN,IAAI;EAUJ,KAAK,eAAe,cAAc;MAM9B;;UAKI;;UAuBA;;;;UClMO;EACf,SAAS;EACT,KAAK;EACL,QAAQ;;;;;;;EAOR;;UAGe;;;;;;;;EAQf,WAAW,cAAc,KAAK,gBAAgB,KAAK,6BAA6B;;wBAwClE,gBACd,OAAO,YACP,QAAQ,eACR;EAAW;KACT,YAAY,uBAAuB,QAAQ;;;iBCA9B;;;;;;;EAOf;;EAEA,SAAS;;EAET;;;;;EAKA;;EAEA,eAAe;;;;;;EAMf,MAAM;;;;;;EAMN,cAAc;;;;;EAKd;;EAEA,WAAW;;EAEX,kBAAkB;;iBAGH;;;;;;EAMf,QAAQ,SAAS,SAAS,WAAW,oBAAoB,QAAQ;;EAEjE;;;;;;;;wBASc,aAAa,SAAS,sBAAsB;;;;;;;;;;;;;;;;;;;;;;wBA0J5C,mBACd,QAAQ,KAAK,uCAAuC;EAEpD,QACE,SAAS,SACT,MAAM,oCACN,MAAM,oBACH,QAAQ;EACb,YACE;IAAS;KACT,MAAM,oCACN,MAAM,oBACH;EACL,QACE,OAAO,YACP,MAAM,oCACN,MAAM,oBACH;;;iBAyCU;WACN;WACA,UAAU;aACR;aACA;IACT;IACA"}
1
+ {"version":3,"file":"web.d.mts","names":[],"sources":["../src/http/web/driver.ts","../src/http/web/handler.ts","../src/web.ts"],"mappings":";;;;;;;;;;;;;;;;qBAgBa;WACF;WACA;;WAEA,SAAS;EAClB;EACA,QAAQ;EACR,OAAO;EACP;EACA;EACA;GAGC;mBAEgB;EAEjB,YAAY,SAAS,SAAS,KAAK;;EAmBnC,KAAK,eAAe;;EAMpB,GAAG,eAAe;;qBA6BP,6BAA6B;mBAYX;;WAVpB,OAAO,QAAQ;;EAExB;UAEQ;mBACS;UACT;UACA;UACA;EAER,YAA6B,SAAS;EAMtC,OAAO;EAKP,KAAK;EAML,KAAK;EAYL,KAAK;;EAML,UAAU;EAQV,UAAU,cAAc;EAUxB;EAIA,UAAU,oBAAoB,UAAU;EASxC;EAKA,MAAM;EAQN,IAAI;EAUJ,KAAK,eAAe,cAAc;MAM9B;;UAKI;;UAuBA;;;;UCzLO;EACf,SAAS;EACT,KAAK;EACL,QAAQ;;;;;;;EAOR;;UAGe;;;;;;;;EAQf,WAAW,cAAc,KAAK,gBAAgB,KAAK,6BAA6B;;wBAwClE,gBACd,OAAO,YACP,QAAQ,eACR;EAAW;KACT,YAAY,uBAAuB,QAAQ;;;iBCT9B;;;;;;;EAOf;;EAEA,SAAS;;EAET;;;;;EAKA;;EAEA,eAAe;;;;;;EAMf,MAAM;;;;;;EAMN,cAAc;;;;;EAKd;;EAEA,WAAW;;EAEX,kBAAkB;;iBAGH;;;;;;EAMf,QAAQ,SAAS,SAAS,WAAW,oBAAoB,QAAQ;;EAEjE;;;;;;;;wBASc,aAAa,SAAS,sBAAsB;;;;;;;;;;;;;;;;;;;;;;wBA0J5C,mBACd,QAAQ,KAAK,uCAAuC;EAEpD,QACE,SAAS,SACT,MAAM,oCACN,MAAM,oBACH,QAAQ;EACb,YACE;IAAS;KACT,MAAM,oCACN,MAAM,oBACH;EACL,QACE,OAAO,YACP,MAAM,oCACN,MAAM,oBACH;;;iBAyCU;WACN;WACA,UAAU;aACR;aACA;IACT;IACA"}
package/dist/web.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.7.0
2
+ * @forinda/kickjs v10.8.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-CDxa8ik-.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-BJfIOWUT.mjs";import{buildMountPath}from"./core/path.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-dCWA4pdK.mjs";import{t as matchesBearer}from"./web-crypto-Bijc63tB.mjs";import{a as reply,l as parseByteSize,r as isReply}from"./reply-BVdki3Z4.mjs";import{i as waitUntil,s as requestStore,t as forwardBackgroundWork}from"./background-BJjLKrnK.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as loadSettings}from"./settings-BHYpcj_p.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-BeDHfiyW.mjs";import{i as WebResponseDriver,r as WebRequestShim,t as compileWebRoute}from"./handler-TzaD8jPN.mjs";function createWebApp(options){let h3mod=options.h3;if(typeof h3mod?.H3!=`function`)throw Error(`@forinda/kickjs/web: pass the h3 v2 module — \`createWebApp({ h3: await import("h3"), ... })\`. The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.`);let container=Container.getInstance(),routeUrls=new RouteUrls;if(container.registerInstance(ROUTE_URLS,routeUrls),options.env){let env=options.env;Container._envResolver=key=>env[key]}Container._requestStoreProvider=()=>requestStore.getStore()??null;let registry=new MutableModuleRegistry;for(let m of options.modules)registry.mount(m);let modules=registry.entries.map(entry=>typeof entry==`function`?new entry:entry),settingsEnv=options.env??(typeof process<`u`?process.env:{});for(let[section,value]of loadSettings([...options.settings??[],...modules.flatMap(mod=>mod.settings?.()??[])],settingsEnv))container.registerInstance(section,value);for(let mod of modules)mod.register?.(container);container.bootstrap();let app=new h3mod.H3,apiPrefix=options.apiPrefix??`/api`,defaultVersion=options.defaultVersion??1,globalMiddleware=options.middlewares??[],bodyLimit=parseByteSize(options.jsonLimit??`1mb`),globalSources=(options.contributors??[]).map(registration=>({source:`global`,registration,label:`createWebApp`})),seenRoutes=/* @__PURE__ */ new Map,mounted=[];for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));_setExternalContributorSources([...moduleSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){if(!route.controller)throw Error(`@forinda/kickjs/web: module route at '${route.path}' has no controller. Express-style \`router\` mounts are not supported on the web entry.`);let version=route.version??defaultVersion,mountPath=buildMountPath(apiPrefix,version,route.path);for(let entry of buildRouteTable(route.controller,{mountFlags:route.flags})){let url=joinPath(mountPath,entry.path),owner=`${route.controller.name??`controller`}.${String(entry.meta.handlerName??`?`)}`;assertRouteUnique(seenRoutes,entry.method,url,owner),mounted.push({method:entry.method,path:url}),globalMiddleware.length>0&&(entry.middlewares=[...globalMiddleware,...entry.middlewares]),entry.validationError=options.validationError,entry.urls=routeUrls,routeUrls.add(owner,url);let run=compileWebRoute(entry,void 0,{bodyLimit});app.on(entry.method,url,event=>run({request:event.req,url:event.url,params:event.context.params??{}}))}}}finally{_setExternalContributorSources([])}}let notFound=notFoundHandler(mounted);return app.all(`/**`,event=>{let driver=new WebResponseDriver(event.req.signal);return notFound(new WebRequestShim(event.req,event.url),driver,()=>{}),driver.ready}),{fetch:async(request,platform)=>{let response=await app.fetch(request);return forwardBackgroundWork(platform),response},h3:app}}function createFetchHandler(build){let app;return{fetch:(request,env={},ctx)=>(app??=createWebApp(build(env)),app.fetch(request,ctx)),scheduled:async(event,env={},ctx)=>{app??=createWebApp(build(env));let run=runCronJobs(Container.getInstance(),{expression:event.cron},`workers`).then(()=>{});ctx?.waitUntil?.(run),await run},queue:async(batch,env={})=>{app??=createWebApp(build(env));let container=Container.getInstance();await Promise.all(batch.messages.map(async message=>{let body=message.body,named=typeof body==`object`&&!!body&&typeof body.name==`string`;try{await runJob(container,batch.queue,{name:named?body.name:``,data:named?body.data:message.body,id:message.id}),message.ack()}catch{message.retry()}}))}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{JOB_CONTEXT_FIELD,KvRateLimitStore,KvSessionStore,WebRequestShim,WebResponseDriver,compileWebRoute,createFetchHandler,createWebApp,isReply,matchesBearer,rateLimitGuard,registerJobContext,reply,runCronJobs,runJob,stampJobContext,waitUntil};
11
+ import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-DAVOWiQ_.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-Bdqz5n21.mjs";import{buildMountPath}from"./core/path.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-BM9t-xGP.mjs";import{t as matchesBearer}from"./web-crypto-BMaKs6M0.mjs";import{o as parseByteSize}from"./body-policy-DAoHt4Cr.mjs";import{i as waitUntil,s as requestStore,t as forwardBackgroundWork}from"./background-D8VpVDrH.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as loadSettings}from"./settings-CPQhWD12.mjs";import{a as reply,r as isReply}from"./reply-BmNC0SFg.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-BM5Fcds2.mjs";import{i as WebResponseDriver,r as WebRequestShim,t as compileWebRoute}from"./handler-D5QS_90y.mjs";function createWebApp(options){let h3mod=options.h3;if(typeof h3mod?.H3!=`function`)throw Error(`@forinda/kickjs/web: pass the h3 v2 module — \`createWebApp({ h3: await import("h3"), ... })\`. The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.`);let container=Container.getInstance(),routeUrls=new RouteUrls;if(container.registerInstance(ROUTE_URLS,routeUrls),options.env){let env=options.env;Container.setEnvResolver(key=>env[key])}Container.setRequestStoreProvider(()=>requestStore.getStore()??null);let registry=new MutableModuleRegistry;for(let m of options.modules)registry.mount(m);let modules=registry.entries.map(entry=>typeof entry==`function`?new entry:entry),settingsEnv=options.env??(typeof process<`u`?process.env:{});for(let[section,value]of loadSettings([...options.settings??[],...modules.flatMap(mod=>mod.settings?.()??[])],settingsEnv))container.registerInstance(section,value);for(let mod of modules)mod.register?.(container);container.bootstrap();let app=new h3mod.H3,apiPrefix=options.apiPrefix??`/api`,defaultVersion=options.defaultVersion??1,globalMiddleware=options.middlewares??[],bodyLimit=parseByteSize(options.jsonLimit??`1mb`),globalSources=(options.contributors??[]).map(registration=>({source:`global`,registration,label:`createWebApp`})),seenRoutes=/* @__PURE__ */ new Map,mounted=[];for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));_setExternalContributorSources([...moduleSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){if(!route.controller)throw Error(`@forinda/kickjs/web: module route at '${route.path}' has no controller. Express-style \`router\` mounts are not supported on the web entry.`);let version=route.version??defaultVersion,mountPath=buildMountPath(apiPrefix,version,route.path);for(let entry of buildRouteTable(route.controller,{mountFlags:route.flags})){let url=joinPath(mountPath,entry.path),owner=`${route.controller.name??`controller`}.${String(entry.meta.handlerName??`?`)}`;assertRouteUnique(seenRoutes,entry.method,url,owner),mounted.push({method:entry.method,path:url}),globalMiddleware.length>0&&(entry.middlewares=[...globalMiddleware,...entry.middlewares]),entry.validationError=options.validationError,entry.urls=routeUrls,routeUrls.add(owner,url);let run=compileWebRoute(entry,void 0,{bodyLimit});app.on(entry.method,url,event=>run({request:event.req,url:event.url,params:event.context.params??{}}))}}}finally{_setExternalContributorSources([])}}let notFound=notFoundHandler(mounted);return app.all(`/**`,event=>{let driver=new WebResponseDriver(event.req.signal);return notFound(new WebRequestShim(event.req,event.url),driver,()=>{}),driver.ready}),{fetch:async(request,platform)=>{let response=await app.fetch(request);return forwardBackgroundWork(platform),response},h3:app}}function createFetchHandler(build){let app;return{fetch:(request,env={},ctx)=>(app??=createWebApp(build(env)),app.fetch(request,ctx)),scheduled:async(event,env={},ctx)=>{app??=createWebApp(build(env));let run=runCronJobs(Container.getInstance(),{expression:event.cron},`workers`).then(()=>{});ctx?.waitUntil?.(run),await run},queue:async(batch,env={})=>{app??=createWebApp(build(env));let container=Container.getInstance();await Promise.all(batch.messages.map(async message=>{let body=message.body,named=typeof body==`object`&&!!body&&typeof body.name==`string`;try{await runJob(container,batch.queue,{name:named?body.name:``,data:named?body.data:message.body,id:message.id}),message.ack()}catch{message.retry()}}))}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{JOB_CONTEXT_FIELD,KvRateLimitStore,KvSessionStore,WebRequestShim,WebResponseDriver,compileWebRoute,createFetchHandler,createWebApp,isReply,matchesBearer,rateLimitGuard,registerJobContext,reply,runCronJobs,runJob,stampJobContext,waitUntil};
12
12
  //# sourceMappingURL=web.mjs.map
package/dist/web.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container._envResolver = (key: string) => env[key]\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container._requestStoreProvider = () => requestStore.getStore() ?? null\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n const mountPath = buildMountPath(apiPrefix, version, route.path)\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n }),\n )\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\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"],"mappings":";;;;;;;;;;qgCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,aAAgB,KAAgB,IAAI,IAChD,CAGA,UAAU,0BAA8B,aAAa,SAAS,GAAK,KAInE,IAAM,SAAW,IAAI,sBACrB,IAAK,IAAM,KAAK,QAAQ,QAAS,SAAS,MAAM,CAAC,EACjD,IAAM,QAAU,SAAS,QAAQ,IAAK,OACpC,OAAO,OAAU,WAAa,IAAK,MAA8B,KACnE,EAGM,YAAe,QAAQ,MAC1B,OAAO,QAAY,IAAc,QAAQ,IAAM,CAAC,GACnD,IAAK,GAAM,CAAC,QAAS,SAAU,aAC7B,CAAC,GAAI,QAAQ,UAAY,CAAC,EAAI,GAAG,QAAQ,QAAS,KAAQ,IAAI,WAAW,GAAK,CAAC,CAAC,CAAC,EACjF,WACF,EACE,UAAU,iBAAiB,QAAS,KAAK,EAE3C,IAAK,IAAM,OAAO,QAAS,IAAI,WAAW,SAAS,EACnD,UAAU,UAAU,EAEpB,IAAM,IAAM,IAAI,MAAM,GAChB,UAAY,QAAQ,WAAa,OACjC,eAAiB,QAA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MAAS,SAChF,GAAI,CACF,MAAM,OAAO,UAAW,MAAM,MAAO,CACnC,KAAM,MAAS,KAAM,KAAkB,GACvC,KAAM,MAAQ,KAAM,KAAO,QAAQ,KACnC,GAAI,QAAQ,EACd,CAAC,EACD,QAAQ,IAAI,CACd,MAAQ,CAEN,QAAQ,MAAM,CAChB,CACF,CAAC,CACH,CACF,CACF,CACF,CAcA,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"}
1
+ {"version":3,"file":"web.mjs","names":[],"sources":["../src/web.ts"],"sourcesContent":["// `@forinda/kickjs/web` — the web-standard fetch entry for edge runtimes\n// (Cloudflare Workers), Bun, and Deno.\n//\n// PURITY CONTRACT: this entry's import graph must stay free of node-only\n// runtime imports — no `node:http`, `node:cluster`, `node:fs`, `node:module`,\n// no `express`, no `Application`/`bootstrap`. The single sanctioned node API\n// is `node:async_hooks` (AsyncLocalStorage — available on Workers with\n// `nodejs_compat`, Deno, and Bun). Enforced by the bundle-graph purity test.\n//\n// ```ts\n// // Cloudflare Workers (wrangler.toml: compatibility_flags = [\"nodejs_compat\"])\n// import { createWebApp } from '@forinda/kickjs/web'\n// import * as h3 from 'h3'\n// import { modules } from './modules'\n//\n// const app = createWebApp({ h3, modules })\n// export default { fetch: (req: Request) => app.fetch(req) }\n//\n// // Bun\n// Bun.serve({ fetch: (req) => app.fetch(req) })\n// ```\n\nimport { Container } from './core/container'\nimport { MutableModuleRegistry } from './core/module-registry'\nimport type { AppModule, AppModuleClass, AppModuleEntry } from './core/app-module'\nimport type { ContributorRegistrations } from './core/context-decorator'\nimport type { MiddlewareHandler } from './core/decorators'\nimport type { SourcedRegistration } from './core/contributor-pipeline'\nimport {\n _setExternalContributorSources,\n assertRouteUnique,\n buildRouteTable,\n} from './http/router-builder'\nimport { requestStore } from './http/request-store'\nimport { forwardBackgroundWork, type PlatformContext } from './http/background'\nimport { runCronJobs } from './core/cron'\nimport { runJob } from './core/jobs'\nimport { compileWebRoute } from './http/web/handler'\nimport { ROUTE_URLS, RouteUrls } from './http/url-for'\nimport { loadSettings, type SettingsDeclaration } from './config/settings'\nimport { DEFAULT_BODY_LIMIT, parseByteSize } from './http/body-policy'\nimport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nimport { notFoundHandler, type MountedRoute } from './http/middleware/error-handler'\nimport type { ValidationErrorFactory } from './http/middleware/validate'\nimport { buildMountPath } from './core/path'\nimport { moduleName } from './core/define-module'\n\nexport { WebRequestShim, WebResponseDriver } from './http/web/driver'\nexport { compileWebRoute } from './http/web/handler'\n// Return-value handler helpers — edge consumers can't import the main barrel.\nexport {\n reply,\n isReply,\n type Reply,\n type ReplyHeaders,\n type ReplyOptions,\n type InferHandlerResponse,\n} from './http/reply'\nexport type { SseHandler } from './http/context'\nexport { waitUntil, type PlatformContext } from './http/background'\nexport { runCronJobs, type CronRun } from './core/cron'\nexport { matchesBearer } from './core/web-crypto'\nexport {\n runJob,\n registerJobContext,\n stampJobContext,\n JOB_CONTEXT_FIELD,\n type JobLike,\n type JobContextCarrier,\n} from './core/jobs'\n// Edge-safe stores + ctx-style rate limiter (zero runtime imports).\nexport {\n KvRateLimitStore,\n KvSessionStore,\n type KvLike,\n type KvRateLimitStoreOptions,\n type KvSessionStoreOptions,\n} from './http/middleware/kv-stores'\nexport { rateLimitGuard, type RateLimitGuardOptions } from './http/middleware/rate-limit-guard'\n\n// Minimal structural surface of h3 v2 used here (kept local so this entry\n// never imports the node-coupled h3 runtime module).\ninterface H3AppLike {\n on(method: string, path: string, handler: (event: H3EventLike) => unknown): unknown\n all(path: string, handler: (event: H3EventLike) => unknown): unknown\n fetch(request: Request): Promise<Response>\n}\ninterface H3EventLike {\n req: Request\n url: URL\n context: { params?: Record<string, string> }\n}\n\nexport interface CreateWebAppOptions {\n /**\n * The h3 v2 module, statically imported by the caller:\n * `import * as h3 from 'h3'`. Passed in (rather than loaded here) because\n * edge bundlers have no `createRequire`, and a static `import 'h3'` inside\n * this entry would force the peer on every consumer of the subpath.\n */\n h3: unknown\n /** App modules — same shapes `bootstrap({ modules })` accepts. */\n modules: AppModuleEntry[]\n /** Route prefix (default '/api') — parity with bootstrap. */\n apiPrefix?: string\n /**\n * Default route version (default 1) — parity with bootstrap. `false` opts\n * out of URL versioning; a module's own `version` still overrides it.\n */\n defaultVersion?: number | false\n /** Global Context Contributors — parity with `bootstrap({ contributors })`. */\n contributors?: ContributorRegistrations\n /**\n * Env values for ConfigService/@Value resolution. On Workers, pass the\n * `env` binding from the fetch handler (see `createFetchHandler`); on\n * Bun/Deno, ambient `process.env` already works and this can be omitted.\n */\n env?: Record<string, string | undefined>\n /**\n * Global `(ctx, next)` middlewares, run before route middlewares on every\n * route — the web-entry counterpart of `bootstrap({ middlewares })`. Only\n * ctx-style handlers are accepted (no connect/express middleware here).\n */\n middlewares?: MiddlewareHandler[]\n /**\n * Largest request body parsed, as bytes or `'1mb'`-style (default `'1mb'`)\n * — parity with `bootstrap({ jsonLimit })`. A larger body answers 413.\n */\n jsonLimit?: string | number\n /** App-wide settings sections — parity with `bootstrap({ settings })`. */\n settings?: SettingsDeclaration[]\n /** What a failed route validation throws — parity with `bootstrap({ validationError })`. */\n validationError?: ValidationErrorFactory\n}\n\nexport interface WebApp {\n /**\n * Web-standard entry: `Request` in, `Response` out. Pass the platform\n * context (Workers `ctx`, Netlify `context`) so work handed to\n * `ctx.waitUntil()` finishes after the response.\n */\n fetch: (request: Request, platform?: PlatformContext) => Promise<Response>\n /** The underlying h3 v2 app, for advanced composition. */\n h3: unknown\n}\n\n/**\n * Build a KickJS app as a web-standard fetch handler — no node http server,\n * no Application/bootstrap. Module registration, DI, and the contributor\n * pipeline behave exactly like `bootstrap()`; routes are compiled once here\n * and served through h3 v2's router.\n */\nexport function createWebApp(options: CreateWebAppOptions): WebApp {\n const h3mod = options.h3 as { H3?: new () => H3AppLike }\n if (typeof h3mod?.H3 !== 'function') {\n throw new Error(\n '@forinda/kickjs/web: pass the h3 v2 module — `createWebApp({ h3: await import(\"h3\"), ... })`. ' +\n \"The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.\",\n )\n }\n\n const container = Container.getInstance()\n // Route names for ctx.urlFor() / the ROUTE_URLS token — bound before modules\n // register so their services can inject it.\n const routeUrls = new RouteUrls()\n container.registerInstance(ROUTE_URLS, routeUrls)\n // Wire ConfigService/@Value env resolution when the platform has no\n // ambient process.env (Workers). Latest-wins like loadEnv().\n if (options.env) {\n const env = options.env\n Container.setEnvResolver((key: string) => env[key])\n }\n\n // Request-scope provider — same wiring Application.setup() performs.\n Container.setRequestStoreProvider(() => requestStore.getStore() ?? null)\n\n // Module mounting — mirrors Application.setup() steps 1:1 for the module\n // path (plugins/adapters are out of scope for the edge entry at launch).\n const registry = new MutableModuleRegistry()\n for (const m of options.modules) registry.mount(m)\n const modules = registry.entries.map((entry) =>\n typeof entry === 'function' ? new (entry as AppModuleClass)() : (entry as AppModule),\n )\n // Declared settings sections — app-wide and mounted modules' — from the\n // platform env (Workers bindings) when given, bound before modules register.\n const settingsEnv = (options.env ??\n (typeof process !== 'undefined' ? process.env : {})) as NodeJS.ProcessEnv\n for (const [section, value] of loadSettings(\n [...(options.settings ?? []), ...modules.flatMap((mod) => mod.settings?.() ?? [])],\n settingsEnv,\n )) {\n container.registerInstance(section, value)\n }\n for (const mod of modules) mod.register?.(container)\n container.bootstrap()\n\n const app = new h3mod.H3()\n const apiPrefix = options.apiPrefix ?? '/api'\n const defaultVersion = options.defaultVersion ?? 1\n const globalMiddleware = options.middlewares ?? []\n const bodyLimit = parseByteSize(options.jsonLimit ?? DEFAULT_BODY_LIMIT)\n\n const globalSources: SourcedRegistration[] = (options.contributors ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'global',\n registration: registration as SourcedRegistration['registration'],\n label: 'createWebApp',\n }),\n )\n\n // Duplicate-route guard (KICK006) — same boot-time check as the node path.\n const seenRoutes = new Map<string, string>()\n // For the catch-all: a known path with the wrong verb is a 405, not a 404.\n const mounted: MountedRoute[] = []\n\n for (const mod of modules) {\n const moduleLabel = moduleName(mod)\n const moduleSources: SourcedRegistration[] = (mod.contributors?.() ?? []).map(\n (registration): SourcedRegistration => ({\n source: 'module',\n registration,\n label: moduleLabel,\n }),\n )\n\n _setExternalContributorSources([...moduleSources, ...globalSources])\n try {\n const result = mod.routes()\n if (!result) continue\n const routeSets = Array.isArray(result) ? result : [result]\n for (const route of routeSets) {\n if (!route.controller) {\n throw new Error(\n `@forinda/kickjs/web: module route at '${route.path}' has no controller. ` +\n 'Express-style `router` mounts are not supported on the web entry.',\n )\n }\n const version = route.version ?? defaultVersion\n const mountPath = buildMountPath(apiPrefix, version, route.path)\n for (const entry of buildRouteTable(route.controller, { mountFlags: route.flags })) {\n const url = joinPath(mountPath, entry.path)\n // Per-handler owner so intra-controller duplicates name both methods.\n const owner = `${route.controller.name ?? 'controller'}.${String(entry.meta.handlerName ?? '?')}`\n assertRouteUnique(seenRoutes, entry.method, url, owner)\n mounted.push({ method: entry.method, path: url })\n if (globalMiddleware.length > 0) {\n entry.middlewares = [...globalMiddleware, ...entry.middlewares]\n }\n entry.validationError = options.validationError\n entry.urls = routeUrls\n routeUrls.add(owner, url)\n const run = compileWebRoute(entry, undefined, { bodyLimit })\n app.on(entry.method, url, (event: H3EventLike) =>\n run({\n request: event.req,\n url: event.url,\n params: event.context.params ?? {},\n }),\n )\n }\n }\n } finally {\n _setExternalContributorSources([])\n }\n }\n\n // Anything no route answered: the same 404 / 405 problem details as the\n // node engines, instead of h3's own 404 body.\n const notFound = notFoundHandler(mounted)\n app.all('/**', (event: H3EventLike) => {\n const driver = new WebResponseDriver(event.req.signal)\n notFound(new WebRequestShim(event.req, event.url), driver, () => {})\n return driver.ready\n })\n\n return {\n fetch: async (request: Request, platform?: PlatformContext) => {\n const response = await app.fetch(request)\n forwardBackgroundWork(platform)\n return response\n },\n h3: app,\n }\n}\n\n/**\n * Cloudflare Workers convenience: lazily build the app on the first request\n * so the Workers `env` binding can seed config before any module resolves.\n *\n * The Workers execution context (third argument) is forwarded, so work\n * handed to `ctx.waitUntil()` keeps running after the response.\n *\n * `scheduled` runs the `@Cron` jobs whose expression equals the trigger's\n * `event.cron` — list the same expressions under `[triggers] crons` in\n * wrangler.toml.\n *\n * `queue` consumes Cloudflare Queues: each message goes to the `@Job` class\n * for the batch's queue via `runJob`, and is acked when its handler\n * succeeds or retried when it throws. A message body of `{ name, data }`\n * picks the `@Process(name)` method; any other body goes to the queue's\n * catch-all `@Process()` as `data`.\n *\n * ```ts\n * export default createFetchHandler((env) => ({ h3, modules, env }))\n * ```\n */\nexport function createFetchHandler(\n build: (env: Record<string, string | undefined>) => CreateWebAppOptions,\n): {\n fetch: (\n request: Request,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<Response>\n scheduled: (\n event: { cron: string },\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n queue: (\n batch: QueueBatch,\n env?: Record<string, string | undefined>,\n ctx?: PlatformContext,\n ) => Promise<void>\n} {\n let app: WebApp | undefined\n return {\n fetch: (request, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n return app.fetch(request, ctx)\n },\n scheduled: async (event, env = {}, ctx) => {\n app ??= createWebApp(build(env))\n const run = runCronJobs(Container.getInstance(), { expression: event.cron }, 'workers').then(\n () => {},\n )\n ctx?.waitUntil?.(run)\n await run\n },\n queue: async (batch, env = {}) => {\n app ??= createWebApp(build(env))\n const container = Container.getInstance()\n await Promise.all(\n batch.messages.map(async (message) => {\n const body = message.body as { name?: unknown; data?: unknown } | null\n const named = body !== null && typeof body === 'object' && typeof body.name === 'string'\n try {\n await runJob(container, batch.queue, {\n name: named ? (body!.name as string) : '',\n data: named ? body!.data : message.body,\n id: message.id,\n })\n message.ack()\n } catch {\n // Reported by runJob; Cloudflare redelivers per the queue's retry settings.\n message.retry()\n }\n }),\n )\n },\n }\n}\n\n/** The part of a Cloudflare Queues `MessageBatch` the consumer uses. */\nexport interface QueueBatch {\n readonly queue: string\n readonly messages: ReadonlyArray<{\n readonly id: string\n readonly body: unknown\n ack(): void\n retry(): void\n }>\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"],"mappings":";;;;;;;;;;6iCAwJA,SAAgB,aAAa,QAAsC,CACjE,IAAM,MAAQ,QAAQ,GACtB,GAAI,OAAO,OAAO,IAAO,WACvB,MAAU,MACR,0KAEF,EAGF,IAAM,UAAY,UAAU,YAAY,EAGlC,UAAY,IAAI,UAItB,GAHA,UAAU,iBAAiB,WAAY,SAAS,EAG5C,QAAQ,IAAK,CACf,IAAM,IAAM,QAAQ,IACpB,UAAU,eAAgB,KAAgB,IAAI,IAAI,CACpD,CAGA,UAAU,4BAA8B,aAAa,SAAS,GAAK,IAAI,EAIvE,IAAM,SAAW,IAAI,sBACrB,IAAK,IAAM,KAAK,QAAQ,QAAS,SAAS,MAAM,CAAC,EACjD,IAAM,QAAU,SAAS,QAAQ,IAAK,OACpC,OAAO,OAAU,WAAa,IAAK,MAA8B,KACnE,EAGM,YAAe,QAAQ,MAC1B,OAAO,QAAY,IAAc,QAAQ,IAAM,CAAC,GACnD,IAAK,GAAM,CAAC,QAAS,SAAU,aAC7B,CAAC,GAAI,QAAQ,UAAY,CAAC,EAAI,GAAG,QAAQ,QAAS,KAAQ,IAAI,WAAW,GAAK,CAAC,CAAC,CAAC,EACjF,WACF,EACE,UAAU,iBAAiB,QAAS,KAAK,EAE3C,IAAK,IAAM,OAAO,QAAS,IAAI,WAAW,SAAS,EACnD,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AO,UAAY,CACpC,IAAM,KAAO,QAAQ,KACf,MAAyB,OAAO,MAAS,YAAjC,MAA6C,OAAO,KAAK,MAAS,SAChF,GAAI,CACF,MAAM,OAAO,UAAW,MAAM,MAAO,CACnC,KAAM,MAAS,KAAM,KAAkB,GACvC,KAAM,MAAQ,KAAM,KAAO,QAAQ,KACnC,GAAI,QAAQ,EACd,CAAC,EACD,QAAQ,IAAI,CACd,MAAQ,CAEN,QAAQ,MAAM,CAChB,CACF,CAAC,CACH,CACF,CACF,CACF,CAcA,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs",
3
- "version": "10.7.0",
3
+ "version": "10.8.0",
4
4
  "description": "Modern type-safe backend framework, powered by Vite. Built for developer experience, pluggable as you need — runs on Express, Fastify or h3.",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -128,7 +128,7 @@
128
128
  ],
129
129
  "dependencies": {
130
130
  "reflect-metadata": "^0.2.2",
131
- "@forinda/kickjs-di": "0.2.0",
131
+ "@forinda/kickjs-di": "0.3.0",
132
132
  "@forinda/kickjs-schema": "^0.2.4"
133
133
  },
134
134
  "peerDependencies": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"adapter-9sPr_5xt.d.mts","names":["Container","Container","_0","NextFunction","Request","RequestHandler","ErrorRequestHandler","Container"],"sources":["../src/core/adapter-conditions.ts","../src/core/failure-analysis.ts","../src/core/observers.ts","../src/core/introspect.ts","../src/core/augmentation.ts","../src/core/module-registry.ts","../src/core/plugin.ts","../src/core/define-plugin.ts","../src/core/define-module.ts","../src/core/define-modules.ts","../src/core/contributor-pipeline.ts","../src/core/contributor-runner.ts","../src/core/define-adapter.ts","../src/http/url-for.ts","../src/http/conditional.ts","../src/http/middleware/upload-config.ts","../src/http/context.ts","../src/http/runtime.ts","../src/core/adapter.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;KAcY;;UAGK;EACf;EACA;;EAEA;;;;;;;;iBASc,MAAM,cAAc,iBAAiB;;;;;;;iBAiBrC,UAAU,eAAe;;iBAqBzB,SAAS,YAAY,qBAAqB;;;;;;;;;;UC5DzC;EACf;EACA;EACA;;;;;KCSU;UAQK;EACf,QAAQ;EACR;EACA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;UAGK;EACf;EACA;;EAEA;EACA;EACA;EACA;;;;;;;;iBAiFc,YAAY,gBAAgB,MAAM;;iBAKlC,eAAe,MAAM;;;;;;;;;;;;;;;;;;;;;UCrHpB;;;;;;;;;;EAUf;;EAEA;;EAEA,MAAM;;EAEN;;;;;EAKA,QAAQ;;EAER;IAAW;IAA6B;;;;;;EAKxC,UAAU;;EAEV;;;;;;;;KASU;;;;;;KAOA,qBAAqB,wBAAwB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;UC3ChD;;;;;;;;;KAUL,yBAAyB,oDAE3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCAO;;;;;;;;;;;EAWf,MAAM,QAAQ;;;;;;;;;;;cAYH,iCAAiC;WACnC,SAAS;EAElB,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCGC;;EAEf;;;;;;;;;;;;;;;;;;;EAoBA,qBAAqB;;;;;EAMrB,UAAU,WAAWA;;;;;;;;;;;;;;EAerB,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;EA2BZ,OAAO,UAAU;;;;;EAMjB,aAAa;;;;;;;;;EAUb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCA,iBAAiB;;EAGjB,sBAAsB;;;;;EAMtB,SAAS,WAAWA,qBAA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,gBAAgB,QAAQ;;EAE9B,YAAY,gBAAgB;;EAE5B,IAAI,IAAI,mBAAmB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;KChYxB;;;;;;;;;;;;;KAcA,0BAA0B,SAAS,uBAAuB;;UAGrD;;;;;;EAMf,SAASC,iBAAiBC;;EAE1B,QAAQ;;;;;;EAMR,OAAO;;;;;;;;;;;;;;;;;;;;;KAsBG,aAAa,KAAK,SAAS,MAAM,SAAS,MAAM;UAE3C;;;;;;EAMf,MAAM;;;;;;;EAON,KAAK;;;;;;;;;;;;EAYL,MAAM,SAAS,UAAU,QAAQ;;EAEjC,WAAWC;;;;;;;EAOX,SAAS;;;;;;;;EAQT;IAAe,MAAM;IAAa,SAAS,KAAK,SAAS,MAAM;;;EAE/D;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAkCe;;;;;;EAMf;;;;;;;;;;;;;;;;;;;;EAqBA,qBAAqB;;;;;;;;;;;;EAarB,OAAO;;;;;;;;;;;;;;EAeP,gBAAgB,eAAe;;;;;EAM/B,eAAe;;;;;;;;;;EAWf,iBAAiB;;;;;EAMjB,sBAAsB;;;;;EAMtB,aAAa,KAAK,wBAAwB;;;;;EAM1C,cAAc,iBAAiB,aAAa;;;;;;;;;;;;;EAc5C,aAAa,KAAK,wBAAwB;;;;;;;;;;;;;;;EAgB1C,YAAY,KAAK,wBAAwB;;;;;EAMzC,kBAAkB;IAAU;IAAc;;;;;;;;;EAS1C,SAAS,gBAAgB,MAAM,mBAAmB;;;;;EAKlD,YAAY,MAAM,sBAAsB;;;;;;;;;;;;;;;;EAiBxC,aAAa;;;;;;;;;;;;;EAcb,eAAe,wBAAwB,QAAQ;;;;;;;;;;;EAY/C;;;KAIU,4BAA4B"}
@@ -1,14 +0,0 @@
1
- /**
2
- * @forinda/kickjs v10.7.0
3
- *
4
- * Copyright (c) Felix Orinda
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import{a as tlsCredentialsError,i as moduleRouteMissingControllerError,n as http2RequiresTlsError,r as http2UnsupportedRuntimeError}from"./di-hooks-CCKeiLT-.mjs";import{METADATA}from"./core/interfaces.mjs";import{Logger,createLogger}from"./core/logger.mjs";import{Container,tokenName}from"./core/container.mjs";import{n as createToken}from"./token-Cz4YKuL-.mjs";import{t as getClassMeta}from"./metadata-x0eCJRTl.mjs";import{Controller,Get}from"./core/decorators.mjs";import{a as moduleName,i as defineModule,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-CDxa8ik-.mjs";import{a as setObserverPublisher,i as reportResponse,n as releaseObservers,o as setObservers,r as reportError,t as hasResponseObservers}from"./observers-Ss6-7Si7.mjs";import{runCronJobs}from"./core/cron.mjs";import{i as runDisposables,n as drainDisposables,r as registerDisposable,t as disposeAll}from"./disposables-bnkL4rG7.mjs";import{HttpException}from"./core/errors.mjs";import{buildMountPath,joinPaths}from"./core/path.mjs";import{computed,ref}from"./core/reactivity.mjs";import{t as ROUTE_SLOT}from"./route-flag-p89Wzt0D.mjs";import"./core-DlrlhjF4.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-dCWA4pdK.mjs";import{t as isProduction}from"./is-production-BfIKY2Sw.mjs";import{r as offerRoutePolicy,t as RoutePolicyTable}from"./route-policy-DJMiiTrD.mjs";import{t as matchesBearer}from"./web-crypto-Bijc63tB.mjs";import{a as reply,l as parseByteSize}from"./reply-BVdki3Z4.mjs";import{requestId}from"./http/middleware/request-id.mjs";import{n as pendingBackgroundWork,r as settleBackgroundWork,s as requestStore}from"./background-BJjLKrnK.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{allowedHosts}from"./http/middleware/allowed-hosts.mjs";import{i as requestScopeMiddleware,r as isRequestScopeMiddleware}from"./request-scope-BTdpkAqv.mjs";import{a as originsOf,i as loadSettings}from"./settings-BHYpcj_p.mjs";import{i as describeEnvSchema,t as __decorate}from"./decorate-BHhpOfEF.mjs";import{i as expressRuntime,o as settleExpressLoad,r as expressBodyParsers}from"./express-lazy-D9MZnma8.mjs";import{createRequire}from"node:module";import{join}from"node:path";import http from"node:http";import https from"node:https";import http2 from"node:http2";import tls from"node:tls";import diagnostics from"node:diagnostics_channel";import{randomBytes}from"node:crypto";var DuplicateMountNameError=class extends Error{kind;mountName;constructor(kind,mountName){super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`),this.name=`DuplicateMountNameError`,this.kind=kind,this.mountName=mountName}},MissingMountDepError=class extends Error{kind;missing;dependent;constructor(kind,missing,dependent){super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`),this.name=`MissingMountDepError`,this.kind=kind,this.missing=missing,this.dependent=dependent}},MountCycleError=class extends Error{kind;cycle;constructor(kind,cycle){super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(` → `)}`),this.name=`MountCycleError`,this.kind=kind,this.cycle=Object.freeze([...cycle])}};function mountSort(items,kind){let byName=/* @__PURE__ */ new Map;for(let item of items){if(byName.has(item.name))throw new DuplicateMountNameError(kind,item.name);byName.set(item.name,item)}let indegree=/* @__PURE__ */ new Map,dependents=/* @__PURE__ */ new Map;for(let item of items)indegree.set(item.name,item.dependsOn?.length??0);for(let item of items)for(let dep of item.dependsOn??[]){if(!byName.has(dep))throw new MissingMountDepError(kind,dep,item.name);let list=dependents.get(dep)??[];list.push(item),dependents.set(dep,list)}let queue=[];for(let item of items)indegree.get(item.name)===0&&queue.push(item);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.name)??[]){let next=(indegree.get(dependent.name)??0)-1;indegree.set(dependent.name,next),next===0&&queue.push(dependent)}}if(sorted.length!==items.length)throw new MountCycleError(kind,reconstructCycle(items.filter(it=>(indegree.get(it.name)??0)>0),byName));return sorted}function reconstructCycle(residual,byName){let residualNames=new Set(residual.map(r=>r.name)),start=residual[0].name,path=[start],seen=/* @__PURE__ */ new Set([start]),cursor=start;for(;;){let nextDep=byName.get(cursor).dependsOn?.find(d=>residualNames.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}const HANDLER_CHANNEL=`kickjs:handler`,ERROR_CHANNEL=`kickjs:error`,RESPONSE_CHANNEL=`kickjs:response`,handlerChannel=diagnostics.tracingChannel(HANDLER_CHANNEL),errorChannel=diagnostics.channel(ERROR_CHANNEL),responseChannel=diagnostics.channel(RESPONSE_CHANNEL);function installChannelPublisher(){setObserverPublisher({name:`diagnostics_channel`,onError(error,info){errorChannel.hasSubscribers&&errorChannel.publish({error,...info})},onResponse(info){responseChannel.hasSubscribers&&responseChannel.publish(info)}},()=>responseChannel.hasSubscribers)}function traceHandler(handler,meta){return ctx=>handlerChannel.hasSubscribers?handlerChannel.tracePromise(async()=>handler(ctx),{...meta,requestId:ctx.requestId,ctx}):handler(ctx)}const round=ms=>Math.round(ms*10)/10;var StartupTimeline=class{began=performance.now();last=this.began;steps=[];completedAt;mark(name){let now=performance.now();this.steps.push({name,ms:round(now-this.last)}),this.last=now}async time(name,run){let started=performance.now(),before=this.last;try{return await run()}finally{let now=performance.now();this.steps.push({name,ms:round(now-started)}),this.last=now-(started-before)}}complete(){this.completedAt??=performance.now()}snapshot(){let end=this.completedAt??performance.now();return{totalMs:round(end-this.began),steps:[...this.steps]}}slowest(count){return this.steps.toSorted((a,b)=>b.ms-a.ms).slice(0,count)}};function onEnv(name,value){return()=>{let actual=process.env[name];return value===void 0?actual?!0:`${name} is not set`:actual===value?!0:actual===void 0?`${name} is not set`:`${name} is not '${value}'`}}function onPackage(name){return()=>{let bases=[process.argv[1],join(process.cwd(),`package.json`)].filter(base=>typeof base==`string`&&base.length>0);for(let base of bases)try{return createRequire(base).resolve(name),!0}catch{}return`package '${name}' is not installed`}}function allOf(...conditions){return()=>{for(let condition of conditions){let result=condition();if(result!==!0)return result}return!0}}function evaluateCondition(condition,onError){try{let result=condition();return result===!0?!0:typeof result==`string`&&result.length>0?result:`its condition returned false`}catch(err){return onError?.(err),`its condition threw (see the server log)`}}function findCode(err,codes,depth=0){if(!err||typeof err!=`object`||depth>5)return;let e=err;if(typeof e.code==`string`&&codes.includes(e.code))return e;for(let inner of[e.cause,...Array.isArray(e.errors)?e.errors:[]]){let found=findCode(inner,codes,depth+1);if(found)return found}}function findMessage(err,pattern,depth=0){if(!err||typeof err!=`object`||depth>5)return!1;let e=err;return typeof e.message==`string`&&pattern.test(e.message)?!0:[e.cause,...Array.isArray(e.errors)?e.errors:[]].some(inner=>findMessage(inner,pattern,depth+1))}const CREDENTIALS_REJECTED=/password authentication failed|access denied for user|authentication failed|NOAUTH|WRONGPASS/i,target=e=>typeof e.address==`string`?`${e.address}${typeof e.port==`number`?`:${e.port}`:``}`:typeof e.hostname==`string`?e.hostname:`the service`;function builtInAdvice(err,where){let refused=findCode(err,[`ECONNREFUSED`]);if(refused)return{summary:`${where} could not connect to ${target(refused)}: connection refused`,cause:`Nothing is listening at that address — the service is down, not started yet, or the URL points at the wrong host or port.`,fix:`Start the service, or check the connection URL in your env (localhost inside a container is the container itself).`};let dns=findCode(err,[`ENOTFOUND`,`EAI_AGAIN`]);if(dns)return{summary:`${where} could not resolve the host ${target(dns)}`,cause:`The host name in the connection URL does not resolve from here.`,fix:`Check the host name in your env — a typo, or a name that only resolves inside another network (a compose service name used from the host).`};let timeout=findCode(err,[`ETIMEDOUT`,`ECONNRESET`]);if(timeout)return{summary:`${where} lost the connection to ${target(timeout)} (${String(timeout.code)})`,cause:`The address answered slowly or not at all — a firewall, a security group, or the wrong network.`,fix:`Check that this machine is allowed to reach the service, and that TLS and port settings match it.`};if(findMessage(err,CREDENTIALS_REJECTED))return{summary:`${where} was refused: the credentials were not accepted`,cause:`The server rejected the user name or password.`,fix:`Check the user and password in your connection URL or env, and that the user exists on this server.`}}function formatAdvice(advice){return[advice.summary,...advice.cause?[``,` Cause: ${advice.cause}`]:[],``,` Fix: ${advice.fix}`].join(`
12
- `)}const log$1=createLogger(`Checks`);function defineCheck(check){return check}var StartupCheckError=class extends Error{messages;constructor(messages){super(`Startup checks failed:\n${messages.map(m=>` ${m.id}: ${m.message}${m.fix?`\n fix: ${m.fix}`:``}`).join(`
13
- `)}`),this.messages=messages,this.name=`StartupCheckError`}};const builtInChecks=[defineCheck({name:`allowed hosts`,deploy:!0,run:({options})=>{let configured=options.security?.allowedHosts,hosts=Array.isArray(configured)?configured:configured?.hosts;if(!(Array.isArray(hosts)&&hosts.length>0&&!hosts.includes(`*`)))return{id:`KICK-SEC-W001`,level:`warning`,message:"No allowed hosts in production (or `*`): any Host header is accepted, and absolute URLs built from it (reset links, redirects) can point anywhere.",fix:`bootstrap({ security: { allowedHosts: ['example.com'] } })`}}}),defineCheck({name:`trust proxy`,deploy:!0,run:({options})=>{if(options.trustProxy===!0)return{id:`KICK-SEC-W002`,level:`warning`,message:"`trustProxy: true` trusts every X-Forwarded-For hop, so a client that reaches the app directly can set its own IP (rate limits, logs, ctx.ip).",fix:"Trust the number of proxies in front of the app instead, e.g. `trustProxy: 1`."}}})];function runStartupChecks(checks,ctx,silenced=[]){let production=isProduction(),skip=new Set(silenced),found=[];for(let check of checks){if(check.deploy&&!production)continue;let result;try{result=check.run({...ctx,production})}catch(err){log$1.error(err,`Startup check '${check.name}' threw`);continue}for(let message of[result??[]].flat())skip.has(message.id)||found.push(message)}for(let message of found)message.level===`warning`&&log$1.warn(`${message.id}: ${message.message}${message.fix?` Fix: ${message.fix}`:``}`);let errors=found.filter(m=>m.level===`error`);if(errors.length>0)throw new StartupCheckError(errors);return found}function __decorateMetadata(k,v){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(k,v)}const HEALTH_PROBE=createToken(`kick/Health/probe`);function createHealthChecks(sources,options={}){let timeoutMs=options.timeoutMs??2e3,cached,runOne=async source=>{let name=source.name??`unknown`,started=Date.now(),timer,timedOut=new Promise(resolve=>{timer=setTimeout(()=>resolve({name,status:`down`,reason:`timeout`}),timeoutMs)});try{return await Promise.race([Promise.resolve().then(()=>source.onHealthCheck()).catch(()=>({name,status:`down`,reason:`error`})),timedOut])}finally{clearTimeout(timer);let ms=Date.now()-started;ms>=timeoutMs*.5&&options.onSlow?.(name,ms)}};return()=>{let now=Date.now();if(cached&&now-cached.at<1e3)return cached.result;let result=Promise.all(sources().filter(s=>s.onHealthCheck).map(runOne));return cached={at:now,result},result}}let HealthController=class{probe;constructor(probe){this.probe=probe}live(){return reply(200,{status:this.probe.isDraining()?`draining`:`ok`,uptime:process.uptime()})}async ready(){if(this.probe.isDraining())return reply(503,{status:`draining`,checks:[]});if(this.probe.isStarting?.())return reply(503,{status:`starting`,checks:[]});let checks=await this.probe.checks(),healthy=checks.every(c=>c.status===`up`);return reply(healthy?200:503,{status:healthy?`ready`:`degraded`,checks})}};__decorate([Get(`/live`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,void 0)],HealthController.prototype,`live`,null),__decorate([Get(`/ready`),__decorateMetadata(`design:type`,Function),__decorateMetadata(`design:paramtypes`,[]),__decorateMetadata(`design:returntype`,Promise)],HealthController.prototype,`ready`,null),HealthController=__decorate([Controller(),__decorateMetadata(`design:paramtypes`,[Object])],HealthController);const healthModule=defineModule({name:`HealthModule`,build:config=>({register(container){container.registerFactory(HealthController,()=>{let probe=container.resolve(HEALTH_PROBE);return new HealthController(probe)})},routes(){return{path:`/health`,controller:HealthController,version:!1,prefix:!1,flags:config.flags}}})}),HOP_BY_HOP_REQUEST=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`host`,`content-length`],HOP_BY_HOP_RESPONSE=[`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`upgrade`,`trailer`,`content-encoding`,`content-length`],LOOPBACK_HOST=`x-kick-loopback-host`,LOOPBACK_SECRET=`x-kick-loopback-secret`;async function streamedBody(request){if(!request.body||request.method===`GET`||request.method===`HEAD`)return;let reader=request.body.getReader(),first=await reader.read();if(!first.done)return new ReadableStream({start(controller){controller.enqueue(first.value)},async pull(controller){let{done,value}=await reader.read();done?controller.close():controller.enqueue(value)},cancel(reason){return reader.cancel(reason)}})}function createLoopback(handle){let started,secret=randomBytes(24).toString(`hex`),server=()=>(started??=new Promise((resolve,reject)=>{let instance=http.createServer((req,res)=>{let host=req.headers[LOOPBACK_HOST];req.headers[LOOPBACK_SECRET]===secret&&typeof host==`string`&&(req.headers.host=host),delete req.headers[LOOPBACK_HOST],delete req.headers[LOOPBACK_SECRET],handle(req,res)});instance.once(`error`,reject),instance.listen(0,`127.0.0.1`,()=>{instance.unref(),resolve({origin:`http://127.0.0.1:${instance.address().port}`,server:instance})})}).catch(err=>{throw started=void 0,err}),started);return{async fetch(request){let{origin}=await server(),url=new URL(request.url),headers=new Headers(request.headers);for(let name of HOP_BY_HOP_REQUEST)headers.delete(name);headers.set(`x-forwarded-host`,url.host),headers.set(`x-forwarded-proto`,url.protocol.slice(0,-1)),headers.set(LOOPBACK_HOST,url.host),headers.set(LOOPBACK_SECRET,secret);let body=await streamedBody(request),upstream=await fetch(origin+url.pathname+url.search,{method:request.method,headers,body,...body?{duplex:`half`}:{},redirect:`manual`,signal:request.signal}),responseHeaders=new Headers(upstream.headers),named=responseHeaders.get(`connection`)?.split(`,`)??[];for(let name of[...HOP_BY_HOP_RESPONSE,...named])responseHeaders.delete(name.trim());return new Response(upstream.body,{status:upstream.status,statusText:upstream.statusText,headers:responseHeaders})},async close(){let running=await started?.catch(()=>void 0);if(started=void 0,!running)return;let closed=new Promise(resolve=>running.server.close(()=>resolve()));running.server.closeAllConnections(),await closed}}}const log=createLogger(`Application`);function assertUsableTls(options){let{key,cert,pfx,SNICallback,pskCallback}=options;if(!pfx&&!SNICallback&&!pskCallback){if(!key&&!cert)throw tlsCredentialsError(`no key/cert, pfx, SNICallback, or pskCallback`);if(!key)throw tlsCredentialsError(`cert is set but key is missing`);if(!cert)throw tlsCredentialsError(`key is set but cert is missing`)}try{tls.createSecureContext(options)}catch(err){throw tlsCredentialsError(err.message)}}function isModuleFactory(entry){return typeof entry==`function`&&`definition`in entry&&typeof entry.scoped==`function`}function isConfigurable(factory){return factory.definition?.defaults!=null}function toAppModule(entry){if(typeof entry!=`function`)return entry;if(isModuleFactory(entry)){if(isConfigurable(entry)){let name=entry.definition?.name||entry.name||`<anonymous>`;throw TypeError(`bootstrap: module \`${name}\` takes configuration, so it must be invoked.\n Write \`${name}()\` for its defaults, or \`${name}({ … })\` to configure it.\n Passing it bare would have silently selected the defaults.`)}return entry()}let name=entry.name||`<anonymous>`;if(!isConstructible(entry))throw TypeError(`bootstrap: module entry \`${name}\` is a function, but not a module class and not a defineModule() factory (no \`definition\`).\n A defineModule() module is passed as \`${name}\` or \`${name}()\`; a class must implement AppModule.`);let mod=new entry;if(typeof mod?.routes!=`function`)throw TypeError(`bootstrap: module entry \`${name}\` constructed, but the result does not implement AppModule — \`routes()\` is missing.\n A module class needs \`routes()\`; a defineModule() module is passed as \`${name}\` or \`${name}()\`.`);return mod}function isConstructible(fn){try{return Reflect.construct(String,[],fn),!0}catch{return!1}}const APPLICATION=createToken(`kick/Http/Application`);var Application=class{options;app;runtime;container;httpServer=null;managementApp=null;managementServer=null;wantsManagement=!1;handlerMode=!1;observers=[];http2Sessions=/* @__PURE__ */ new Set;loopback;timeline=new StartupTimeline;conditionReport=[];mountedRoutes=[];mountedRouteInfo=[];routeUrls=new RouteUrls;settingsPrefixes=/* @__PURE__ */ new Map;settingsProvided=/* @__PURE__ */ new Map;handlerFor;adapters;routePolicy=new RoutePolicyTable;plugins;_moduleContributors=[];_inFlightRequests=0;_status=ref(`idle`);status=computed(()=>this._status.value);_shutdownInitiated=!1;_drainResolvers=[];constructor(options){this.options=options,this.runtime=options.runtime??expressRuntime(),this.container=Container.getInstance(),this.container.registerInstance(APPLICATION,this),this.plugins=mountSort(options.plugins??[],`plugin`);let allAdapters=[...this.plugins.flatMap(p=>p.adapters?.()??[]),...options.adapters??[]],anonAdapterCount=0,namedAdapters=allAdapters.map(adapter=>{if(!adapter.name){let ctorName=adapter.constructor?.name,fallback=ctorName&&ctorName!==`Object`?ctorName:`AnonymousAdapter#${anonAdapterCount++}`;return Object.assign(adapter,{name:fallback})}return adapter});this.adapters=mountSort(this.applyConditions(namedAdapters),`adapter`),this.observers=setObservers([...this.adapters,...this.plugins]),installChannelPublisher(),Container._requestStoreProvider=()=>requestStore.getStore()??null}applyConditions(adapters){let seen=/* @__PURE__ */ new Set;for(let adapter of adapters){if(seen.has(adapter.name))throw new DuplicateMountNameError(`adapter`,adapter.name);seen.add(adapter.name)}let off=/* @__PURE__ */ new Map;for(let adapter of adapters){if(!adapter.when)continue;let result=evaluateCondition(adapter.when,err=>log.warn(`Adapter ${adapter.name}: its \`when\` condition threw — ${String(err)}`));result!==!0&&off.set(adapter.name,result)}let changed=off.size>0;for(;changed;){changed=!1;for(let adapter of adapters){if(off.has(adapter.name))continue;let missing=adapter.dependsOn?.find(dep=>off.has(dep));missing&&(off.set(adapter.name,`depends on ${missing}, which is off`),changed=!0)}}this.conditionReport=adapters.filter(a=>a.when||off.has(a.name)).map(a=>off.has(a.name)?{adapter:a.name,enabled:!1,reason:off.get(a.name)}:{adapter:a.name,enabled:!0});for(let outcome of this.conditionReport)outcome.enabled||log.debug(`Adapter ${outcome.adapter} is off: ${outcome.reason}`);return adapters.filter(a=>!off.has(a.name))}getConditionReport(){return this.conditionReport}get isDraining(){return this._status.value===`draining`||this._status.value===`stopped`}get inFlightRequests(){return this._inFlightRequests}getContainer(){return this.container}fetch(request){if(this.app===void 0)return Promise.reject(/* @__PURE__ */ Error(`kickjs: Application.fetch() before setup — await start() or startWithoutServer() first`));let runtimeApp=this.app;return typeof runtimeApp?.fetch==`function`?Promise.resolve(runtimeApp.fetch(request)):(this.loopback??=createLoopback((req,res)=>this.handle(req,res)),this.loopback.fetch(request))}createEngineApp(){return this.runtime.createApp({trustProxy:this.options.trustProxy,notFoundFallthrough:this.options.notFoundFallthrough,bodyLimit:parseByteSize(this.options.jsonLimit??`1mb`)})}handle(req,res,next){if(this.app===void 0)throw Error(`kickjs: Application.handle() before setup — await start() or startWithoutServer() first`);(!this.handlerFor||this.handlerFor.app!==this.app)&&(this.handlerFor={app:this.app,handler:this.runtime.nodeHandler(this.app)});let handler=this.handlerFor.handler;next?handler(req,res,next):handler(req,res)}adapterCtx(server,owner){let env=process.env.NODE_ENV??`production`,managementApp=this.managementApp;return{http:this.adapterHttp(void 0,owner),app:this.app,fetch:request=>this.fetch(request),container:this.container,server,...managementApp?{management:{http:this.adapterHttp(()=>managementApp,owner),server:this.managementServer??void 0}}:{},env,isProduction:isProduction()}}adapterHttp(target=()=>this.app,owner=`kick`){let record=(method,pattern,handler)=>{this.mountedRouteInfo.push({method,pattern,controller:owner,handler,contributors:[],source:`adapter`,port:target()===this.app?`app`:`management`})};return{route:(method,path,handler)=>{record(method,path,``);let entry={method,path,middlewares:[],contributorRunner:null,handler,meta:{}};this.runtime.mountRoutes(target(),[{mountPath:`/`,routes:[entry]}])},mount:(prefix,routes)=>{for(let entry of routes)record(entry.method,joinPaths(prefix,entry.path),String(entry.meta.handlerName??``));this.runtime.mountRoutes(target(),[{mountPath:prefix,routes}])},serveStatic:(prefix,dir)=>{record(`GET`,`${joinPaths(prefix,`/`).replace(/\/$/,``)}/*`,`static`),this.runtime.serveStatic(target(),prefix,dir)},use:(mw,opts)=>{this.runtime.useConnect(target(),mw,opts)}}}async callHook(hook,ctx,adapterName=`adapter`,hookName){if(!hook)return;let where=`${adapterName}.${hookName}`;try{await this.timeline.time(where,()=>hook(ctx))}catch(err){if(this.adviseOnFailure(err,where,adapterName),hookName!==`afterStart`)throw err;log.error(err,`${adapterName} afterStart hook failed`)}}adviseOnFailure(err,where,adapterName){let adapter=this.adapters.find(a=>a.name===adapterName),advice;try{advice=adapter?.analyzeFailure?.(err)}catch(analyzerErr){log.debug(`${adapterName}.analyzeFailure threw: ${String(analyzerErr)}`)}advice??=builtInAdvice(err,where),advice&&log.error(formatAdvice(advice))}getStartupTimeline(){return this.timeline.snapshot()}urlFor(name,...args){let[params,query]=args;return this.routeUrls.build(name,params,query)}collectModules(){let registry=new MutableModuleRegistry;for(let plugin of this.plugins){for(let m of plugin.modules?.()??[])registry.mount(m);plugin.setup?.(registry)}for(let m of this.options.modules)registry.mount(m);return this.options.setup?.(registry),registry}describeConfig(){let sections=[],seen=/* @__PURE__ */ new Set,add=(declaredBy,list)=>{for(let decl of list??[]){let section=`section`in decl?decl.section:decl;seen.has(section)||(seen.add(section),sections.push({prefix:section.prefix,declaredBy,vars:section.describe()}))}};add(`app`,this.options.settings);for(let plugin of this.plugins)add(`plugin ${plugin.name}`,plugin.settings?.());for(let adapter of this.adapters)add(`adapter ${adapter.name}`,adapter.settings?.());for(let entry of this.collectModules().entries){let mod=toAppModule(entry);add(`module ${moduleName(mod)}`,mod.settings?.())}return{env:describeEnvSchema(),sections}}configOrigins(){return{env:originsOf(describeEnvSchema()),sections:Array.from(this.settingsPrefixes.values(),section=>({prefix:section.prefix,vars:this.settingsProvided.has(section)?section.envNames.map(name=>({name,origin:`provided`})):originsOf(section.describe())}))}}bindSettings(sections){for(let[section,value]of loadSettings(sections,process.env,this.settingsPrefixes,this.settingsProvided))this.container.registerInstance(section,value)}runChecks(){runStartupChecks([...builtInChecks,...this.options.checks??[]],{options:this.options,routes:this.mountedRoutes},this.options.silenceChecks),this.timeline.mark(`checks`)}reportStartup(){let{totalMs}=this.timeline.snapshot();if(totalMs<1e3)return;let slowest=this.timeline.slowest(3).map(step=>`${step.name} ${Math.round(step.ms)}ms`).join(`, `);log.info(`Startup took ${Math.round(totalMs)}ms — slowest: ${slowest}`)}async setup(){log.debug(`Bootstrapping application...`),await this.runtime.load?.(),await settleExpressLoad(),this.app??=this.createEngineApp(),this.wantsManagement&&(this.managementApp??=this.createEngineApp()),this.timeline=new StartupTimeline,this.mountedRouteInfo=[],this.routeUrls=new RouteUrls,this.container.registerInstance(ROUTE_URLS,this.routeUrls),this.container.registerInstance(APPLICATION,this),this.settingsPrefixes=/* @__PURE__ */ new Map,this.settingsProvided=/* @__PURE__ */ new Map,this.bindSettings([...this.options.settings??[],...this.plugins.flatMap(plugin=>plugin.settings?.()??[]),...this.adapters.flatMap(adapter=>adapter.settings?.()??[])]),this._moduleContributors=[];let adapterMw=this.collectAdapterMiddleware();this.app.__kickApp=this;let hostList=this.options.security?.allowedHosts;if(hostList){let hostOptions=Array.isArray(hostList)?{hosts:hostList}:hostList;this.runtime.useConnect(this.app,allowedHosts({...hostOptions,ignorePaths:[...hostOptions.ignorePaths??[],`/health/live`,`/health/ready`]}))}for(let adapter of this.adapters)await this.callHook(adapter.beforeMount?.bind(adapter),this.adapterCtx(void 0,adapter.name),adapter.name,`beforeMount`);this.handlerMode&&this.mountCronTrigger(),this.runtime.useConnect(this.app,this.requestTrackingMiddleware()),this.shouldAutoMountRequestScope()&&this.runtime.useConnect(this.app,requestScopeMiddleware()),this.managementApp&&this.options.contextStore!==`manual`&&this.runtime.useConnect(this.managementApp,requestScopeMiddleware()),this.mountMiddlewareList(adapterMw.beforeGlobal);for(let plugin of this.plugins)plugin.register?.(this.container);for(let plugin of this.plugins)try{let mw=plugin.middleware?.()??[];for(let handler of mw)this.runtime.useConnect(this.app,handler)}catch(err){log.error(err,`Plugin middleware failed: ${plugin.name??`unknown`}`)}let declaredHelmet=(this.options.middlewares??[]).some(entry=>typeof entry==`function`&&Symbol.for(`kick/http/helmet`)in entry);if(this.options.security?.helmet!==!1&&!declaredHelmet)try{let{helmet:helmetFn}=await import(`./http/middleware/helmet.mjs`);this.runtime.useConnect(this.app,helmetFn())}catch{}let userMiddlewares=this.options.middlewares;if(userMiddlewares)for(let entry of userMiddlewares)this.mountMiddlewareEntry(entry);else if(this.runtime.useConnect(this.app,requestId()),!this.runtime.capabilities.nativeBodyParsing){let limit=this.options.jsonLimit??`1mb`,parsers=this.runtime.bodyParsers?this.runtime.bodyParsers({limit}):await expressBodyParsers(limit);for(let parser of parsers)this.runtime.useConnect(this.app,parser)}this.mountMiddlewareList(adapterMw.afterGlobal),this.timeline.mark(`middleware`);let moduleRegistry=this.collectModules();this.options.health!==!1&&(this.container.registerInstance(HEALTH_PROBE,{isDraining:()=>this.isDraining,isStarting:()=>this._status.value===`starting`,checks:createHealthChecks(()=>this.adapters,{timeoutMs:typeof this.options.health==`object`?this.options.health.checkTimeout:void 0,onSlow:(name,ms)=>log.warn(`Health check '${name}' took ${ms}ms`)})}),moduleRegistry.mount(healthModule(this.options.health===!0?{}:this.options.health)));let modules=moduleRegistry.entries.map(toAppModule);this.bindSettings(modules.flatMap(mod=>mod.settings?.()??[]));for(let mod of modules)mod.register?.(this.container);this.container.bootstrap(),this.container.has(Logger)||this.container.registerInstance(Logger,new Logger),this.timeline.mark(`modules`),this.mountMiddlewareList(adapterMw.beforeRoutes);let apiPrefix=this.options.apiPrefix??`/api`,defaultVersion=this.options.defaultVersion??1,shouldLogRoutes=this.options.logRouteTable??this.options.logRoutesTable??!1,mountedRoutes=[],adapterSources=[];for(let adapter of this.adapters){let adapterContribs=adapter.contributors?.()??[],adapterLabel=adapter.name??adapter.constructor.name??`adapter`;for(let registration of adapterContribs)adapterSources.push({source:`adapter`,registration,label:adapterLabel})}for(let plugin of this.plugins){let pluginContribs=plugin.contributors?.()??[],pluginLabel=plugin.name??plugin.constructor?.name??`plugin`;for(let registration of pluginContribs)adapterSources.push({source:`adapter`,registration,label:pluginLabel})}let globalSources=(this.options.contributors??[]).map(registration=>({source:`global`,registration,label:`bootstrap`}));this._moduleContributors=[];let seenRoutes=/* @__PURE__ */ new Map,mountedPaths=[],managementPaths=[];this.mountedRoutes=mountedPaths;for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));for(let src of moduleSources)this._moduleContributors.push({registration:src.registration,label:moduleLabel});_setExternalContributorSources([...moduleSources,...adapterSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);if(route.router)this.runtime.useConnect(this.app,route.router,{path:mountPath});else if(route.controller){let target=this.managementApp&&route.controller===HealthController?this.managementApp:this.app,routeTable=buildRouteTable(route.controller,{mountFlags:route.flags}),ctrl=route.controller.name??`controller`;for(let entry of routeTable){let owner=`${ctrl}.${String(entry.meta.handlerName??`?`)}`,fullPath=joinPaths(mountPath,entry.path);assertRouteUnique(seenRoutes,entry.method,fullPath,owner),(target===this.app?mountedPaths:managementPaths).push({method:entry.method,path:fullPath}),this.routeUrls.add(owner,fullPath),this.routePolicy.add(entry.method,fullPath,entry.meta.flags)}let traced=routeTable.map(entry=>{let pattern=joinPaths(mountPath,entry.path);return{...entry,handler:traceHandler(entry.handler,{method:entry.method,route:pattern,controller:route.controller?.name,handler:entry.meta.handlerName}),meta:{...entry.meta,pattern},validationError:this.options.validationError,urls:this.routeUrls}});this.runtime.mountRoutes(target,[{mountPath,routes:traced}]);for(let entry of traced)this.mountedRouteInfo.push({method:entry.method,pattern:entry.meta.pattern??entry.path,controller:route.controller.name,handler:String(entry.meta.handlerName??``),contributors:entry.meta.contributors??[],source:`module`,port:target===this.app?`app`:`management`})}else throw moduleRouteMissingControllerError(mountPath);let onManagement=!!this.managementApp&&route.controller===HealthController;if(route.controller&&!onManagement)for(let adapter of this.adapters)try{adapter.onRouteMount?.(route.controller,mountPath)}catch(err){log.error(err,`adapter.onRouteMount() failed for ${mountPath}`)}route.controller&&shouldLogRoutes&&mountedRoutes.push({controller:route.controller,mountPath,management:onManagement})}}finally{_setExternalContributorSources([])}}if(shouldLogRoutes&&mountedRoutes.length>0){let methodOrder=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`],methodRank=m=>{let i=methodOrder.indexOf(m);return i===-1?99:i},totalRoutes=0;log.info(`Routes:`);for(let{controller,mountPath,management}of mountedRoutes){let defs=getClassMeta(METADATA.ROUTES,controller,[]);if(defs.length===0)continue;let counts={};for(let def of defs){let m=def.method.toUpperCase();counts[m]=(counts[m]||0)+1}totalRoutes+=defs.length;let methods=Object.entries(counts).toSorted(([a],[b])=>methodRank(a)-methodRank(b)).map(([m,n])=>`${n} ${m}`).join(`, `),name=controller.name||`Controller`,port=management?` [management port]`:``;log.info(` ${name.padEnd(30)} ${mountPath.padEnd(25)} ${defs.length} routes (${methods})${port}`)}log.info(` Total: ${totalRoutes} routes`)}this.mountMiddlewareList(adapterMw.afterRoutes),this.timeline.mark(`routes`);for(let adapter of this.adapters)await this.callHook(adapter.beforeStart?.bind(adapter),this.adapterCtx(void 0,adapter.name),adapter.name,`beforeStart`);for(let entry of this.options.middlewares??[])offerRoutePolicy(typeof entry==`function`?entry:entry.handler,this.routePolicy);for(let adapter of this.adapters)for(let mw of adapter.middleware?.()??[])offerRoutePolicy(mw.handler,this.routePolicy);let builtInNotFound=notFoundHandler(mountedPaths),customNotFound=this.options.onNotFound;this.runtime.setNotFound(this.app,customNotFound?(req,res,next)=>customNotFound(req,res,err=>err===void 0?builtInNotFound(req,res,next):next(err)):builtInNotFound),this.runtime.setErrorHandler(this.app,observeErrors(this.options.onError??errorHandler())),this.managementApp&&(this.runtime.setNotFound(this.managementApp,notFoundHandler(managementPaths)),this.runtime.setErrorHandler(this.managementApp,observeErrors(errorHandler()))),this.timeline.mark(`error handlers`)}async registerOnly(){await this.setup()}async startWithoutServer(){await this.untilStartedOrStopped(()=>this.startWithoutServerSteps())}async untilStartedOrStopped(run){try{await run()}catch(err){throw this._status.value=`stopped`,err}}async startWithoutServerSteps(){this.handlerMode=!0,this._status.value=`starting`,await this.setup(),this.runChecks();let needServer=this.adapters.filter(adapter=>adapter.afterStart);needServer.length>0&&log.warn(`No HTTP server in handler mode, so afterStart does not run for: ${needServer.map(adapter=>adapter.name).join(`, `)}. Anything they attach to the server (WebSockets, upgrade handlers) is unavailable.`);for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup()}async start(){await this.untilStartedOrStopped(()=>this.startSteps())}async startSteps(){let g=globalThis,serverOptions=this.options.server;if(this._status.value=`starting`,serverOptions&&g.__kickjs_httpServer)log.warn(`server options (tls / http2) are ignored in dev mode — Vite owns the server`);else if(serverOptions){if(serverOptions.http2&&!serverOptions.tls)throw http2RequiresTlsError();if(serverOptions.http2&&!this.runtime.capabilities.http2)throw http2UnsupportedRuntimeError(this.runtime.name);serverOptions.tls&&assertUsableTls(serverOptions.tls)}let management=this.options.management;if(management&&g.__kickjs_httpServer?log.info(`management port is ignored in dev mode — /health stays on the dev server`):management&&(this.wantsManagement=!0),await this.setup(),this.runChecks(),g.__kickjs_httpServer){this.httpServer=g.__kickjs_httpServer,log.debug(`Attached to Vite dev server`),g.__kickjs_app_shutdown=()=>this.shutdown();for(let adapter of this.adapters){let ctx=this.adapterCtx(this.httpServer,adapter.name);await this.callHook(adapter.afterStart?.bind(adapter),ctx,adapter.name,`afterStart`)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup();return}let port=this.options.port??parseInt(process.env.PORT||`3000`,10);this.httpServer=this.createNodeServer(),this.httpServer.on(`error`,err=>{throw err.code===`EADDRINUSE`&&(log.error(`Port ${port} is already in use. Kill the existing process or use a different port:\n PORT=${port+1} kick dev\n lsof -i :${port} # find what's using it\n kill <PID> # stop it`),process.exit(1)),err}),this.managementApp&&management&&await this.listenManagement(management);try{await this.listenAndFinishStartup(port,serverOptions)}catch(err){throw await this.closeManagementServer(),err}}async listenAndFinishStartup(port,serverOptions){await new Promise((resolve,reject)=>{this.httpServer.listen(port,async()=>{try{let scheme=serverOptions?.tls?`https`:`http`,protocol=serverOptions?.http2?` (HTTP/2)`:``;this.timeline.mark(`listen`),log.info(`Server running on ${scheme}://localhost:${port}${protocol}`);for(let adapter of this.adapters){let afterCtx=this.adapterCtx(this.httpServer,adapter.name);await this.callHook(adapter.afterStart?.bind(adapter),afterCtx,adapter.name,`afterStart`)}for(let plugin of this.plugins)await plugin.onReady?.(this.container);this.timeline.mark(`ready`),this._status.value=`ready`,this.timeline.complete(),this.reportStartup(),resolve()}catch(err){reject(err)}})})}async closeManagementServer(){let server=this.managementServer;server&&(this.managementServer=null,await new Promise(resolve=>{server.close(()=>resolve()),server.closeAllConnections()}))}async listenManagement(options){let handler=this.runtime.nodeHandler(this.managementApp);options.tls&&assertUsableTls(options.tls);let server=options.tls?https.createServer(options.tls,handler):http.createServer(handler);await new Promise((resolve,reject)=>{server.once(`error`,reject),server.listen(options.port,options.host,()=>{server.off(`error`,reject),resolve()})}),this.managementServer=server;let scheme=options.tls?`https`:`http`;log.info(`Management server on ${scheme}://${options.host??`localhost`}:${options.port}`);for(let line of describeRoutes(this.mountedRouteInfo.filter(r=>r.port===`management`)))log.info(` ${line}`)}createNodeServer(){let server=this.createBareServer(),options=this.options.server??{},keepAlive=options.keepAliveTimeout??65e3;return`keepAliveTimeout`in server&&(server.keepAliveTimeout=keepAlive,server.headersTimeout=options.headersTimeout??keepAlive+1e3,server.requestTimeout=options.requestTimeout??3e5),server}createBareServer(){let handler=this.runtime.nodeHandler(this.app),{tls,http2:useHttp2}=this.options.server??{};if(useHttp2){let server=http2.createSecureServer({...tls,allowHTTP1:!0},handler);return server.on(`session`,session=>{this.http2Sessions.add(session),session.once(`close`,()=>this.http2Sessions.delete(session))}),server}return tls?https.createServer(tls,handler):http.createServer(handler)}async rebuild(){let prevApp=this.app,prevContainer=this.container,prevRouteUrls=this.routeUrls,prevSettingsPrefixes=this.settingsPrefixes,prevSettingsProvided=this.settingsProvided,staleDisposables=drainDisposables();try{Container.reset(),this.container=Container.getInstance(),this.app=this.createEngineApp(),await this.setup()}catch(err){log.error(err,`HMR rebuild failed, keeping previous app`),await runDisposables(drainDisposables());for(let d of staleDisposables)registerDisposable(d);this.app=prevApp,this.container=prevContainer,this.routeUrls=prevRouteUrls,this.settingsPrefixes=prevSettingsPrefixes,this.settingsProvided=prevSettingsProvided;return}await runDisposables(staleDisposables),this.httpServer&&(this.httpServer.removeAllListeners(`request`),this.httpServer.on(`request`,this.runtime.nodeHandler(this.app)),log.debug(`HMR: app rebuilt and swapped`))}async shutdown(options={}){let closeServer=options.closeServer??!0;if(this._shutdownInitiated){log.debug(`Shutdown already in progress, skipping duplicate call`);return}this._shutdownInitiated=!0,this._status.value=`draining`;let preStopDelay=this.options.preStopDelay??0;closeServer&&preStopDelay>0&&(log.debug(`Waiting ${preStopDelay}ms for load balancers to stop routing here...`),await new Promise(resolve=>setTimeout(resolve,preStopDelay))),log.debug(`Shutting down — draining in-flight requests...`);let timeoutMs=this.options.shutdownTimeout??3e4,timer,forceExitPromise=timeoutMs>0?new Promise(resolve=>{timer=setTimeout(()=>resolve(`timeout`),timeoutMs),timer.unref()}):new Promise(()=>{});try{if(closeServer&&this.httpServer){this.httpServer.close(()=>{});for(let session of this.http2Sessions)session.close()}if(closeServer&&this._inFlightRequests>0){log.debug(`Waiting for ${this._inFlightRequests} in-flight request(s) to complete...`);let drainPromise=new Promise(resolve=>{this._drainResolvers.push(()=>resolve(`drained`))});if(await Promise.race([drainPromise,forceExitPromise])===`timeout`){log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${this._inFlightRequests} request(s) still in-flight, forcing shutdown`);for(let session of this.http2Sessions)session.destroy()}else log.debug(`All in-flight requests completed`)}closeServer&&pendingBackgroundWork()>0&&(log.debug(`Waiting for ${pendingBackgroundWork()} waitUntil() task(s) to settle...`),await Promise.race([settleBackgroundWork().then(()=>`settled`),forceExitPromise])===`timeout`&&log.warn(`Shutdown timeout (${timeoutMs}ms) reached with ${pendingBackgroundWork()} waitUntil() task(s) still running`));let hookTimeoutMs=closeServer?timeoutMs:Math.min(timeoutMs,5e3),timeBoxed=(label,run)=>{let hook=(async()=>run())();return hookTimeoutMs<=0?hook:new Promise((resolve,reject)=>{let t=setTimeout(()=>{log.warn(`${label} did not finish shutting down within ${hookTimeoutMs}ms — continuing without it. Its resources may still be held.`),resolve(void 0)},hookTimeoutMs);t.unref(),hook.then(value=>{clearTimeout(t),resolve(value)},err=>{clearTimeout(t),reject(err)})})},wasListening=this.httpServer?.listening===!0,results=await Promise.allSettled([...this.plugins.map(plugin=>timeBoxed(`Plugin '${plugin.name}'`,()=>plugin.shutdown?.())),...this.adapters.map(adapter=>timeBoxed(`Adapter '${adapter.name}'`,()=>adapter.shutdown?.())),timeBoxed(`Runtime '${this.runtime.name}'`,()=>this.runtime.close?.(this.app)),...this.managementApp&&closeServer?[timeBoxed(`Runtime '${this.runtime.name}' (management)`,()=>this.runtime.close?.(this.managementApp))]:[]]);!closeServer&&wasListening&&this.httpServer?.listening===!1&&log.error("An adapter or plugin closed the shared HTTP server during an HMR reload. The dev server is now unreachable and will not rebind until you restart it. Close only what you own: socket.io's `io.close()` closes the HTTP server passed to its constructor — on a reload, disconnect the sockets instead.");for(let result of results)result.status===`rejected`&&log.error({err:result.reason},`Adapter shutdown failed`);await disposeAll(),this.container.flushChanges(),await this.loopback?.close(),this.loopback=void 0,closeServer&&await this.closeManagementServer(),closeServer&&releaseObservers(this.observers)}finally{timer&&clearTimeout(timer),this._status.value=`stopped`}}getRuntimeApp(){return this.app}getActiveRuntime(){return{name:this.runtime.name,capabilities:this.runtime.capabilities}}getExpressApp(){return this.app}getAdapters(){return this.adapters}getPlugins(){return this.plugins}getRoutes(){return this.mountedRouteInfo}getContributors(){let out=[],ingest=(list,source,label)=>{if(list)for(let reg of list){let r=reg;if(r.key===void 0||r.key===null)continue;let key=typeof r.key==`string`?r.key:tokenName(r.key);out.push({key,source,label,dependsOn:Array.isArray(r.dependsOn)?r.dependsOn:[]})}};for(let adapter of this.adapters)ingest(adapter.contributors?.(),`adapter`,adapter.name??`adapter`);for(let plugin of this.plugins)ingest(plugin.contributors?.(),`plugin`,plugin.name??`plugin`);for(let{registration,label}of this._moduleContributors)ingest([registration],`module`,label);ingest(this.options.contributors,`global`,`bootstrap`);let sites=/* @__PURE__ */ new Set;for(let route of this.mountedRouteInfo)for(let c of route.contributors){if(c.source!==`class`&&c.source!==`method`)continue;let site=`${c.source}:${c.label??`${route.controller}.${route.handler}`}`;sites.has(site)||(sites.add(site),out.push({key:c.key,source:c.source,label:c.label??`${route.controller}.${route.handler}`,dependsOn:c.dependsOn}))}return out}getHttpServer(){return this.httpServer}getManagementServer(){return this.managementServer}shouldAutoMountRequestScope(){if(this.options.contextStore===`manual`)return!1;let userEntries=this.options.middlewares??[];for(let entry of userEntries){let handler=typeof entry==`function`?entry:entry.handler;if(isRequestScopeMiddleware(handler))return!1}return!0}collectAdapterMiddleware(){let result={beforeGlobal:[],afterGlobal:[],beforeRoutes:[],afterRoutes:[]};for(let adapter of this.adapters){let entries=adapter.middleware?.()??[];for(let entry of entries)result[entry.phase??`afterGlobal`].push(entry)}return result}mountMiddlewareList(entries){for(let entry of entries)entry.path===void 0?this.runtime.useConnect(this.app,entry.handler):this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}mountMiddlewareEntry(entry){typeof entry==`function`?this.runtime.useConnect(this.app,entry):this.runtime.useConnect(this.app,entry.handler,{path:entry.path})}mountCronTrigger(){let secret=process.env.CRON_SECRET;secret&&this.adapterHttp().route(`GET`,`/_kick/cron/:scheduleId`,async ctx=>{if(!matchesBearer(ctx.headers.authorization,secret))throw new HttpException(401,`Missing or invalid CRON_SECRET bearer token`);let result=await runCronJobs(this.container,{scheduleId:ctx.params.scheduleId},`http`);ctx.json(result,result.failed>0?500:200)})}requestTrackingMiddleware(){return(req,res,next)=>{this._inFlightRequests++;let started=hasResponseObservers()?performance.now():void 0,onFinish=()=>settle(!0),onClose=()=>settle(!1),settle=finished=>{if(res.removeListener(`finish`,onFinish),res.removeListener(`close`,onClose),finished&&started!==void 0){let matched=req[ROUTE_SLOT];reportResponse({method:req.method,path:requestPath(req),route:matched?.pattern,status:res.statusCode,durationMs:performance.now()-started,requestId:requestIdOf(req)})}if(this._inFlightRequests--,this.isDraining&&this._inFlightRequests===0){for(let resolve of this._drainResolvers)resolve();this._drainResolvers=[]}};res.on(`finish`,onFinish),res.on(`close`,onClose),next()}}};function describeRoutes(routes){let byOwner=/* @__PURE__ */ new Map;for(let route of routes)byOwner.set(route.controller,[...byOwner.get(route.controller)??[],route]);let width=Math.max(0,...[...byOwner.keys()].map(owner=>owner.length));return[...byOwner].map(([owner,list])=>{if(list.length<=4)return`${owner.padEnd(width)} ${list.map(r=>`${r.method} ${r.pattern}`).join(`, `)}`;let segments=list.map(r=>r.pattern.split(`/`)),common=[];for(let i=0;segments.every(s=>s[i]!==void 0&&s[i]===segments[0][i]);i++)common.push(segments[0][i]);return`${owner.padEnd(width)} ${list.length} routes under ${common.join(`/`)||`/`}`})}function requestPath(req){return(req.originalUrl??req.url??``).split(`?`)[0]}function requestIdOf(req){let header=req.headers?.[`x-request-id`];return req.requestId??(typeof header==`string`?header:void 0)}function errorStatus(err){return typeof err?.problem?.status==`number`?err.problem.status:typeof err?.status==`number`?err.status:typeof err?.statusCode==`number`?err.statusCode:err?.name===`ZodError`?422:500}function observeErrors(handler){return((err,req,res,next)=>{let matched=req?.[ROUTE_SLOT];return reportError(err,{source:`request`,requestId:requestIdOf(req??{}),method:req?.method,path:requestPath(req??{}),route:matched?.pattern,status:errorStatus(err)}),handler(err,req,res,next)})}export{MountCycleError as _,HealthController as a,defineCheck as c,onPackage as d,ERROR_CHANNEL as f,MissingMountDepError as g,DuplicateMountNameError as h,HEALTH_PROBE as i,allOf as l,RESPONSE_CHANNEL as m,Application as n,healthModule as o,HANDLER_CHANNEL as p,describeRoutes as r,StartupCheckError as s,APPLICATION as t,onEnv as u,mountSort as v};
14
- //# sourceMappingURL=application-BSzwuTQ6.mjs.map