@forinda/kickjs 6.7.0 → 7.1.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 (135) hide show
  1. package/dist/{adapter-diFqgxGR.d.mts → adapter-NstPNaFV.d.mts} +36 -3
  2. package/dist/{adapter-diFqgxGR.d.mts.map → adapter-NstPNaFV.d.mts.map} +1 -1
  3. package/dist/{application-VxxP88FH.mjs → application-BDtFj66k.mjs} +3 -3
  4. package/dist/application-BDtFj66k.mjs.map +1 -0
  5. package/dist/{application-D_mReBi_.d.mts → application-CnJh2Bry.d.mts} +55 -15
  6. package/dist/application-CnJh2Bry.d.mts.map +1 -0
  7. package/dist/{bootstrap-F6IShJ1f.mjs → bootstrap-CJbP4DXN.mjs} +3 -3
  8. package/dist/{bootstrap-F6IShJ1f.mjs.map → bootstrap-CJbP4DXN.mjs.map} +1 -1
  9. package/dist/{bootstrap-CytCvAnr.d.mts → bootstrap-Iq_WR08c.d.mts} +2 -2
  10. package/dist/bootstrap-Iq_WR08c.d.mts.map +1 -0
  11. package/dist/client-ip-Di2MrjCQ.mjs +12 -0
  12. package/dist/client-ip-Di2MrjCQ.mjs.map +1 -0
  13. package/dist/config/index.mjs +2 -2
  14. package/dist/{config-D035b21X.mjs → config-BQgwhAlJ.mjs} +3 -3
  15. package/dist/{config-D035b21X.mjs.map → config-BQgwhAlJ.mjs.map} +1 -1
  16. package/dist/{container-CFVAdwXa.mjs → container-BITnQkhU.mjs} +3 -3
  17. package/dist/{container-CFVAdwXa.mjs.map → container-BITnQkhU.mjs.map} +1 -1
  18. package/dist/context-DYOcPcg8.mjs +12 -0
  19. package/dist/context-DYOcPcg8.mjs.map +1 -0
  20. package/dist/{context-errors-Ce44238b.mjs → context-errors-Bf2NqTS3.mjs} +2 -2
  21. package/dist/{context-errors-Ce44238b.mjs.map → context-errors-Bf2NqTS3.mjs.map} +1 -1
  22. package/dist/core/adapter.d.mts +1 -1
  23. package/dist/core/adapter.mjs +1 -1
  24. package/dist/core/app-module.mjs +1 -1
  25. package/dist/core/cache.mjs +1 -1
  26. package/dist/core/container.mjs +2 -2
  27. package/dist/core/cron.mjs +2 -2
  28. package/dist/core/decorators.mjs +2 -2
  29. package/dist/core/errors.mjs +1 -1
  30. package/dist/core/interfaces.mjs +1 -1
  31. package/dist/core/logger.mjs +1 -1
  32. package/dist/core/path.mjs +1 -1
  33. package/dist/core/plugin.d.mts +1 -1
  34. package/dist/core/plugin.mjs +1 -1
  35. package/dist/core/reactivity.mjs +1 -1
  36. package/dist/{core-DW5uoNhO.mjs → core-MI5Y1nGg.mjs} +3 -3
  37. package/dist/{core-DW5uoNhO.mjs.map → core-MI5Y1nGg.mjs.map} +1 -1
  38. package/dist/csrf-BAnc9Ww7.mjs +12 -0
  39. package/dist/csrf-BAnc9Ww7.mjs.map +1 -0
  40. package/dist/csrf-vR23CJas.d.mts.map +1 -1
  41. package/dist/define-adapter-Cz-bj4Xk.mjs +12 -0
  42. package/dist/define-adapter-Cz-bj4Xk.mjs.map +1 -0
  43. package/dist/{disposables-QYOU5_Eg.mjs → disposables-0gJffTe_.mjs} +2 -2
  44. package/dist/{disposables-QYOU5_Eg.mjs.map → disposables-0gJffTe_.mjs.map} +1 -1
  45. package/dist/{env-DPEhlEC4.mjs → env-IfTg0Rv1.mjs} +3 -3
  46. package/dist/{env-DPEhlEC4.mjs.map → env-IfTg0Rv1.mjs.map} +1 -1
  47. package/dist/{error-handler-Cr6Yt9as.d.mts → error-handler-p_T3hhiD.d.mts} +19 -4
  48. package/dist/error-handler-p_T3hhiD.d.mts.map +1 -0
  49. package/dist/{handler-DcxBY95X.mjs → handler-mLCYXfTQ.mjs} +3 -3
  50. package/dist/{handler-DcxBY95X.mjs.map → handler-mLCYXfTQ.mjs.map} +1 -1
  51. package/dist/http/application.d.mts +2 -2
  52. package/dist/http/application.mjs +2 -2
  53. package/dist/http/bootstrap.d.mts +1 -1
  54. package/dist/http/bootstrap.mjs +2 -2
  55. package/dist/http/context.d.mts +1 -1
  56. package/dist/http/context.mjs +2 -2
  57. package/dist/http/middleware/cors.mjs +1 -1
  58. package/dist/http/middleware/csrf.mjs +2 -2
  59. package/dist/http/middleware/error-handler.d.mts +1 -1
  60. package/dist/http/middleware/error-handler.mjs +2 -2
  61. package/dist/http/middleware/error-handler.mjs.map +1 -1
  62. package/dist/http/middleware/helmet.mjs +1 -1
  63. package/dist/http/middleware/rate-limit.mjs +2 -2
  64. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  65. package/dist/http/middleware/request-id.mjs +1 -1
  66. package/dist/http/middleware/request-logger.d.mts +1 -1
  67. package/dist/http/middleware/request-logger.mjs +2 -2
  68. package/dist/http/middleware/request-logger.mjs.map +1 -1
  69. package/dist/http/middleware/session.mjs +2 -2
  70. package/dist/http/middleware/spa.d.mts +2 -2
  71. package/dist/http/middleware/spa.mjs +2 -2
  72. package/dist/http/middleware/spa.mjs.map +1 -1
  73. package/dist/http/middleware/upload.d.mts +1 -1
  74. package/dist/http/middleware/upload.mjs +2 -2
  75. package/dist/http/middleware/validate.mjs +1 -1
  76. package/dist/http/middleware/views.d.mts +1 -1
  77. package/dist/http/middleware/views.mjs +3 -2
  78. package/dist/http/middleware/views.mjs.map +1 -0
  79. package/dist/http/query/index.mjs +2 -2
  80. package/dist/http/router-builder.d.mts +1 -1
  81. package/dist/http/router-builder.mjs +2 -2
  82. package/dist/http/runtimes/fastify.d.mts +1 -1
  83. package/dist/http/runtimes/fastify.mjs +2 -2
  84. package/dist/http/runtimes/h3-web.d.mts +1 -1
  85. package/dist/http/runtimes/h3-web.mjs +2 -2
  86. package/dist/http/runtimes/h3.d.mts +1 -1
  87. package/dist/http/runtimes/h3.mjs +2 -2
  88. package/dist/index.d.mts +9 -10
  89. package/dist/index.mjs +2 -2
  90. package/dist/index.mjs.map +1 -1
  91. package/dist/kv-stores-DNeEYG-J.mjs +12 -0
  92. package/dist/kv-stores-DNeEYG-J.mjs.map +1 -0
  93. package/dist/{kv-stores-D2kSUAEP.d.mts → kv-stores-pWdw8RKf.d.mts} +3 -3
  94. package/dist/kv-stores-pWdw8RKf.d.mts.map +1 -0
  95. package/dist/{metadata-DjW8JOQZ.mjs → metadata-CyyYO_qa.mjs} +2 -2
  96. package/dist/{metadata-DjW8JOQZ.mjs.map → metadata-CyyYO_qa.mjs.map} +1 -1
  97. package/dist/{module-registry-cbndPnlY.mjs → module-registry-BfOa58-E.mjs} +2 -2
  98. package/dist/{module-registry-cbndPnlY.mjs.map → module-registry-BfOa58-E.mjs.map} +1 -1
  99. package/dist/{query-B_YnIZ2-.mjs → query-BYUCKdu5.mjs} +2 -2
  100. package/dist/{query-B_YnIZ2-.mjs.map → query-BYUCKdu5.mjs.map} +1 -1
  101. package/dist/rate-limit-Dme747JJ.d.mts.map +1 -1
  102. package/dist/{reply-Y50qUtDy.mjs → reply-Bo950wuK.mjs} +3 -3
  103. package/dist/{reply-Y50qUtDy.mjs.map → reply-Bo950wuK.mjs.map} +1 -1
  104. package/dist/{request-logger-BU4ulKLp.d.mts → request-logger-D_pf4xzE.d.mts} +21 -3
  105. package/dist/request-logger-D_pf4xzE.d.mts.map +1 -0
  106. package/dist/{router-builder-C6E11Grf.d.mts → router-builder-BYDUIiZW.d.mts} +2 -2
  107. package/dist/{router-builder-C6E11Grf.d.mts.map → router-builder-BYDUIiZW.d.mts.map} +1 -1
  108. package/dist/{router-builder-DtonR20n.mjs → router-builder-Bv175XoR.mjs} +3 -3
  109. package/dist/{router-builder-DtonR20n.mjs.map → router-builder-Bv175XoR.mjs.map} +1 -1
  110. package/dist/{views-BBY9_PUV.d.mts → spa-CDQ74RGA.d.mts} +136 -11
  111. package/dist/spa-CDQ74RGA.d.mts.map +1 -0
  112. package/dist/{upload-Wck12jE5.d.mts → upload-CUtcjc-n.d.mts} +2 -2
  113. package/dist/{upload-Wck12jE5.d.mts.map → upload-CUtcjc-n.d.mts.map} +1 -1
  114. package/dist/{upload-config-Dxr2BxTi.mjs → upload-config-C9V9tIR3.mjs} +2 -2
  115. package/dist/{upload-config-Dxr2BxTi.mjs.map → upload-config-C9V9tIR3.mjs.map} +1 -1
  116. package/dist/web.d.mts +2 -2
  117. package/dist/web.mjs +2 -2
  118. package/package.json +5 -5
  119. package/dist/application-D_mReBi_.d.mts.map +0 -1
  120. package/dist/application-VxxP88FH.mjs.map +0 -1
  121. package/dist/bootstrap-CytCvAnr.d.mts.map +0 -1
  122. package/dist/context-CAN3t2jg.mjs +0 -12
  123. package/dist/context-CAN3t2jg.mjs.map +0 -1
  124. package/dist/csrf-MbsM7-58.mjs +0 -12
  125. package/dist/csrf-MbsM7-58.mjs.map +0 -1
  126. package/dist/error-handler-Cr6Yt9as.d.mts.map +0 -1
  127. package/dist/kv-stores-D2kSUAEP.d.mts.map +0 -1
  128. package/dist/kv-stores-VfJbg9Gs.mjs +0 -12
  129. package/dist/kv-stores-VfJbg9Gs.mjs.map +0 -1
  130. package/dist/request-logger-BU4ulKLp.d.mts.map +0 -1
  131. package/dist/spa-CCi-hC2M.d.mts +0 -97
  132. package/dist/spa-CCi-hC2M.d.mts.map +0 -1
  133. package/dist/views-3TYTcdyF.mjs +0 -12
  134. package/dist/views-3TYTcdyF.mjs.map +0 -1
  135. package/dist/views-BBY9_PUV.d.mts.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.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{r as registerDisposable}from"../../disposables-QYOU5_Eg.mjs";import{createHmac,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=new Map;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),null):entry.data:null}async set(sid,data,maxAge){this.sessions.set(sid,{data,expires:Date.now()+maxAge})}async destroy(sid){this.sessions.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge)}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&this.sessions.delete(sid)}};function parseCookieHeader(header){let out={};for(let pair of header.split(`;`)){let eq=pair.indexOf(`=`);if(eq===-1)continue;let key=pair.slice(0,eq).trim();if(!key)continue;let value=pair.slice(eq+1).trim();value.startsWith(`"`)&&value.endsWith(`"`)&&(value=value.slice(1,-1));try{out[key]=decodeURIComponent(value)}catch{out[key]=value}}return out}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secret){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),providedSig=raw.slice(dotIndex+1),expectedSig=createHmac(`sha256`,secret).update(value).digest(`base64url`),a=Buffer.from(providedSig),b=Buffer.from(expectedSig);return a.length!==b.length||!timingSafeEqual(a,b)?!1:value}function session(options){let{secret,cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,store=new MemoryStore,cookie:cookieOpts={}}=options,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??process.env.NODE_ENV===`production`,sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1;signedCookie&&(sid=unsign(signedCookie,secret),sid&&(sessionData=await store.get(sid))),(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),res.cookie(cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,res.clearCookie(cookieName,{path:cookieDefaults.path})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&res.cookie(cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||isNew&&!saveUninitialized&&Object.keys(currentData).length===0||(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),rolling&&!isNew&&res.cookie(cookieName,sign(currentSid,secret),cookieDefaults),next()}}export{session};
11
+ import{r as registerDisposable}from"../../disposables-0gJffTe_.mjs";import{createHmac,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=new Map;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),null):entry.data:null}async set(sid,data,maxAge){this.sessions.set(sid,{data,expires:Date.now()+maxAge})}async destroy(sid){this.sessions.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge)}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&this.sessions.delete(sid)}};function parseCookieHeader(header){let out={};for(let pair of header.split(`;`)){let eq=pair.indexOf(`=`);if(eq===-1)continue;let key=pair.slice(0,eq).trim();if(!key)continue;let value=pair.slice(eq+1).trim();value.startsWith(`"`)&&value.endsWith(`"`)&&(value=value.slice(1,-1));try{out[key]=decodeURIComponent(value)}catch{out[key]=value}}return out}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secret){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),providedSig=raw.slice(dotIndex+1),expectedSig=createHmac(`sha256`,secret).update(value).digest(`base64url`),a=Buffer.from(providedSig),b=Buffer.from(expectedSig);return a.length!==b.length||!timingSafeEqual(a,b)?!1:value}function session(options){let{secret,cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,store=new MemoryStore,cookie:cookieOpts={}}=options,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??process.env.NODE_ENV===`production`,sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1;signedCookie&&(sid=unsign(signedCookie,secret),sid&&(sessionData=await store.get(sid))),(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),res.cookie(cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,res.clearCookie(cookieName,{path:cookieDefaults.path})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&res.cookie(cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||isNew&&!saveUninitialized&&Object.keys(currentData).length===0||(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),rolling&&!isNew&&res.cookie(cookieName,sign(currentSid,secret),cookieDefaults),next()}}export{session};
12
12
  //# sourceMappingURL=session.mjs.map
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as SpaAdapterOptions, t as SpaAdapter } from "../../spa-CCi-hC2M.mjs";
3
- export { SpaAdapter, SpaAdapterOptions };
2
+ import { n as SpaAdapterOptions, r as resolveClientDir, t as SpaAdapter } from "../../spa-CDQ74RGA.mjs";
3
+ export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.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{c as __require}from"../../env-DPEhlEC4.mjs";import{Logger}from"../../core/logger.mjs";import"../../core-DW5uoNhO.mjs";import{existsSync,readFileSync}from"node:fs";import{join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);var SpaAdapter=class{options;name=`SpaAdapter`;clientDir;apiPrefixes;excludePaths;cacheControl;indexCacheControl;indexHtml=null;constructor(options={}){this.options=options,this.clientDir=resolve(options.clientDir??`dist/client`),this.excludePaths=options.exclude??[],this.cacheControl=options.cacheControl??`public, max-age=31536000, immutable`,this.indexCacheControl=options.indexCacheControl??`no-cache`;let prefix=options.apiPrefix??`/api`;this.apiPrefixes=Array.isArray(prefix)?prefix:[prefix]}beforeMount({app}){if(!existsSync(this.clientDir)){log.warn(`SPA client directory not found: ${this.clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path.`);return}let indexPath=join(this.clientDir,`index.html`);if(existsSync(indexPath))this.indexHtml=readFileSync(indexPath,`utf-8`);else{log.warn(`index.html not found in ${this.clientDir}`);return}try{let express=__require(`express`),staticOpts={};this.cacheControl&&(staticOpts.setHeaders=(res,filePath)=>{filePath.endsWith(`.html`)?res.setHeader(`Cache-Control`,this.indexCacheControl):res.setHeader(`Cache-Control`,this.cacheControl)}),app.use(express.static(this.clientDir,staticOpts))}catch{log.error(`express.static not available — SPA static file serving disabled`);return}log.debug(`Serving SPA from ${this.clientDir}`)}beforeStart({app}){this.indexHtml&&app.use((req,res,next)=>{for(let prefix of this.apiPrefixes)if(req.path.startsWith(prefix))return next();for(let path of this.excludePaths)if(req.path.startsWith(path))return next();if(req.path.includes(`.`)||req.method!==`GET`)return next();res.setHeader(`Content-Type`,`text/html`),res.setHeader(`Cache-Control`,this.indexCacheControl),res.send(this.indexHtml)})}};export{SpaAdapter};
11
+ import{Logger}from"../../core/logger.mjs";import"../../core-MI5Y1nGg.mjs";import{t as defineAdapter}from"../../define-adapter-Cz-bj4Xk.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=new Set;function snapshotClientDir(){let paths=new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);if(!existsSync(indexPath)){log.warn(`index.html not found in ${clientDir}`);return}indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
12
12
  //# sourceMappingURL=spa.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"spa.mjs","names":[],"sources":["../../../src/http/middleware/spa.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve, join } from 'node:path'\nimport { Logger, type AppAdapter, type AdapterContext } from '../../core'\n\nconst log = Logger.for('SpaAdapter')\n\nexport interface SpaAdapterOptions {\n /**\n * Directory containing the built SPA files (index.html, assets, etc.)\n * Default: 'dist/client'\n *\n * @example\n * ```ts\n * // Vue: 'dist'\n * // React (Vite): 'dist'\n * // React (CRA): 'build'\n * // Svelte: 'build'\n * // Angular: 'dist/my-app/browser'\n * ```\n */\n clientDir?: string\n\n /**\n * URL prefix for API routes. SPA fallback only applies to\n * non-API routes (routes NOT starting with this prefix).\n * Default: '/api'\n *\n * Set to an array for multiple prefixes:\n * ```ts\n * apiPrefix: ['/api', '/graphql', '/_debug']\n * ```\n */\n apiPrefix?: string | string[]\n\n /**\n * Additional paths to exclude from SPA fallback.\n * These paths will NOT serve index.html.\n *\n * @example\n * ```ts\n * exclude: ['/health', '/metrics', '/ws']\n * ```\n */\n exclude?: string[]\n\n /**\n * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')\n * Set to false to disable caching headers.\n */\n cacheControl?: string | false\n\n /**\n * Cache-Control for index.html (default: 'no-cache')\n * index.html should not be cached to ensure clients get fresh builds.\n */\n indexCacheControl?: string\n}\n\n/**\n * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside\n * your KickJS API. API routes are handled by controllers; everything else\n * falls back to index.html for client-side routing.\n *\n * @example\n * ```ts\n * import { SpaAdapter } from '@forinda/kickjs/spa'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * new SpaAdapter({\n * clientDir: 'dist/client', // or 'build', 'dist', etc.\n * apiPrefix: '/api',\n * }),\n * ],\n * })\n * ```\n *\n * File structure:\n * ```\n * dist/\n * client/ ← SPA build output\n * index.html\n * assets/\n * app.js\n * style.css\n * server/ ← KickJS server\n * ```\n */\nexport class SpaAdapter implements AppAdapter {\n name = 'SpaAdapter'\n private clientDir: string\n private apiPrefixes: string[]\n private excludePaths: string[]\n private cacheControl: string | false\n private indexCacheControl: string\n private indexHtml: string | null = null\n\n constructor(private options: SpaAdapterOptions = {}) {\n this.clientDir = resolve(options.clientDir ?? 'dist/client')\n this.excludePaths = options.exclude ?? []\n this.cacheControl = options.cacheControl ?? 'public, max-age=31536000, immutable'\n this.indexCacheControl = options.indexCacheControl ?? 'no-cache'\n\n const prefix = options.apiPrefix ?? '/api'\n this.apiPrefixes = Array.isArray(prefix) ? prefix : [prefix]\n }\n\n beforeMount({ app }: AdapterContext): void {\n if (!existsSync(this.clientDir)) {\n log.warn(`SPA client directory not found: ${this.clientDir}`)\n log.warn('Build your frontend first, or set clientDir to the correct path.')\n return\n }\n\n // Read index.html into memory\n const indexPath = join(this.clientDir, 'index.html')\n if (existsSync(indexPath)) {\n this.indexHtml = readFileSync(indexPath, 'utf-8')\n } else {\n log.warn(`index.html not found in ${this.clientDir}`)\n return\n }\n\n // Serve static files with cache headers\n try {\n // Dynamic import to avoid hard dependency on express.static\n const express = require('express')\n const staticOpts: any = {}\n\n if (this.cacheControl) {\n staticOpts.setHeaders = (res: any, filePath: string) => {\n if (filePath.endsWith('.html')) {\n res.setHeader('Cache-Control', this.indexCacheControl)\n } else {\n res.setHeader('Cache-Control', this.cacheControl as string)\n }\n }\n }\n\n app.use(express.static(this.clientDir, staticOpts))\n } catch {\n log.error('express.static not available — SPA static file serving disabled')\n return\n }\n\n log.debug(`Serving SPA from ${this.clientDir}`)\n }\n\n beforeStart({ app }: AdapterContext): void {\n if (!this.indexHtml) return\n\n // SPA fallback: serve index.html for all non-API, non-file routes\n app.use((req: any, res: any, next: any) => {\n // Skip API routes\n for (const prefix of this.apiPrefixes) {\n if (req.path.startsWith(prefix)) return next()\n }\n\n // Skip excluded paths\n for (const path of this.excludePaths) {\n if (req.path.startsWith(path)) return next()\n }\n\n // Skip requests for files (have an extension)\n if (req.path.includes('.')) return next()\n\n // Skip non-GET requests\n if (req.method !== 'GET') return next()\n\n // Serve index.html\n res.setHeader('Content-Type', 'text/html')\n res.setHeader('Cache-Control', this.indexCacheControl)\n res.send(this.indexHtml)\n })\n }\n}\n"],"mappings":";;;;;;;;;;8MAIA,MAAM,IAAM,OAAO,IAAI,YAAY,EAqFnC,IAAa,WAAb,KAA8C,CASxB,QARpB,KAAO,aACP,UACA,YACA,aACA,aACA,kBACA,UAAmC,KAEnC,YAAY,QAAqC,CAAC,EAAG,CAAjC,KAAA,QAAA,QAClB,KAAK,UAAY,QAAQ,QAAQ,WAAa,aAAa,EAC3D,KAAK,aAAe,QAAQ,SAAW,CAAC,EACxC,KAAK,aAAe,QAAQ,cAAgB,sCAC5C,KAAK,kBAAoB,QAAQ,mBAAqB,WAEtD,IAAM,OAAS,QAAQ,WAAa,OACpC,KAAK,YAAc,MAAM,QAAQ,MAAM,EAAI,OAAS,CAAC,MAAM,CAC7D,CAEA,YAAY,CAAE,KAA6B,CACzC,GAAI,CAAC,WAAW,KAAK,SAAS,EAAG,CAC/B,IAAI,KAAK,mCAAmC,KAAK,WAAW,EAC5D,IAAI,KAAK,kEAAkE,EAC3E,MACF,CAGA,IAAM,UAAY,KAAK,KAAK,UAAW,YAAY,EACnD,GAAI,WAAW,SAAS,EACtB,KAAK,UAAY,aAAa,UAAW,OAAO,MAC3C,CACL,IAAI,KAAK,2BAA2B,KAAK,WAAW,EACpD,MACF,CAGA,GAAI,CAEF,IAAM,QAAA,UAAkB,SAAS,EAC3B,WAAkB,CAAC,EAErB,KAAK,eACP,WAAW,YAAc,IAAU,WAAqB,CAClD,SAAS,SAAS,OAAO,EAC3B,IAAI,UAAU,gBAAiB,KAAK,iBAAiB,EAErD,IAAI,UAAU,gBAAiB,KAAK,YAAsB,CAE9D,GAGF,IAAI,IAAI,QAAQ,OAAO,KAAK,UAAW,UAAU,CAAC,CACpD,MAAQ,CACN,IAAI,MAAM,iEAAiE,EAC3E,MACF,CAEA,IAAI,MAAM,oBAAoB,KAAK,WAAW,CAChD,CAEA,YAAY,CAAE,KAA6B,CACpC,KAAK,WAGV,IAAI,KAAK,IAAU,IAAU,OAAc,CAEzC,IAAK,IAAM,UAAU,KAAK,YACxB,GAAI,IAAI,KAAK,WAAW,MAAM,EAAG,OAAO,KAAK,EAI/C,IAAK,IAAM,QAAQ,KAAK,aACtB,GAAI,IAAI,KAAK,WAAW,IAAI,EAAG,OAAO,KAAK,EAO7C,GAHI,IAAI,KAAK,SAAS,GAAG,GAGrB,IAAI,SAAW,MAAO,OAAO,KAAK,EAGtC,IAAI,UAAU,eAAgB,WAAW,EACzC,IAAI,UAAU,gBAAiB,KAAK,iBAAiB,EACrD,IAAI,KAAK,KAAK,SAAS,CACzB,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"spa.mjs","names":[],"sources":["../../../src/http/middleware/spa.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { resolve, join, dirname, isAbsolute } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\nimport type { ConnectMiddleware } from '../runtime'\n\nconst log = Logger.for('SpaAdapter')\n\nexport interface SpaAdapterOptions {\n /**\n * Directory containing the built SPA files (index.html, assets, etc.)\n * Default: 'dist/client'\n *\n * @example\n * ```ts\n * // Vue: 'dist'\n * // React (Vite): 'dist'\n * // React (CRA): 'build'\n * // Svelte: 'build'\n * // Angular: 'dist/my-app/browser'\n * ```\n */\n clientDir?: string\n\n /**\n * URL prefix for API routes. SPA fallback only applies to\n * non-API routes (routes NOT starting with this prefix).\n * Default: '/api'\n *\n * Matching is segment-aware: `/api` excludes `/api` and `/api/users`, but\n * NOT `/apidocs` — a plain `startsWith` swallowed any path that merely\n * began with the same letters.\n *\n * Set to an array for multiple prefixes:\n * ```ts\n * apiPrefix: ['/api', '/graphql', '/_debug']\n * ```\n */\n apiPrefix?: string | string[]\n\n /**\n * Additional paths to exclude from SPA fallback.\n * These paths will NOT serve index.html. Segment-aware, like `apiPrefix`.\n *\n * @example\n * ```ts\n * exclude: ['/health', '/metrics', '/ws']\n * ```\n */\n exclude?: string[]\n\n /**\n * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')\n * Set to false to disable caching headers.\n */\n cacheControl?: string | false\n\n /**\n * Cache-Control for index.html (default: 'no-cache')\n * index.html should not be cached to ensure clients get fresh builds.\n */\n indexCacheControl?: string\n\n /**\n * Serve index.html even when the client did not ask for HTML.\n * Default: false.\n *\n * By default the fallback only fires for requests whose `Accept` header\n * includes `text/html` — the rule `connect-history-api-fallback` uses. That\n * keeps a missing `/assets/app.js` a 404 instead of handing back an HTML\n * document that the browser then fails to parse as JavaScript, which is a\n * confusing way to discover a broken build.\n *\n * Turn this on if you have non-browser clients that deep-link into SPA\n * routes without an `Accept` header.\n */\n alwaysFallback?: boolean\n}\n\n/**\n * Nearest directory at or above `from` that holds a `package.json`.\n * `null` when the walk reaches the filesystem root without finding one.\n */\nfunction nearestPackageRoot(from: string): string | null {\n let dir = from\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Where to look for the built SPA.\n *\n * `process.cwd()` is the framework's convention (assets and env files resolve\n * the same way) and stays the primary base. But a relative `clientDir` then\n * only works when the process happens to be started from the app directory —\n * `node server/dist/index.js` run from a monorepo root resolved `../web/dist`\n * against the root and found nothing, serving no SPA with only a warning.\n *\n * So: try cwd first, and only if that misses, retry against the package root\n * of the entry script. Both are checked for existence before being chosen, so\n * this can never silently pick a directory that is not there — a genuinely\n * missing build still lands on the cwd path, which is what the warning names.\n *\n * Deliberately not entry-relative FIRST: under `kick dev` the entry is the CLI\n * binary, whose package root is the CLI itself.\n *\n * Exported for tests only — not re-exported from the package index.\n */\nexport function resolveClientDir(\n clientDir: string,\n // Injected rather than read from the process so tests can exercise the\n // monorepo-root case without `process.chdir` / `process.argv` mutation —\n // neither is supported under vitest's `threads` pool, and the root config\n // uses exactly that.\n cwd: string = process.cwd(),\n entry: string | undefined = process.argv[1],\n): string {\n // `resolve` even for an already-absolute path: `resolvesToFile` compares its\n // (always normalized) target against this string, so a trailing slash or a\n // `.`/`..` segment here would make the containment check never match and\n // silently drop the Cache-Control header on every request. Fails closed, so\n // it never weakened the traversal guard — it just stopped doing its job.\n if (isAbsolute(clientDir)) return resolve(clientDir)\n const fromCwd = resolve(cwd, clientDir)\n if (existsSync(fromCwd)) return fromCwd\n\n if (entry) {\n const root = nearestPackageRoot(dirname(resolve(entry)))\n if (root) {\n const fromEntry = resolve(root, clientDir)\n if (existsSync(fromEntry)) return fromEntry\n }\n }\n return fromCwd\n}\n\n/**\n * The slice of the request/response this adapter touches, spelled from the\n * node `http` shapes rather than Express's. `ConnectMiddleware` is typed as\n * Express's `RequestHandler`, but under Fastify and h3 these handlers receive\n * the raw node objects (or a driver), so relying on `req.path` / `res.send`\n * is what made the previous version Express-only.\n */\ninterface SpaRequest {\n url?: string\n method?: string\n headers?: Record<string, string | string[] | undefined>\n}\n\ninterface SpaResponse {\n setHeader(name: string, value: string): void\n statusCode: number\n end(chunk?: string): void\n}\n\ntype SpaHandler = (req: SpaRequest, res: SpaResponse, next: () => void) => void\n\n/** Pathname only — `req.url` carries the query string, and `req.path` is Express-only. */\nfunction pathnameOf(url: string | undefined): string {\n if (!url) return '/'\n const q = url.indexOf('?')\n const h = url.indexOf('#')\n const end = Math.min(q === -1 ? url.length : q, h === -1 ? url.length : h)\n return url.slice(0, end) || '/'\n}\n\n/**\n * Segment-aware prefix test: `/api` covers `/api` and `/api/users`, not\n * `/apidocs`. `startsWith` alone made any same-prefixed route disappear from\n * the SPA fallback and 404 instead.\n */\nfunction isUnder(pathname: string, prefix: string): boolean {\n if (!prefix || prefix === '/') return true\n const p = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix\n return pathname === p || pathname.startsWith(`${p}/`)\n}\n\n/** Media ranges that count as \"the client wants a document\". */\nconst HTML_TYPES = ['text/html', 'application/xhtml+xml']\n\n/** `q` for a media range, defaulting to 1 when absent or unparseable. */\nfunction qualityOf(params: string[]): number {\n const q = params.find((param) => param.startsWith('q='))\n if (!q) return 1\n const value = Number.parseFloat(q.slice(2))\n return Number.isNaN(value) ? 1 : value\n}\n\n/**\n * Does the client want an HTML document back?\n *\n * Parses media ranges with q-values rather than substring-matching:\n * `Accept: text/html;q=0` explicitly says HTML is NOT acceptable (RFC 9110\n * §12.5.1 — \"a value of 0 means not acceptable\"), and a substring check read\n * that as a yes and returned the document anyway.\n *\n * Wildcards are matched by specificity, as RFC 9110 §12.5.1 requires: an exact\n * `text/html` beats `text/*`, so `Accept: text/*, text/html;q=0` correctly\n * rejects HTML even though the wildcard would have accepted it.\n *\n * A bare `*` / `*` deliberately does NOT count, at any q. Assets are fetched\n * with `Accept: * / *`, and treating that as a document request is what makes\n * a missing script come back as HTML — the very thing the fallback rules\n * exist to prevent.\n */\nfunction acceptsHtml(accept: string | string[] | undefined): boolean {\n const raw = Array.isArray(accept) ? accept.join(',') : (accept ?? '')\n if (!raw) return false\n\n const ranges = raw\n .split(',')\n .map((part) => part.split(';').map((t) => t.trim().toLowerCase()))\n .filter(([type]) => Boolean(type))\n\n return HTML_TYPES.some((htmlType) => {\n const [group] = htmlType.split('/')\n // Most specific match wins: exact type, else `type/*`. `*/*` is skipped.\n const exact = ranges.find(([type]) => type === htmlType)\n const wildcard = ranges.find(([type]) => type === `${group}/*`)\n const match = exact ?? wildcard\n return match ? qualityOf(match.slice(1)) > 0 : false\n })\n}\n\n/**\n * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside\n * your KickJS API. API routes are handled by controllers; everything else\n * falls back to index.html for client-side routing.\n *\n * Written against the engine-agnostic `http` surface (`serveStatic` / `use`),\n * so it runs under Express, Fastify, and h3 alike. The previous version\n * reached for `express.static`, `req.path`, and `res.send`, all of which are\n * Express-only — it silently served nothing on the other runtimes.\n *\n * Migrated to the `defineAdapter()` factory — call without `new`, as\n * `ViewAdapter` has since v4.\n *\n * @example\n * ```ts\n * import { SpaAdapter } from '@forinda/kickjs/spa'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * SpaAdapter({\n * clientDir: 'dist/client', // or 'build', 'dist', etc.\n * apiPrefix: '/api',\n * }),\n * ],\n * })\n * ```\n *\n * File structure:\n * ```\n * dist/\n * client/ ← SPA build output\n * index.html\n * assets/\n * app.js\n * style.css\n * server/ ← KickJS server\n * ```\n */\nexport const SpaAdapter = defineAdapter<SpaAdapterOptions>({\n name: 'SpaAdapter',\n defaults: {\n clientDir: 'dist/client',\n apiPrefix: '/api',\n exclude: [],\n cacheControl: 'public, max-age=31536000, immutable',\n indexCacheControl: 'no-cache',\n alwaysFallback: false,\n },\n build: (config) => {\n const clientDir = resolveClientDir(config.clientDir ?? 'dist/client')\n const rawPrefix = config.apiPrefix ?? '/api'\n const apiPrefixes = Array.isArray(rawPrefix) ? rawPrefix : [rawPrefix]\n const excludePaths = config.exclude ?? []\n const cacheControl = config.cacheControl ?? 'public, max-age=31536000, immutable'\n const indexCacheControl = config.indexCacheControl ?? 'no-cache'\n const alwaysFallback = config.alwaysFallback ?? false\n\n let indexHtml: string | null = null\n\n /**\n * Every file in the build, as request paths (`/assets/app.js`), captured\n * once at mount.\n *\n * This used to be a `statSync` per request. That is a synchronous\n * filesystem call on the hot path of every non-reserved request, and a\n * slow or contended disk blocks the event loop for unrelated requests.\n * The directory is a static build — its contents are already snapshotted\n * at boot, since `index.html` is read into memory there — so the lookup\n * belongs in memory too. No filesystem access remains in the request path.\n *\n * A build added to after boot is not picked up, which is the same\n * contract `index.html` already had.\n */\n let assetPaths: ReadonlySet<string> = new Set()\n\n function snapshotClientDir(): ReadonlySet<string> {\n const paths = new Set<string>()\n // A hand-rolled walk rather than `readdirSync(dir, { recursive: true })`\n // with `Dirent.parentPath`. Both are newer than the package's declared\n // `node >=20.0`: the `recursive` option landed in 20.1, `parentPath` in\n // 20.12, and the older `Dirent.path` alias it replaced is already gone\n // on Node 24 — so no single spelling covers the supported range. The\n // failure would have been silent, too: the surrounding `catch` turns a\n // `TypeError` from `join(undefined, name)` into an empty snapshot, which\n // reads as \"no files\" and drops every Cache-Control header.\n //\n // `readdirSync(dir, { withFileTypes: true })` is ancient and stable, and\n // tracking the parent ourselves needs no new API.\n const walk = (absDir: string, prefix: string): void => {\n for (const entry of readdirSync(absDir, { withFileTypes: true })) {\n const child = `${prefix}/${entry.name}`\n // Symlinks report as neither file nor directory here (readdir does\n // not follow them), so a symlinked tree is skipped rather than\n // risking a cycle. A symlinked asset simply goes unlabelled — the\n // static layer still serves it, it just misses the cache header.\n if (entry.isDirectory()) walk(join(absDir, entry.name), child)\n else if (entry.isFile()) paths.add(child)\n }\n }\n try {\n walk(clientDir, '')\n } catch {\n // Unreadable build directory — fall back to labelling nothing rather\n // than failing the boot. Serving still works; caching just opts out.\n return new Set()\n }\n return paths\n }\n\n /**\n * How the static layer will answer this path: as the index document, as a\n * long-lived asset, or not at all.\n *\n * Membership of the snapshot IS the containment guard — a traversal like\n * `/../../etc/passwd` simply is not a key — so no prefix comparison is\n * needed and the whole check is one `Set.has`.\n */\n const classifyPath = (pathname: string): 'file' | 'index' | null => {\n let decoded: string\n try {\n decoded = decodeURIComponent(pathname)\n } catch {\n return null\n }\n if (decoded.includes('\\0')) return null\n\n // A directory is served from its `index.html`, so `/` — the single most\n // common request — is an index request, not an asset. Reporting it as\n // neither left the root document without the configured policy.\n const asIndex = decoded.endsWith('/') ? `${decoded}index.html` : null\n if (asIndex && assetPaths.has(asIndex)) return 'index'\n if (!assetPaths.has(decoded)) return null\n return decoded.endsWith('.html') ? 'index' : 'file'\n }\n\n /** Skipped by the fallback: API routes, opted-out paths. */\n const isReserved = (pathname: string): boolean =>\n apiPrefixes.some((p) => isUnder(pathname, p)) ||\n excludePaths.some((p) => isUnder(pathname, p))\n\n return {\n beforeMount({ http }) {\n if (!existsSync(clientDir)) {\n log.warn(`SPA client directory not found: ${clientDir}`)\n log.warn(\n `Build your frontend first, or set clientDir to the correct path ` +\n `(relative paths resolve from ${process.cwd()}).`,\n )\n return\n }\n\n const indexPath = join(clientDir, 'index.html')\n if (!existsSync(indexPath)) {\n log.warn(`index.html not found in ${clientDir}`)\n return\n }\n indexHtml = readFileSync(indexPath, 'utf-8')\n assetPaths = snapshotClientDir()\n\n // Cache-Control runs as its own middleware ahead of the static\n // handler: the engine-agnostic `serveStatic` takes no header hook,\n // and headers set before the static layer writes still land on the\n // response. Keyed off the request path rather than the resolved file,\n // which is the same decision `express.static`'s `setHeaders` made.\n if (cacheControl !== false) {\n http.use(((req, res, next) => {\n const pathname = pathnameOf(req.url)\n // Only label a response the static layer will actually serve.\n // `express.static`'s `setHeaders` fired on hits only; running as\n // a separate middleware loses that, and an unconditional header\n // put `immutable, max-age=31536000` on the 404 for a missing\n // asset — telling every cache to keep that miss for a year.\n const kind = isReserved(pathname) ? null : classifyPath(pathname)\n if (kind) {\n res.setHeader('Cache-Control', kind === 'index' ? indexCacheControl : cacheControl)\n }\n next()\n }) satisfies SpaHandler as unknown as ConnectMiddleware)\n }\n\n http.serveStatic('/', clientDir)\n log.debug(`Serving SPA from ${clientDir}`)\n },\n\n beforeStart({ http }) {\n if (!indexHtml) return\n\n http.use(((req, res, next) => {\n // GET and HEAD both navigate. HEAD used to fall through to a 404,\n // which broke proxies and link checkers probing SPA routes.\n const method = (req.method ?? 'GET').toUpperCase()\n if (method !== 'GET' && method !== 'HEAD') return next()\n\n const pathname = pathnameOf(req.url)\n if (isReserved(pathname)) return next()\n\n // Content negotiation instead of a \"does the path contain a dot\"\n // guess. The old heuristic 404'd every legitimate route carrying a\n // dot (`/users/john.doe`, `/v1.2/spec`) while still handing HTML to\n // genuinely missing assets whose path had no extension.\n const accept = req.headers?.['accept'] as string | string[] | undefined\n if (!alwaysFallback && !acceptsHtml(accept)) return next()\n\n const body = indexHtml as string\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Cache-Control', indexCacheControl)\n res.setHeader('Content-Length', String(Buffer.byteLength(body)))\n res.statusCode = 200\n // HEAD must carry identical headers and no body.\n res.end(method === 'HEAD' ? undefined : body)\n }) satisfies SpaHandler as unknown as ConnectMiddleware)\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;4PAKA,MAAM,IAAM,OAAO,IAAI,YAAY,EA6EnC,SAAS,mBAAmB,KAA6B,CACvD,IAAI,IAAM,KACV,OAAS,CACP,GAAI,WAAW,KAAK,IAAK,cAAc,CAAC,EAAG,OAAO,IAClD,IAAM,OAAS,QAAQ,GAAG,EAC1B,GAAI,SAAW,IAAK,OAAO,KAC3B,IAAM,MACR,CACF,CAqBA,SAAgB,iBACd,UAKA,IAAc,QAAQ,IAAI,EAC1B,MAA4B,QAAQ,KAAK,GACjC,CAMR,GAAI,WAAW,SAAS,EAAG,OAAO,QAAQ,SAAS,EACnD,IAAM,QAAU,QAAQ,IAAK,SAAS,EACtC,GAAI,WAAW,OAAO,EAAG,OAAO,QAEhC,GAAI,MAAO,CACT,IAAM,KAAO,mBAAmB,QAAQ,QAAQ,KAAK,CAAC,CAAC,EACvD,GAAI,KAAM,CACR,IAAM,UAAY,QAAQ,KAAM,SAAS,EACzC,GAAI,WAAW,SAAS,EAAG,OAAO,SACpC,CACF,CACA,OAAO,OACT,CAwBA,SAAS,WAAW,IAAiC,CACnD,GAAI,CAAC,IAAK,MAAO,IACjB,IAAM,EAAI,IAAI,QAAQ,GAAG,EACnB,EAAI,IAAI,QAAQ,GAAG,EACnB,IAAM,KAAK,IAAI,IAAM,GAAK,IAAI,OAAS,EAAG,IAAM,GAAK,IAAI,OAAS,CAAC,EACzE,OAAO,IAAI,MAAM,EAAG,GAAG,GAAK,GAC9B,CAOA,SAAS,QAAQ,SAAkB,OAAyB,CAC1D,GAAI,CAAC,QAAU,SAAW,IAAK,MAAO,GACtC,IAAM,EAAI,OAAO,SAAS,GAAG,EAAI,OAAO,MAAM,EAAG,EAAE,EAAI,OACvD,OAAO,WAAa,GAAK,SAAS,WAAW,GAAG,EAAE,EAAE,CACtD,CAGA,MAAM,WAAa,CAAC,YAAa,uBAAuB,EAGxD,SAAS,UAAU,OAA0B,CAC3C,IAAM,EAAI,OAAO,KAAM,OAAU,MAAM,WAAW,IAAI,CAAC,EACvD,GAAI,CAAC,EAAG,MAAO,GACf,IAAM,MAAQ,OAAO,WAAW,EAAE,MAAM,CAAC,CAAC,EAC1C,OAAO,OAAO,MAAM,KAAK,EAAI,EAAI,KACnC,CAmBA,SAAS,YAAY,OAAgD,CACnE,IAAM,IAAM,MAAM,QAAQ,MAAM,EAAI,OAAO,KAAK,GAAG,EAAK,QAAU,GAClE,GAAI,CAAC,IAAK,MAAO,GAEjB,IAAM,OAAS,IACZ,MAAM,GAAG,CAAC,CACV,IAAK,MAAS,KAAK,MAAM,GAAG,CAAC,CAAC,IAAK,GAAM,EAAE,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CACjE,QAAQ,CAAC,QAAU,EAAQ,IAAK,EAEnC,OAAO,WAAW,KAAM,UAAa,CACnC,GAAM,CAAC,OAAS,SAAS,MAAM,GAAG,EAE5B,MAAQ,OAAO,MAAM,CAAC,QAAU,OAAS,QAAQ,EACjD,SAAW,OAAO,MAAM,CAAC,QAAU,OAAS,GAAG,MAAM,GAAG,EACxD,MAAQ,OAAS,SACvB,OAAO,MAAQ,UAAU,MAAM,MAAM,CAAC,CAAC,EAAI,EAAI,EACjD,CAAC,CACH,CAyCA,MAAa,WAAa,cAAiC,CACzD,KAAM,aACN,SAAU,CACR,UAAW,cACX,UAAW,OACX,QAAS,CAAC,EACV,aAAc,sCACd,kBAAmB,WACnB,eAAgB,EAClB,EACA,MAAQ,QAAW,CACjB,IAAM,UAAY,iBAAiB,OAAO,WAAa,aAAa,EAC9D,UAAY,OAAO,WAAa,OAChC,YAAc,MAAM,QAAQ,SAAS,EAAI,UAAY,CAAC,SAAS,EAC/D,aAAe,OAAO,SAAW,CAAC,EAClC,aAAe,OAAO,cAAgB,sCACtC,kBAAoB,OAAO,mBAAqB,WAChD,eAAiB,OAAO,gBAAkB,GAE5C,UAA2B,KAgB3B,WAAkC,IAAI,IAE1C,SAAS,mBAAyC,CAChD,IAAM,MAAQ,IAAI,IAYZ,MAAQ,OAAgB,SAAyB,CACrD,IAAK,IAAM,SAAS,YAAY,OAAQ,CAAE,cAAe,EAAK,CAAC,EAAG,CAChE,IAAM,MAAQ,GAAG,OAAO,GAAG,MAAM,OAK7B,MAAM,YAAY,EAAG,KAAK,KAAK,OAAQ,MAAM,IAAI,EAAG,KAAK,EACpD,MAAM,OAAO,GAAG,MAAM,IAAI,KAAK,CAC1C,CACF,EACA,GAAI,CACF,KAAK,UAAW,EAAE,CACpB,MAAQ,CAGN,OAAO,IAAI,GACb,CACA,OAAO,KACT,CAUA,IAAM,aAAgB,UAA8C,CAClE,IAAI,QACJ,GAAI,CACF,QAAU,mBAAmB,QAAQ,CACvC,MAAQ,CACN,OAAO,IACT,CACA,GAAI,QAAQ,SAAS,IAAI,EAAG,OAAO,KAKnC,IAAM,QAAU,QAAQ,SAAS,GAAG,EAAI,GAAG,QAAQ,YAAc,KAGjE,OAFI,SAAW,WAAW,IAAI,OAAO,EAAU,QAC1C,WAAW,IAAI,OAAO,EACpB,QAAQ,SAAS,OAAO,EAAI,QAAU,OADR,IAEvC,EAGM,WAAc,UAClB,YAAY,KAAM,GAAM,QAAQ,SAAU,CAAC,CAAC,GAC5C,aAAa,KAAM,GAAM,QAAQ,SAAU,CAAC,CAAC,EAE/C,MAAO,CACL,YAAY,CAAE,MAAQ,CACpB,GAAI,CAAC,WAAW,SAAS,EAAG,CAC1B,IAAI,KAAK,mCAAmC,WAAW,EACvD,IAAI,KACF,gGACkC,QAAQ,IAAI,EAAE,GAClD,EACA,MACF,CAEA,IAAM,UAAY,KAAK,UAAW,YAAY,EAC9C,GAAI,CAAC,WAAW,SAAS,EAAG,CAC1B,IAAI,KAAK,2BAA2B,WAAW,EAC/C,MACF,CACA,UAAY,aAAa,UAAW,OAAO,EAC3C,WAAa,kBAAkB,EAO3B,eAAiB,IACnB,KAAK,MAAM,IAAK,IAAK,OAAS,CAC5B,IAAM,SAAW,WAAW,IAAI,GAAG,EAM7B,KAAO,WAAW,QAAQ,EAAI,KAAO,aAAa,QAAQ,EAC5D,MACF,IAAI,UAAU,gBAAiB,OAAS,QAAU,kBAAoB,YAAY,EAEpF,KAAK,CACP,EAAuD,EAGzD,KAAK,YAAY,IAAK,SAAS,EAC/B,IAAI,MAAM,oBAAoB,WAAW,CAC3C,EAEA,YAAY,CAAE,MAAQ,CACf,WAEL,KAAK,MAAM,IAAK,IAAK,OAAS,CAG5B,IAAM,QAAU,IAAI,QAAU,MAAA,CAAO,YAAY,EACjD,GAAI,SAAW,OAAS,SAAW,OAAQ,OAAO,KAAK,EAEvD,IAAM,SAAW,WAAW,IAAI,GAAG,EACnC,GAAI,WAAW,QAAQ,EAAG,OAAO,KAAK,EAMtC,IAAM,OAAS,IAAI,SAAU,OAC7B,GAAI,CAAC,gBAAkB,CAAC,YAAY,MAAM,EAAG,OAAO,KAAK,EAEzD,IAAM,KAAO,UACb,IAAI,UAAU,eAAgB,0BAA0B,EACxD,IAAI,UAAU,gBAAiB,iBAAiB,EAChD,IAAI,UAAU,iBAAkB,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,EAC/D,IAAI,WAAa,IAEjB,IAAI,IAAI,SAAW,OAAS,IAAA,GAAY,IAAI,CAC9C,EAAuD,CACzD,CACF,CACF,CACF,CAAC"}
@@ -1,3 +1,3 @@
1
1
 
2
- import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-Wck12jE5.mjs";
2
+ import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-CUtcjc-n.mjs";
3
3
  export { type RawUploadPart, UploadOptions, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-Dxr2BxTi.mjs";import{createRequire}from"node:module";import{unlink}from"node:fs/promises";const requireFromHere=createRequire(import.meta.url);let _multer;function loadMulter(){if(_multer)return _multer;try{return _multer=requireFromHere(`multer`),_multer}catch{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed.
11
+ import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-C9V9tIR3.mjs";import{createRequire}from"node:module";import{unlink}from"node:fs/promises";const requireFromHere=createRequire(import.meta.url);let _multer;function loadMulter(){if(_multer)return _multer;try{return _multer=requireFromHere(`multer`),_multer}catch{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed.
12
12
  Install it as a peer dependency: pnpm add multer (or npm i multer / yarn add multer).`)}}function createMulter(options){let limits={fileSize:options.maxSize??5*1024*1024},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(Error(`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}};return loadMulter()(multerOptions)}function single(fieldName,options={}){return createMulter(options).single(fieldName)}function array(fieldName,maxCount=10,options={}){return createMulter(options).array(fieldName,maxCount)}function none(options={}){return createMulter(options).none()}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
13
13
  //# sourceMappingURL=upload.mjs.map
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as ViewAdapterOptions, t as ViewAdapter } from "../../views-BBY9_PUV.mjs";
2
+ import { a as ViewAdapterOptions, i as ViewAdapter } from "../../spa-CDQ74RGA.mjs";
3
3
  export { ViewAdapter, ViewAdapterOptions };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as ViewAdapter}from"../../views-3TYTcdyF.mjs";export{ViewAdapter};
11
+ import{Logger}from"../../core/logger.mjs";import"../../core-MI5Y1nGg.mjs";import{t as defineAdapter}from"../../define-adapter-Cz-bj4Xk.mjs";import{resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app}){let{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,resolve(viewsDir)),log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)}})});export{ViewAdapter};
12
+ //# sourceMappingURL=views.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\n\nconst log = Logger.for('ViewEngine')\n\nexport interface ViewAdapterOptions {\n /**\n * Template engine — pass the engine module or a render function.\n * Supported engines: ejs, pug, handlebars, nunjucks, or any\n * Express-compatible engine with a __express property.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * ViewAdapter({ engine: ejs, ext: 'ejs' })\n *\n * import pug from 'pug'\n * ViewAdapter({ engine: pug, ext: 'pug' })\n * ```\n */\n engine: any\n\n /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */\n ext: string\n\n /** Directory containing template files (default: 'src/views') */\n viewsDir?: string\n\n /** Default layout template (optional — depends on engine) */\n layout?: string\n}\n\n/**\n * View/template adapter — pluggable template engine support for KickJS.\n *\n * Registers an Express view engine and sets the views directory.\n * Use `ctx.render()` in controllers to render templates.\n *\n * Migrated to the `defineAdapter()` factory in v4 — call without `new`.\n * The pre-v4 `new ViewAdapter({...})` form is gone; see\n * `docs/guide/migration-v3-to-v4.md` for the rename.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * import { ViewAdapter } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),\n * ],\n * })\n *\n * // In a controller:\n * @Get('/dashboard')\n * async dashboard(ctx: RequestContext) {\n * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })\n * }\n * ```\n */\nexport const ViewAdapter = defineAdapter<ViewAdapterOptions>({\n name: 'ViewAdapter',\n build: (options) => ({\n beforeMount({ app }) {\n const { engine, ext, viewsDir = 'src/views' } = options\n\n // Register the engine. Three resolution paths cover every\n // mainstream template engine + a fall-through for custom ones.\n if (engine.__express) {\n // EJS, Pug — have __express method\n app.engine(ext, engine.__express)\n } else if (typeof engine.renderFile === 'function') {\n // Engines with renderFile (nunjucks-style)\n app.engine(\n ext,\n (path: string, opts: any, callback: (err: Error | null, html?: string) => void) => {\n engine.renderFile(path, opts, callback)\n },\n )\n } else if (typeof engine === 'function') {\n // Custom render function: (path, options, callback) => void\n app.engine(ext, engine)\n } else {\n log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`)\n app.engine(ext, engine)\n }\n\n app.set('view engine', ext)\n app.set('views', resolve(viewsDir))\n\n log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)\n },\n }),\n})\n"],"mappings":";;;;;;;;;;2KAGA,MAAM,IAAM,OAAO,IAAI,YAAY,EA0DtB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,KAAO,CACnB,GAAM,CAAE,OAAQ,IAAK,SAAW,aAAgB,QAI5C,OAAO,UAET,IAAI,OAAO,IAAK,OAAO,SAAS,EACvB,OAAO,OAAO,YAAe,WAEtC,IAAI,OACF,KACC,KAAc,KAAW,WAAyD,CACjF,OAAO,WAAW,KAAM,KAAM,QAAQ,CACxC,CACF,GACS,OAAO,QAAW,YAI3B,IAAI,KAAK,eAAe,IAAI,sDAAsD,EAFlF,IAAI,OAAO,IAAK,MAAM,GAMxB,IAAI,IAAI,cAAe,GAAG,EAC1B,IAAI,IAAI,QAAS,QAAQ,QAAQ,CAAC,EAElC,IAAI,MAAM,gBAAgB,IAAI,IAAI,QAAQ,QAAQ,EAAE,EAAE,CACxD,CACF,EACF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"../../query-B_YnIZ2-.mjs";export{FILTER_OPERATORS,buildQueryParams,getQueryParsingDefaults,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,resetQueryParsingDefaults,setQueryParsingDefaults};
11
+ import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"../../query-BYUCKdu5.mjs";export{FILTER_OPERATORS,buildQueryParams,getQueryParsingDefaults,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,resetQueryParsingDefaults,setQueryParsingDefaults};
@@ -1,3 +1,3 @@
1
1
 
2
- import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-C6E11Grf.mjs";
2
+ import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-BYDUIiZW.mjs";
3
3
  export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"../router-builder-DtonR20n.mjs";export{_setExternalContributorSources,assertRouteUnique,buildRouteTable};
11
+ import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"../router-builder-Bv175XoR.mjs";export{_setExternalContributorSources,assertRouteUnique,buildRouteTable};
@@ -1,5 +1,5 @@
1
1
 
2
- import { f as HttpRuntime } from "../../adapter-diFqgxGR.mjs";
2
+ import { f as HttpRuntime } from "../../adapter-NstPNaFV.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/http/runtimes/fastify.d.ts
5
5
  interface FastifyReplyLike {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{i as requestStore,t as RequestContext}from"../../context-CAN3t2jg.mjs";import{a as disposeRequestStore,i as createRequestStore,t as applyHandlerResult}from"../../reply-Y50qUtDy.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-Dxr2BxTi.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),loadPeer=name=>{let mod=peerRequire(name);return mod&&mod.__esModule&&mod.default?mod.default:mod.default??mod},QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}setHeader(name,value){return this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.end(data),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
11
+ import{i as requestStore,t as RequestContext}from"../../context-DYOcPcg8.mjs";import{a as disposeRequestStore,i as createRequestStore,t as applyHandlerResult}from"../../reply-Bo950wuK.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-C9V9tIR3.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),loadPeer=name=>{let mod=peerRequire(name);return mod&&mod.__esModule&&mod.default?mod.default:mod.default??mod},QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}setHeader(name,value){return this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.end(data),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
12
12
  Install it as a peer dependency: pnpm add @fastify/multipart.`);let rawParts=[],fields={};for await(let part of request.parts())part.type===`file`&&part.toBuffer?rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer:await part.toBuffer()}):fields[part.fieldname]=part.value;let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...fields}}let headerId=raw.headers[`x-request-id`],store=createRequestStore((Array.isArray(headerId)?headerId[0]:headerId)||raw.requestId);raw.requestId=store.requestId,reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));validator&&await new Promise((resolve,reject)=>{validator(raw,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||reply.sent)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),reply.sent)return;let result=await entry.handler(ctx);reply.sent||applyHandlerResult(ctx,result)})}}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=loadPeer(`fastify`)({logger:!1,routerOptions:{ignoreTrailingSlash:!0},trustProxy:typeof options.trustProxy!=`function`&&options.trustProxy});return app[QUEUE]=[],app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=loadPeer(`@fastify/multipart`);await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=loadPeer(`@fastify/middie`);await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY];return(req,res,next)=>{next&&(req[NEXT]=next),readyP.then(()=>app.routing(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){let serveStatic=loadPeer(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];if(next){reply.hijack(),next();return}mw(request.raw,replyDriver(reply),NOOP_NEXT)})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{mw(err,request.raw,replyDriver(reply),NOOP_NEXT)})},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{fastifyRuntime};
13
13
  //# sourceMappingURL=fastify.mjs.map
@@ -1,5 +1,5 @@
1
1
 
2
- import { f as HttpRuntime } from "../../adapter-diFqgxGR.mjs";
2
+ import { f as HttpRuntime } from "../../adapter-NstPNaFV.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/http/runtimes/h3-web.d.ts
5
5
  interface H3AppLike {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{createLogger,describeError}from"../../core/logger.mjs";import{n as WebRequestShim,r as WebResponseDriver,t as compileWebRoute}from"../../handler-DcxBY95X.mjs";import{createRequire}from"node:module";const log=createLogger(`H3WebRuntime`),peerRequire=createRequire(import.meta.url),NOTFOUND_MW=Symbol(`kickjs.h3web.notFoundMw`),ERROR_MW=Symbol(`kickjs.h3web.errorMw`),ASSEMBLED=Symbol(`kickjs.h3web.assembled`),NOOP_NEXT=()=>{};function loadH3v2(injected){let m=injected??peerRequire(`h3`),resolved=m&&m.__esModule&&m.default?{...m.default,...m}:m;if(typeof resolved.H3!=`function`)throw Error("@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), but the installed h3 has no H3 class — that is the v1 line. Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.");return resolved}async function runConnectTerminal(mw,event,err){let req=new WebRequestShim(event.req,event.url),driver=new WebResponseDriver(event.req.signal);return mw&&(err===void 0?mw(req,driver,NOOP_NEXT):mw(err,req,driver,NOOP_NEXT)),driver.settled||(err===void 0?driver.status(404).json({error:`Not Found`}):(log.error(err,`h3-web: error handler did not settle the response — ${describeError(err)}`),driver.status(500).json({error:`Internal Server Error`,...typeof process<`u`&&process.env?.NODE_ENV===`production`?{}:{message:describeError(err)}}))),driver.ready}function h3WebRuntime(options={}){let{H3,toNodeHandler,fromNodeHandler}=loadH3v2(options.h3);return{name:`h3-web`,createApp(_options={}){let holder={},app=new H3({onError:(error,event)=>{let mw=holder.app?.[ERROR_MW];return runConnectTerminal(mw,event,error)}});return holder.app=app,app},nodeHandler(app){let state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,app.all(`/**`,event=>{let mw=state[NOTFOUND_MW];return runConnectTerminal(mw,event)}));let listener=toNodeHandler(app);return(req,res,next)=>{try{let result=listener(req,res);result&&typeof result.then==`function`&&result.catch(err=>next?.(err))}catch(err){next?.(err)}}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path),run=compileWebRoute(entry,{onError:async(err,req,driver)=>{let mw=app[ERROR_MW];mw&&mw(err,req,driver,NOOP_NEXT)}});app.on(entry.method,url,event=>run({request:event.req,url:event.url,params:event.context.params??{}}))}},useConnect(app,mw,opts){let handler=fromNodeHandler(mw);opts?.path===void 0?app.use(handler):app.use(joinPath(String(opts.path),`/**`),handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3WebRuntime};
11
+ import{createLogger,describeError}from"../../core/logger.mjs";import{n as WebRequestShim,r as WebResponseDriver,t as compileWebRoute}from"../../handler-mLCYXfTQ.mjs";import{createRequire}from"node:module";const log=createLogger(`H3WebRuntime`),peerRequire=createRequire(import.meta.url),NOTFOUND_MW=Symbol(`kickjs.h3web.notFoundMw`),ERROR_MW=Symbol(`kickjs.h3web.errorMw`),ASSEMBLED=Symbol(`kickjs.h3web.assembled`),NOOP_NEXT=()=>{};function loadH3v2(injected){let m=injected??peerRequire(`h3`),resolved=m&&m.__esModule&&m.default?{...m.default,...m}:m;if(typeof resolved.H3!=`function`)throw Error("@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), but the installed h3 has no H3 class — that is the v1 line. Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.");return resolved}async function runConnectTerminal(mw,event,err){let req=new WebRequestShim(event.req,event.url),driver=new WebResponseDriver(event.req.signal);return mw&&(err===void 0?mw(req,driver,NOOP_NEXT):mw(err,req,driver,NOOP_NEXT)),driver.settled||(err===void 0?driver.status(404).json({error:`Not Found`}):(log.error(err,`h3-web: error handler did not settle the response — ${describeError(err)}`),driver.status(500).json({error:`Internal Server Error`,...typeof process<`u`&&process.env?.NODE_ENV===`production`?{}:{message:describeError(err)}}))),driver.ready}function h3WebRuntime(options={}){let{H3,toNodeHandler,fromNodeHandler}=loadH3v2(options.h3);return{name:`h3-web`,createApp(_options={}){let holder={},app=new H3({onError:(error,event)=>{let mw=holder.app?.[ERROR_MW];return runConnectTerminal(mw,event,error)}});return holder.app=app,app},nodeHandler(app){let state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,app.all(`/**`,event=>{let mw=state[NOTFOUND_MW];return runConnectTerminal(mw,event)}));let listener=toNodeHandler(app);return(req,res,next)=>{try{let result=listener(req,res);result&&typeof result.then==`function`&&result.catch(err=>next?.(err))}catch(err){next?.(err)}}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path),run=compileWebRoute(entry,{onError:async(err,req,driver)=>{let mw=app[ERROR_MW];mw&&mw(err,req,driver,NOOP_NEXT)}});app.on(entry.method,url,event=>run({request:event.req,url:event.url,params:event.context.params??{}}))}},useConnect(app,mw,opts){let handler=fromNodeHandler(mw);opts?.path===void 0?app.use(handler):app.use(joinPath(String(opts.path),`/**`),handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3WebRuntime};
12
12
  //# sourceMappingURL=h3-web.mjs.map
@@ -1,5 +1,5 @@
1
1
 
2
- import { f as HttpRuntime } from "../../adapter-diFqgxGR.mjs";
2
+ import { f as HttpRuntime } from "../../adapter-NstPNaFV.mjs";
3
3
  //#region src/http/runtimes/h3.d.ts
4
4
  interface H3AppLike {
5
5
  use(arg1: unknown, arg2?: unknown): unknown;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.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{i as requestStore,t as RequestContext}from"../../context-CAN3t2jg.mjs";import{a as disposeRequestStore,i as createRequestStore,t as applyHandlerResult}from"../../reply-Y50qUtDy.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-Dxr2BxTi.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),h3=()=>peerRequire(`h3`),NEXT=Symbol(`kickjs.h3.next`),ERROR_MW=Symbol(`kickjs.h3.errorMw`),ROUTER=Symbol(`kickjs.h3.router`),NOTFOUND_MW=Symbol(`kickjs.h3.notFoundMw`),ASSEMBLED=Symbol(`kickjs.h3.assembled`),NOOP_NEXT=()=>{},BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var NodeResDriver=class{res;constructor(res){this.res=res}status(code){return this.res.statusCode=code,this}json(data){return this.res.headersSent||this.res.setHeader(`content-type`,`application/json; charset=utf-8`),this.res.end(JSON.stringify(data)),this}send(data){return this.res.end(data),this}type(contentType){return this.res.setHeader(`content-type`,contentType),this}setHeader(name,value){return this.res.setHeader(name,value),this}render(){throw Error(`ctx.render() is not supported on the h3 runtime (no view engine).`)}writeHead(statusCode,headers){return this.res.writeHead(statusCode,headers),this}flushHeaders(){return this.res.flushHeaders(),this}write(chunk){return this.res.write(chunk)}end(data){return this.res.end(data),this}once(event,listener){return this.res.once(event,listener),this}get headersSent(){return this.res.headersSent}};function resDriver(res){return new NodeResDriver(res)}function makeEventHandler(entry){let{getRouterParams,getQuery,readBody,readMultipartFormData}=h3(),upload=entry.meta.upload,validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async event=>{let req=event.node.req,res=event.node.res;if(req.params=getRouterParams(event)??{},req.query=getQuery(event)??{},upload&&upload.mode!==`none`){let form=await readMultipartFormData(event).catch(()=>void 0),rawParts=[],fields={};for(let part of form??[])part.filename?rawParts.push({fieldname:part.name??``,filename:part.filename,mimetype:part.type??`application/octet-stream`,buffer:part.data}):part.name&&(fields[part.name]=part.data.toString(`utf-8`));let{file,files}=applyUploadConfig(rawParts,upload);req.file=file,req.files=files,req.body=fields}else BODY_METHODS.has(req.method??`GET`)&&(req.body=await readBody(event).catch(()=>void 0));let headerId=req.headers[`x-request-id`],store=createRequestStore((Array.isArray(headerId)?headerId[0]:headerId)||req.requestId);req.requestId=store.requestId,res.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{let ctx=new RequestContext(req,res,NOOP_NEXT,resDriver(res));validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||res.writableEnded)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),res.writableEnded)return;let result=await entry.handler(ctx);!res.writableEnded&&!res.headersSent&&applyHandlerResult(ctx,result)})}}function h3Runtime(){return{name:`h3`,createApp(_options={}){let{createApp}=h3(),app=createApp({onError:(error,event)=>{let res=event.node.res;if(res.writableEnded)return;let state=app;if(error?.statusCode===404){let next=event.node.req[NEXT];if(next){next();return}let nf=state[NOTFOUND_MW];if(nf){nf(event.node.req,resDriver(res),NOOP_NEXT);return}}let mw=state[ERROR_MW];mw&&mw(error,event.node.req,resDriver(res),NOOP_NEXT)}});return app},nodeHandler(app){let{toNodeListener}=h3(),state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,state[ROUTER]&&app.use(state[ROUTER]));let listener=toNodeListener(app);return(req,res,next)=>{next&&(req[NEXT]=next),Promise.resolve(listener(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){let{createRouter,eventHandler}=h3(),state=app;state[ROUTER]||(state[ROUTER]=createRouter());let router=state[ROUTER];for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path);router[entry.method.toLowerCase()](url,eventHandler(makeEventHandler(entry)))}},useConnect(app,mw,opts){let{fromNodeMiddleware}=h3(),handler=fromNodeMiddleware(mw);opts?.path===void 0?app.use(handler):app.use(opts.path,handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3Runtime};
11
+ import{i as requestStore,t as RequestContext}from"../../context-DYOcPcg8.mjs";import{a as disposeRequestStore,i as createRequestStore,t as applyHandlerResult}from"../../reply-Bo950wuK.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-C9V9tIR3.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),h3=()=>peerRequire(`h3`),NEXT=Symbol(`kickjs.h3.next`),ERROR_MW=Symbol(`kickjs.h3.errorMw`),ROUTER=Symbol(`kickjs.h3.router`),NOTFOUND_MW=Symbol(`kickjs.h3.notFoundMw`),ASSEMBLED=Symbol(`kickjs.h3.assembled`),NOOP_NEXT=()=>{},BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var NodeResDriver=class{res;constructor(res){this.res=res}status(code){return this.res.statusCode=code,this}json(data){return this.res.headersSent||this.res.setHeader(`content-type`,`application/json; charset=utf-8`),this.res.end(JSON.stringify(data)),this}send(data){return this.res.end(data),this}type(contentType){return this.res.setHeader(`content-type`,contentType),this}setHeader(name,value){return this.res.setHeader(name,value),this}render(){throw Error(`ctx.render() is not supported on the h3 runtime (no view engine).`)}writeHead(statusCode,headers){return this.res.writeHead(statusCode,headers),this}flushHeaders(){return this.res.flushHeaders(),this}write(chunk){return this.res.write(chunk)}end(data){return this.res.end(data),this}once(event,listener){return this.res.once(event,listener),this}get headersSent(){return this.res.headersSent}};function resDriver(res){return new NodeResDriver(res)}function makeEventHandler(entry){let{getRouterParams,getQuery,readBody,readMultipartFormData}=h3(),upload=entry.meta.upload,validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async event=>{let req=event.node.req,res=event.node.res;if(req.params=getRouterParams(event)??{},req.query=getQuery(event)??{},upload&&upload.mode!==`none`){let form=await readMultipartFormData(event).catch(()=>void 0),rawParts=[],fields={};for(let part of form??[])part.filename?rawParts.push({fieldname:part.name??``,filename:part.filename,mimetype:part.type??`application/octet-stream`,buffer:part.data}):part.name&&(fields[part.name]=part.data.toString(`utf-8`));let{file,files}=applyUploadConfig(rawParts,upload);req.file=file,req.files=files,req.body=fields}else BODY_METHODS.has(req.method??`GET`)&&(req.body=await readBody(event).catch(()=>void 0));let headerId=req.headers[`x-request-id`],store=createRequestStore((Array.isArray(headerId)?headerId[0]:headerId)||req.requestId);req.requestId=store.requestId,res.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{let ctx=new RequestContext(req,res,NOOP_NEXT,resDriver(res));validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||res.writableEnded)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),res.writableEnded)return;let result=await entry.handler(ctx);!res.writableEnded&&!res.headersSent&&applyHandlerResult(ctx,result)})}}function h3Runtime(){return{name:`h3`,createApp(_options={}){let{createApp}=h3(),app=createApp({onError:(error,event)=>{let res=event.node.res;if(res.writableEnded)return;let state=app;if(error?.statusCode===404){let next=event.node.req[NEXT];if(next){next();return}let nf=state[NOTFOUND_MW];if(nf){nf(event.node.req,resDriver(res),NOOP_NEXT);return}}let mw=state[ERROR_MW];mw&&mw(error,event.node.req,resDriver(res),NOOP_NEXT)}});return app},nodeHandler(app){let{toNodeListener}=h3(),state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,state[ROUTER]&&app.use(state[ROUTER]));let listener=toNodeListener(app);return(req,res,next)=>{next&&(req[NEXT]=next),Promise.resolve(listener(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){let{createRouter,eventHandler}=h3(),state=app;state[ROUTER]||(state[ROUTER]=createRouter());let router=state[ROUTER];for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path);router[entry.method.toLowerCase()](url,eventHandler(makeEventHandler(entry)))}},useConnect(app,mw,opts){let{fromNodeMiddleware}=h3(),handler=fromNodeMiddleware(mw);opts?.path===void 0?app.use(handler):app.use(opts.path,handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3Runtime};
12
12
  //# sourceMappingURL=h3.mjs.map
package/dist/index.d.mts CHANGED
@@ -4,28 +4,27 @@ import { a as tokenName, c as createToken, i as KickJsRegistry, l as isInjection
4
4
  import { A as Service, B as resolveAsset, C as Post, D as Put, F as ASSET_MANIFEST_VERSION, I as KickAssets, L as UnknownAssetError, M as normalizeApiQueryParamsConfig, N as withBuilder, O as Repository, P as ASSETS, R as assets, S as Patch, T as PreDestroy, V as useAssets, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as Value, k as RouteDefinition, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable, z as clearAssetCache } from "./decorators-Bks7cgBJ.mjs";
5
5
  import { a as baseEnvSchema, c as loadEnv, d as resetEnvCache, l as loadEnvFromSchema, n as TypedConfigService, o as defineEnv, r as createConfigService, s as getEnv, t as ConfigService, u as reloadEnv } from "./index-M6TF75MS.mjs";
6
6
  import { S as MetaValue, _ as defineContextDecorator, a as AnyContributorRegistration, b as ContextMetaKey, c as ContextDecoratorRequiringParams, d as ContextDecoratorWithDefaults, f as ContributorRegistration, g as ResolvedDeps, h as MissingParamKeys, i as ModuleRoutes, l as ContextDecoratorSpec, m as DepValue, n as AppModuleClass, o as CallSiteParams, p as ContributorRegistrations, r as AppModuleEntry, s as ContextDecorator, t as AppModule, u as ContextDecoratorTarget, v as ContextKeys, x as ExecutionContext, y as ContextMeta } from "./app-module-DtNJpj0r.mjs";
7
- import { $ as defineModules, A as DefineAdapterOptions, B as getClassMetaOrUndefined, C as Ctx, D as SseHandler, E as RouteShape, F as ContributorPipeline, G as hasClassMeta, H as getMetaRecord, I as ContributorSource, J as setClassMeta, K as pushClassMeta, L as SourcedRegistration, M as RunContributorsOptions, N as runContributors, O as AdapterAsyncOptions, P as BuildPipelineOptions, Q as ModuleList, R as buildPipeline, S as UseConnectOptions, T as RequestContext, U as getMethodMeta, V as getMetaMap, W as getMethodMetaOrUndefined, X as setInMetaRecord, Y as setInMetaMap, Z as setMethodMeta, _ as RouteTable, _t as IntrospectionSnapshot, a as MiddlewarePath, at as PluginAsyncOptions, b as RuntimeResponse, c as AdapterHttp, ct as KickPlugin, d as ExpressRuntimeTypes, dt as AugmentationMeta, et as DefineModuleOptions, f as HttpRuntime, ft as KickJsPluginName, g as RouteMethod, gt as IntrospectionKind, h as RouteMeta, ht as IntrospectFn, i as AppAdapterClass, it as DefinePluginOptions, j as defineAdapter, k as AdapterFactory, l as ConnectMiddleware, lt as ModuleRegistry, m as RouteEntry, mt as defineAugmentation, n as AdapterMiddleware, nt as defineModule, o as MiddlewarePhase, ot as PluginFactory, p as KickRuntimeRegister, pt as KickJsPluginRegistry, q as pushMethodMeta, r as AppAdapter, rt as BuildContext, s as ActiveRuntime, st as definePlugin, t as AdapterContext, tt as ModuleFactory, u as CtxHandler, ut as MutableModuleRegistry, v as RuntimeAppOptions, w as DeepReadonly, x as RuntimeTypeMap, y as RuntimeCapabilities, z as getClassMeta } from "./adapter-diFqgxGR.mjs";
7
+ import { $ as defineModules, A as DefineAdapterOptions, B as getClassMetaOrUndefined, C as Ctx, D as SseHandler, E as RouteShape, F as ContributorPipeline, G as hasClassMeta, H as getMetaRecord, I as ContributorSource, J as setClassMeta, K as pushClassMeta, L as SourcedRegistration, M as RunContributorsOptions, N as runContributors, O as AdapterAsyncOptions, P as BuildPipelineOptions, Q as ModuleList, R as buildPipeline, S as UseConnectOptions, T as RequestContext, U as getMethodMeta, V as getMetaMap, W as getMethodMetaOrUndefined, X as setInMetaRecord, Y as setInMetaMap, Z as setMethodMeta, _ as RouteTable, _t as IntrospectionSnapshot, a as MiddlewarePath, at as PluginAsyncOptions, b as RuntimeResponse, c as AdapterHttp, ct as KickPlugin, d as ExpressRuntimeTypes, dt as AugmentationMeta, et as DefineModuleOptions, f as HttpRuntime, ft as KickJsPluginName, g as RouteMethod, gt as IntrospectionKind, h as RouteMeta, ht as IntrospectFn, i as AppAdapterClass, it as DefinePluginOptions, j as defineAdapter, k as AdapterFactory, l as ConnectMiddleware, lt as ModuleRegistry, m as RouteEntry, mt as defineAugmentation, n as AdapterMiddleware, nt as defineModule, o as MiddlewarePhase, ot as PluginFactory, p as KickRuntimeRegister, pt as KickJsPluginRegistry, q as pushMethodMeta, r as AppAdapter, rt as BuildContext, s as ActiveRuntime, st as definePlugin, t as AdapterContext, tt as ModuleFactory, u as CtxHandler, ut as MutableModuleRegistry, v as RuntimeAppOptions, w as DeepReadonly, x as RuntimeTypeMap, y as RuntimeCapabilities, z as getClassMeta } from "./adapter-NstPNaFV.mjs";
8
8
  import { i as getCronJobs, n as Cron, r as CronJobMeta, t as CRON_META } from "./cron-DOOtTY4q.mjs";
9
9
  import { a as Cacheable, c as setCacheProvider, i as CacheProvider, n as CacheEvict, o as MemoryCacheProvider, r as CacheOptions, s as getCacheProvider } from "./cache-C0qL0NSD.mjs";
10
10
  import { a as describeError, i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "./logger-DA43DvNY.mjs";
11
- import { A as mountSort, B as FormatKickErrorOptions, C as groupAssetKeys, D as MountCycleError, E as MissingMountDepError, F as CircuitBreaker, G as disposeAll, H as KickErrorInit, I as CircuitBreakerOptions, K as registerDisposable, L as CircuitBreakerState, M as DuplicateContributorError, N as MissingContextValueError, O as MountKind, P as MissingContributorError, R as CircuitBreakerStats, S as GroupAssetKeysResult, T as DuplicateMountNameError, U as formatKickError, V as KickError, W as Disposable, _ as ClusterOptions, a as TraceContextOptions, b as AssetKeyStrategy, c as requestScopeMiddleware, d as getRequestValue, f as requestStore, g as defineHttpContextDecorator, h as materializeRouter, i as TraceContext, j as ContributorCycleError, k as MountSortItem, l as RequestStore, m as expressRuntime, n as ViewAdapterOptions, o as parseTraceparent, p as buildRoutes, r as TRACEPARENT_HEADER, s as traceContext, t as ViewAdapter, u as getRequestStore, v as isClusterPrimary, w as stripExt, x as GroupAssetKeysOptions, y as AssetKeyPair, z as CircuitOpenError } from "./views-BBY9_PUV.mjs";
11
+ import { A as MountCycleError, B as CircuitBreakerState, C as AssetKeyStrategy, D as stripExt, E as groupAssetKeys, F as DuplicateContributorError, G as KickErrorInit, H as CircuitOpenError, I as MissingContextValueError, J as disposeAll, K as formatKickError, L as MissingContributorError, M as MountSortItem, N as mountSort, O as DuplicateMountNameError, P as ContributorCycleError, R as CircuitBreaker, S as AssetKeyPair, T as GroupAssetKeysResult, U as FormatKickErrorOptions, V as CircuitBreakerStats, W as KickError, Y as registerDisposable, _ as expressRuntime, a as ViewAdapterOptions, b as ClusterOptions, c as TraceContextOptions, d as requestScopeMiddleware, f as RequestStore, g as buildRoutes, h as requestStore, i as ViewAdapter, j as MountKind, k as MissingMountDepError, l as parseTraceparent, m as getRequestValue, n as SpaAdapterOptions, o as TRACEPARENT_HEADER, p as getRequestStore, q as Disposable, s as TraceContext, t as SpaAdapter, u as traceContext, v as materializeRouter, w as GroupAssetKeysOptions, x as isClusterPrimary, y as defineHttpContextDecorator, z as CircuitBreakerOptions } from "./spa-CDQ74RGA.mjs";
12
12
  import { a as ProblemException, c as defaultProblemTitle, i as ProblemDetails, l as normalizeProblem, n as HttpStatus, o as Problems, r as HttpStatusCode, s as ValidationError, t as HttpException } from "./errors-By6UueCm.mjs";
13
13
  import { n as normalizePath, t as joinPaths } from "./path-BVA9MfN1.mjs";
14
14
  import { a as isRef, c as toRefs, i as computed, l as unref, n as Ref, o as reactive, r as WatchOptions, s as ref, t as ComputedRef, u as watch } from "./reactivity-BkMNA0kp.mjs";
15
15
  import { C as SortItem, S as QueryFieldConfig, T as TypedParsedQuery, _ as FilterOperator, a as getQueryParsingDefaults, b as ParsedQuery, c as parseQuery, d as resetQueryParsingDefaults, f as setQueryParsingDefaults, g as FilterItem, h as FieldsOf, i as buildQueryParams, l as parseSearchQuery, m as FILTER_OPERATORS, n as QueryRejectReason, o as parseFilters, r as QueryRejection, s as parsePagination, t as ParseQueryOptions, u as parseSort, v as PaginatedResponse, x as QueryBuilderAdapter, y as PaginationParams } from "./index-BfT5KZ-M.mjs";
16
- import { n as ApplicationOptions, r as MiddlewareEntry, t as Application } from "./application-D_mReBi_.mjs";
17
- import { t as bootstrap } from "./bootstrap-CytCvAnr.mjs";
16
+ import { n as ApplicationOptions, r as MiddlewareEntry, t as Application } from "./application-CnJh2Bry.mjs";
17
+ import { t as bootstrap } from "./bootstrap-Iq_WR08c.mjs";
18
18
  import { n as cors, t as CorsOptions } from "./cors-BuDU9CpA.mjs";
19
19
  import { n as csrf, t as CsrfOptions } from "./csrf-vR23CJas.mjs";
20
- import { n as notFoundHandler, t as errorHandler } from "./error-handler-Cr6Yt9as.mjs";
20
+ import { n as notFoundHandler, t as errorHandler } from "./error-handler-p_T3hhiD.mjs";
21
21
  import { n as helmet, t as HelmetOptions } from "./helmet-CFQUTVig.mjs";
22
22
  import { n as RateLimitStore, r as rateLimit, t as RateLimitOptions } from "./rate-limit-Dme747JJ.mjs";
23
23
  import { n as requestId, t as REQUEST_ID_HEADER } from "./request-id-CVzJ1uHD.mjs";
24
- import { n as requestLogger, t as RequestLoggerOptions } from "./request-logger-BU4ulKLp.mjs";
24
+ import { n as requestLogger, t as RequestLoggerOptions } from "./request-logger-D_pf4xzE.mjs";
25
25
  import { a as session, i as SessionStore, n as SessionData, r as SessionOptions, t as Session } from "./session-z9iewOXA.mjs";
26
- import { n as SpaAdapterOptions, t as SpaAdapter } from "./spa-CCi-hC2M.mjs";
27
- import { i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-Wck12jE5.mjs";
26
+ import { a as KvSessionStoreOptions, c as InferHandlerResponse, d as isReply, f as reply, i as KvSessionStore, l as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as applyHandlerResult } from "./kv-stores-pWdw8RKf.mjs";
27
+ import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-BYDUIiZW.mjs";
28
28
  import { n as validate } from "./validate-DMYpUnrf.mjs";
29
- import { a as KvSessionStoreOptions, c as InferHandlerResponse, d as isReply, f as reply, i as KvSessionStore, l as Reply, n as KvRateLimitStore, o as RateLimitGuardOptions, r as KvRateLimitStoreOptions, s as rateLimitGuard, t as KvLike, u as applyHandlerResult } from "./kv-stores-D2kSUAEP.mjs";
30
- import { i as buildRouteTable, t as BuildRoutesOptions } from "./router-builder-C6E11Grf.mjs";
29
+ import { i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-CUtcjc-n.mjs";
31
30
  export { ASSETS, ASSET_MANIFEST_VERSION, type ActiveRuntime, type AdapterAsyncOptions, type AdapterContext, type AdapterFactory, type AdapterHttp, type AdapterMiddleware, type AnyContributorRegistration, ApiQueryParams, type ApiQueryParamsConfig, type ApiQueryParamsConfig as QueryParamsConfig, type AppAdapter, type AppAdapterClass, type AppModule, type AppModuleClass, type AppModuleEntry, Application, type ApplicationOptions, Asset, type AssetKey, type AssetKeyPair, type AssetKeyStrategy, type AugmentationMeta, Autowired, type BaseUploadOptions, type BuildContext, type BuildPipelineOptions, type BuildRoutesOptions, type Buildable, Builder, type BuilderOf, CRON_META, CacheEvict, type CacheOptions, type CacheProvider, Cacheable, type CallSiteParams, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerState, type CircuitBreakerStats, CircuitOpenError, type ClassKind, type ClusterOptions, type ColumnApiQueryParamsConfig, Component, type ComputedRef, ConfigService, type ConnectMiddleware, ConsoleLoggerProvider, type Constructor, Container, type ContainerChangeEvent, type ContainerChangeListener, type ContextDecorator, type ContextDecoratorRequiringParams, type ContextDecoratorSpec, type ContextDecoratorTarget, type ContextDecoratorWithDefaults, type ContextKeys, type ContextMeta, type ContextMetaKey, ContributorCycleError, type ContributorPipeline, type ContributorRegistration, type ContributorRegistrations, type ContributorSource, Controller, type CorsOptions, Cron, type CronJobMeta, type CsrfOptions, type Ctx, type CtxHandler, type DeepReadonly, type DefineAdapterOptions, type DefineModuleOptions, type DefinePluginOptions, Delete, type DepValue, type Disposable, DuplicateContributorError, DuplicateMountNameError, type Env, type EnvKey, type ExecutionContext, type ExpressRuntimeTypes, FILTER_OPERATORS, type FieldsOf, type FileTypeFilter, FileUpload, type FileUploadConfig, type FilterItem, type FilterOperator, type FormatKickErrorOptions, Get, type GroupAssetKeysOptions, type GroupAssetKeysResult, type HelmetOptions, HttpException, type HttpRuntime, HttpStatus, type HttpStatusCode, INJECTION_TOKEN, type InferHandlerResponse, Inject, Injectable, type InjectionToken, type IntrospectFn, type IntrospectionKind, type IntrospectionSnapshot, type KickAssets, KickError, type KickErrorInit, type KickJsPluginName, type KickJsPluginRegistry, type KickJsRegistry, type KickPlugin, type KickRuntimeRegister, type KvLike, KvRateLimitStore, type KvRateLimitStoreOptions, KvSessionStore, type KvSessionStoreOptions, Logger, type LoggerProvider, METADATA, type MaybePromise, MemoryCacheProvider, type MetaValue, Middleware, type MiddlewareEntry, type MiddlewareHandler, type MiddlewarePath, type MiddlewarePhase, MissingContextValueError, MissingContributorError, MissingMountDepError, type MissingParamKeys, type ModuleFactory, ModuleList, type ModuleRegistry, type ModuleRoutes, MountCycleError, type MountKind, type MountSortItem, MutableModuleRegistry, type PaginatedResponse, type PaginationParams, type ParseQueryOptions, type ParsedQuery, Patch, type PluginAsyncOptions, type PluginFactory, Post, PostConstruct, type PostConstructStatus, PreDestroy, type ProblemDetails, ProblemException, Problems, Put, type QueryBuilderAdapter, type QueryFieldConfig, type QueryRejectReason, type QueryRejection, REQUEST_ID_HEADER, type RateLimitGuardOptions, type RateLimitOptions, type RateLimitStore, type Ref, type Reply, Repository, RequestContext, type RequestLoggerOptions, type RequestStore, type ResolvedDeps, type RouteDefinition, type RouteEntry, type RouteMeta, type RouteMethod, type RouteShape, type RouteTable, type RunContributorsOptions, type RuntimeAppOptions, type RuntimeCapabilities, type RuntimeResponse, type RuntimeTypeMap, Scope, Service, type ServiceOptions, type Session, type SessionData, type SessionOptions, type SessionStore, type SortItem, type SourcedRegistration, SpaAdapter, type SpaAdapterOptions, type SseHandler, TRACEPARENT_HEADER, type TraceContext, type TraceContextOptions, type TypedConfigService, type TypedParsedQuery, UnknownAssetError, type UploadOptions, type UseConnectOptions, type ValidationError, Value, ViewAdapter, type ViewAdapterOptions, type WatchOptions, applyHandlerResult, assets, baseEnvSchema, bootstrap, buildPipeline, buildQueryParams, buildRouteTable, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createLogger, createToken, csrf, defaultProblemTitle, defineAdapter, defineAugmentation, defineContextDecorator, defineEnv, defineHttpContextDecorator, defineModule, defineModules, definePlugin, describeError, disposeAll, errorHandler, expressRuntime, formatKickError, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getQueryParsingDefaults, getRequestStore, getRequestValue, groupAssetKeys, hasClassMeta, helmet, isClusterPrimary, isInjectionToken, isRef, isReply, joinPaths, loadEnv, loadEnvFromSchema, materializeRouter, mountSort, normalizeApiQueryParamsConfig, normalizePath, normalizeProblem, notFoundHandler, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, rateLimitGuard, reactive, ref, registerDisposable, reloadEnv, reply, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resetQueryParsingDefaults, resolveAsset, resolveMimeTypes, runContributors, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, setQueryParsingDefaults, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, watch, withBuilder };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v6.7.0
2
+ * @forinda/kickjs v7.1.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{a as loadEnvFromSchema,i as loadEnv,n as defineEnv,o as reloadEnv,r as getEnv,s as resetEnvCache,t as baseEnvSchema}from"./env-DPEhlEC4.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,c as KickError,i as createToken,l as formatKickError,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-CFVAdwXa.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-DjW8JOQZ.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{t as MutableModuleRegistry}from"./module-registry-cbndPnlY.mjs";import{CRON_META,Cron,getCronJobs}from"./core/cron.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-QYOU5_Eg.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,toRefs,unref,watch}from"./core/reactivity.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-DW5uoNhO.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-Ce44238b.mjs";import{a as buildPipeline,i as runContributors,r as buildRouteTable}from"./router-builder-DtonR20n.mjs";import{a as DuplicateMountNameError,c as mountSort,i as materializeRouter,n as buildRoutes,o as MissingMountDepError,r as expressRuntime,s as MountCycleError,t as Application}from"./application-VxxP88FH.mjs";import{n as defineAdapter,t as ViewAdapter}from"./views-3TYTcdyF.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as requestStore,n as getRequestStore,r as getRequestValue,t as RequestContext}from"./context-CAN3t2jg.mjs";import{n as isReply,r as reply,s as requestScopeMiddleware,t as applyHandlerResult}from"./reply-Y50qUtDy.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-B_YnIZ2-.mjs";import{validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-Dxr2BxTi.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{n as isClusterPrimary,t as bootstrap}from"./bootstrap-F6IShJ1f.mjs";import{n as randomHex,t as csrf}from"./csrf-MbsM7-58.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-VfJbg9Gs.mjs";import{session}from"./http/middleware/session.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-D035b21X.mjs";const mergeConfig$1=(defaults={},overrides={})=>({...defaults,...overrides}),composeName$1=(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$1(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$1(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}function defineAugmentation(name,meta){}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CacheEvict,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,FILTER_OPERATORS,FileUpload,Get,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Put,REQUEST_ID_HEADER,Repository,RequestContext,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,applyHandlerResult,assets,baseEnvSchema,bootstrap,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createLogger,createToken,csrf,defaultProblemTitle,defineAdapter,defineAugmentation,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,describeError,disposeAll,errorHandler,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,groupAssetKeys,hasClassMeta,helmet,isClusterPrimary,isInjectionToken,isRef,isReply,joinPaths,loadEnv,loadEnvFromSchema,materializeRouter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,reloadEnv,reply,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,runContributors,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,stripExt,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,watch,withBuilder};
11
+ import{a as loadEnvFromSchema,i as loadEnv,n as defineEnv,o as reloadEnv,r as getEnv,s as resetEnvCache,t as baseEnvSchema}from"./env-IfTg0Rv1.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{a as isInjectionToken,c as KickError,i as createToken,l as formatKickError,n as tokenName,r as INJECTION_TOKEN,t as Container}from"./container-BITnQkhU.mjs";import{ConsoleLoggerProvider,Logger,createLogger,describeError}from"./core/logger.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-CyyYO_qa.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,PreDestroy,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{t as MutableModuleRegistry}from"./module-registry-BfOa58-E.mjs";import{CRON_META,Cron,getCronJobs}from"./core/cron.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{r as registerDisposable,t as disposeAll}from"./disposables-0gJffTe_.mjs";import{HttpException,HttpStatus,ProblemException,Problems,defaultProblemTitle,normalizeProblem}from"./core/errors.mjs";import{joinPaths,normalizePath}from"./core/path.mjs";import{computed,isRef,reactive,ref,toRefs,unref,watch}from"./core/reactivity.mjs";import{a as clearAssetCache,c as groupAssetKeys,i as assets,l as stripExt,n as ASSET_MANIFEST_VERSION,o as resolveAsset,r as UnknownAssetError,s as useAssets,t as ASSETS,u as defineContextDecorator}from"./core-MI5Y1nGg.mjs";import{i as MissingContributorError,n as DuplicateContributorError,r as MissingContextValueError,t as ContributorCycleError}from"./context-errors-Bf2NqTS3.mjs";import{a as buildPipeline,i as runContributors,r as buildRouteTable}from"./router-builder-Bv175XoR.mjs";import{a as DuplicateMountNameError,c as mountSort,i as materializeRouter,n as buildRoutes,o as MissingMountDepError,r as expressRuntime,s as MountCycleError,t as Application}from"./application-BDtFj66k.mjs";import{t as defineAdapter}from"./define-adapter-Cz-bj4Xk.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as requestStore,n as getRequestStore,r as getRequestValue,t as RequestContext}from"./context-DYOcPcg8.mjs";import{n as isReply,r as reply,s as requestScopeMiddleware,t as applyHandlerResult}from"./reply-Bo950wuK.mjs";import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"./query-BYUCKdu5.mjs";import{validate}from"./http/middleware/validate.mjs";import{r as resolveMimeTypes}from"./upload-config-C9V9tIR3.mjs";import{buildUploadMiddleware,cleanupFiles,upload}from"./http/middleware/upload.mjs";import{n as isClusterPrimary,t as bootstrap}from"./bootstrap-CJbP4DXN.mjs";import{n as randomHex,t as csrf}from"./csrf-BAnc9Ww7.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-DNeEYG-J.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-BQgwhAlJ.mjs";const mergeConfig$1=(defaults={},overrides={})=>({...defaults,...overrides}),composeName$1=(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$1(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$1(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok)),config=await opts.useFactory(...deps);return inner=buildSync(instanceName,!1,config),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}function defineAugmentation(name,meta){}function defineHttpContextDecoratorImpl(spec){return defineContextDecorator(spec)}const defineHttpContextDecorator=Object.freeze(Object.assign(defineHttpContextDecoratorImpl,{withParams:()=>spec=>defineHttpContextDecoratorImpl(spec)})),TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return randomHex(16)}function generateSpanId(){return randomHex(8)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CacheEvict,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,FILTER_OPERATORS,FileUpload,Get,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,KickError,KvRateLimitStore,KvSessionStore,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContextValueError,MissingContributorError,MissingMountDepError,ModuleList,MountCycleError,MutableModuleRegistry,Patch,Post,PostConstruct,PreDestroy,ProblemException,Problems,Put,REQUEST_ID_HEADER,Repository,RequestContext,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,applyHandlerResult,assets,baseEnvSchema,bootstrap,buildPipeline,buildQueryParams,buildRouteTable,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createLogger,createToken,csrf,defaultProblemTitle,defineAdapter,defineAugmentation,defineContextDecorator,defineEnv,defineHttpContextDecorator,defineModule,defineModules,definePlugin,describeError,disposeAll,errorHandler,expressRuntime,formatKickError,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getQueryParsingDefaults,getRequestStore,getRequestValue,groupAssetKeys,hasClassMeta,helmet,isClusterPrimary,isInjectionToken,isRef,isReply,joinPaths,loadEnv,loadEnvFromSchema,materializeRouter,mountSort,normalizeApiQueryParamsConfig,normalizePath,normalizeProblem,notFoundHandler,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,rateLimitGuard,reactive,ref,registerDisposable,reloadEnv,reply,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resetQueryParsingDefaults,resolveAsset,resolveMimeTypes,runContributors,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,setQueryParsingDefaults,stripExt,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,watch,withBuilder};
12
12
  //# sourceMappingURL=index.mjs.map