@forinda/kickjs 10.4.0 → 10.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-BZ1WzN1z.d.mts → adapter-9sPr_5xt.d.mts} +123 -35
- package/dist/adapter-9sPr_5xt.d.mts.map +1 -0
- package/dist/{allowed-hosts-D6qcuK5I.d.mts → allowed-hosts-BpKwviq5.d.mts} +3 -3
- package/dist/allowed-hosts-BpKwviq5.d.mts.map +1 -0
- package/dist/{application-D5Iiy7rt.d.mts → application-BD9LQ2s4.d.mts} +83 -43
- package/dist/application-BD9LQ2s4.d.mts.map +1 -0
- package/dist/application-DwYTFctU.mjs +14 -0
- package/dist/application-DwYTFctU.mjs.map +1 -0
- package/dist/background-DSztbyc4.mjs +12 -0
- package/dist/background-DSztbyc4.mjs.map +1 -0
- package/dist/bootstrap-DdTHtS8P.mjs +12 -0
- package/dist/{bootstrap-B_sGJNSz.mjs.map → bootstrap-DdTHtS8P.mjs.map} +1 -1
- package/dist/{bounded-counters-DS-IbDW9.mjs → bounded-counters-Bd7X3eI5.mjs} +2 -2
- package/dist/{bounded-counters-DS-IbDW9.mjs.map → bounded-counters-Bd7X3eI5.mjs.map} +1 -1
- package/dist/{breach-padding-C-Dnq8CS.d.mts → breach-padding-FBVGmcBb.d.mts} +3 -3
- package/dist/breach-padding-FBVGmcBb.d.mts.map +1 -0
- package/dist/{client-ip-BLkoQTIR.mjs → client-ip-DxEVqZP-.mjs} +2 -2
- package/dist/{client-ip-BLkoQTIR.mjs.map → client-ip-DxEVqZP-.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-B6EeAw4P.mjs → config-_YTqZtnE.mjs} +3 -3
- package/dist/{config-B6EeAw4P.mjs.map → config-_YTqZtnE.mjs.map} +1 -1
- package/dist/connect-BlIamapT.d.mts +41 -0
- package/dist/connect-BlIamapT.d.mts.map +1 -0
- package/dist/context-UaQ6cv0K.mjs +12 -0
- package/dist/context-UaQ6cv0K.mjs.map +1 -0
- package/dist/{context-errors-CR5NCXfl.mjs → context-errors-DcPmDybm.mjs} +2 -2
- package/dist/{context-errors-CR5NCXfl.mjs.map → context-errors-DcPmDybm.mjs.map} +1 -1
- package/dist/{contributor-runner--ofCRZ0d.mjs → contributor-runner-BHjr6qSE.mjs} +3 -3
- package/dist/{contributor-runner--ofCRZ0d.mjs.map → contributor-runner-BHjr6qSE.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/core-Ddq8b9hi.mjs +12 -0
- package/dist/{core-CsMDdzNE.mjs.map → core-Ddq8b9hi.mjs.map} +1 -1
- package/dist/{cors-2Bwhyhpt.d.mts → cors-BlR_b0Qb.d.mts} +3 -3
- package/dist/cors-BlR_b0Qb.d.mts.map +1 -0
- package/dist/{csrf-BDAZK2mm.d.mts → csrf-ZFOrJZhJ.d.mts} +3 -3
- package/dist/csrf-ZFOrJZhJ.d.mts.map +1 -0
- package/dist/decorate-wrAUzCjW.mjs +13 -0
- package/dist/{decorate-CLeX6hbL.mjs.map → decorate-wrAUzCjW.mjs.map} +1 -1
- package/dist/{define-adapter-RbKRSG3i.mjs → define-adapter-Ce1FDvEo.mjs} +2 -2
- package/dist/{define-adapter-RbKRSG3i.mjs.map → define-adapter-Ce1FDvEo.mjs.map} +1 -1
- package/dist/{di-hooks-CiNaIu12.mjs → di-hooks-MFthA-Fs.mjs} +9 -4
- package/dist/di-hooks-MFthA-Fs.mjs.map +1 -0
- package/dist/{disposables-DYTkgNiG.mjs → disposables-BgUIg4s1.mjs} +1 -1
- package/dist/{error-handler-CbP7hKdJ.d.mts → error-handler-CH4PPZCK.d.mts} +2 -2
- package/dist/{error-handler-CbP7hKdJ.d.mts.map → error-handler-CH4PPZCK.d.mts.map} +1 -1
- package/dist/express-BcfJgvBP.mjs +12 -0
- package/dist/express-BcfJgvBP.mjs.map +1 -0
- package/dist/express-lazy-DCYWtKZx.mjs +12 -0
- package/dist/express-lazy-DCYWtKZx.mjs.map +1 -0
- package/dist/handler-CS1BhG0C.mjs +12 -0
- package/dist/{handler-Cw4mr3ls.mjs.map → handler-CS1BhG0C.mjs.map} +1 -1
- package/dist/{helmet-CEOmo516.d.mts → helmet-BVuVBl-D.d.mts} +3 -3
- package/dist/helmet-BVuVBl-D.d.mts.map +1 -0
- package/dist/{host-H7CIkHNB.mjs → host-lMSIGnh7.mjs} +2 -2
- package/dist/{host-H7CIkHNB.mjs.map → host-lMSIGnh7.mjs.map} +1 -1
- package/dist/http/application.d.mts +2 -2
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +1 -1
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.d.mts +1 -1
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs.map +1 -1
- package/dist/http/middleware/breach-padding.d.mts +1 -1
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/breach-padding.mjs.map +1 -1
- package/dist/http/middleware/cors.d.mts +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.d.mts +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.d.mts +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +1 -1
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +3 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.d.mts +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.d.mts +47 -0
- package/dist/http/runtimes/express.d.mts.map +1 -0
- package/dist/http/runtimes/express.mjs +11 -0
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/index.d.mts +17 -16
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{is-production-BTroGhp5.mjs → is-production-MYGnN2Nv.mjs} +2 -2
- package/dist/{is-production-BTroGhp5.mjs.map → is-production-MYGnN2Nv.mjs.map} +1 -1
- package/dist/{jobs-xqoMmdr4.mjs → jobs-ANHUk_Ht.mjs} +3 -3
- package/dist/{jobs-xqoMmdr4.mjs.map → jobs-ANHUk_Ht.mjs.map} +1 -1
- package/dist/{kv-stores-DXFBEYYu.d.mts → kv-stores-C1sQs2Rb.d.mts} +4 -4
- package/dist/{kv-stores-DXFBEYYu.d.mts.map → kv-stores-C1sQs2Rb.d.mts.map} +1 -1
- package/dist/{kv-stores-0-6blGzh.mjs → kv-stores-Cro8JwAF.mjs} +3 -3
- package/dist/{kv-stores-0-6blGzh.mjs.map → kv-stores-Cro8JwAF.mjs.map} +1 -1
- package/dist/lazy-serve-static-Zge6_pKo.mjs +12 -0
- package/dist/lazy-serve-static-Zge6_pKo.mjs.map +1 -0
- package/dist/{metadata-Bm65Y-5O.mjs → metadata-_LqQme8p.mjs} +1 -1
- package/dist/{observers-BAXkwMx0.mjs → observers-Oedvuzit.mjs} +2 -2
- package/dist/{observers-BAXkwMx0.mjs.map → observers-Oedvuzit.mjs.map} +1 -1
- package/dist/precompressed-B6wz_5tz.mjs +12 -0
- package/dist/precompressed-B6wz_5tz.mjs.map +1 -0
- package/dist/{query-CGyw7vNi.mjs → query-KMR84Kwu.mjs} +2 -2
- package/dist/{query-CGyw7vNi.mjs.map → query-KMR84Kwu.mjs.map} +1 -1
- package/dist/{rate-limit-BgoeahE5.d.mts → rate-limit-DQDk6bAH.d.mts} +5 -5
- package/dist/rate-limit-DQDk6bAH.d.mts.map +1 -0
- package/dist/reply-BQTif5Iu.mjs +12 -0
- package/dist/reply-BQTif5Iu.mjs.map +1 -0
- package/dist/{request-id-CVzJ1uHD.d.mts → request-id-Dn64nEHK.d.mts} +3 -3
- package/dist/request-id-Dn64nEHK.d.mts.map +1 -0
- package/dist/request-scope-L71-nmRe.mjs +12 -0
- package/dist/request-scope-L71-nmRe.mjs.map +1 -0
- package/dist/{respond-BOlh-baJ.mjs → respond-DR7zkOUf.mjs} +2 -2
- package/dist/{respond-BOlh-baJ.mjs.map → respond-DR7zkOUf.mjs.map} +1 -1
- package/dist/rolldown-runtime-DouoOEDq.mjs +11 -0
- package/dist/{route-flag-BPSq2JCs.mjs → route-flag-DCOS_F5A.mjs} +3 -3
- package/dist/{route-flag-BPSq2JCs.mjs.map → route-flag-DCOS_F5A.mjs.map} +1 -1
- package/dist/{route-policy-DDszB6dQ.mjs → route-policy-Cy-oSUro.mjs} +2 -2
- package/dist/{route-policy-DDszB6dQ.mjs.map → route-policy-Cy-oSUro.mjs.map} +1 -1
- package/dist/{router-builder-BewIsj7V.d.mts → router-builder-BfbEdxew.d.mts} +2 -2
- package/dist/{router-builder-BewIsj7V.d.mts.map → router-builder-BfbEdxew.d.mts.map} +1 -1
- package/dist/{router-builder-DoaDAmK8.mjs → router-builder-U-kiHlqo.mjs} +3 -3
- package/dist/{router-builder-DoaDAmK8.mjs.map → router-builder-U-kiHlqo.mjs.map} +1 -1
- package/dist/{session-ChXx7jG5.d.mts → session-8uNRCplB.d.mts} +3 -3
- package/dist/session-8uNRCplB.d.mts.map +1 -0
- package/dist/{settings-CRkMOwcz.mjs → settings-CrEgdXc0.mjs} +3 -3
- package/dist/{settings-CRkMOwcz.mjs.map → settings-CrEgdXc0.mjs.map} +1 -1
- package/dist/{token-2CJq89za.mjs → token-B1FRPTVt.mjs} +1 -1
- package/dist/upload-Jgs9BFC4.d.mts +55 -0
- package/dist/upload-Jgs9BFC4.d.mts.map +1 -0
- package/dist/{upload-config-Be7w0Dfx.mjs → upload-config-DEnNEwL4.mjs} +2 -2
- package/dist/upload-config-DEnNEwL4.mjs.map +1 -0
- package/dist/{url-for-EQsmb3yi.mjs → url-for-CLtZIeYd.mjs} +3 -3
- package/dist/{url-for-EQsmb3yi.mjs.map → url-for-CLtZIeYd.mjs.map} +1 -1
- package/dist/{validate-CzjCbRUn.d.mts → validate-D4Poe2EE.d.mts} +3 -3
- package/dist/validate-D4Poe2EE.d.mts.map +1 -0
- package/dist/{web-crypto-G-m6c6w2.mjs → web-crypto-B6iM0yYx.mjs} +2 -2
- package/dist/{web-crypto-G-m6c6w2.mjs.map → web-crypto-B6iM0yYx.mjs.map} +1 -1
- package/dist/web.d.mts +3 -3
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +9 -2
- package/dist/adapter-BZ1WzN1z.d.mts.map +0 -1
- package/dist/allowed-hosts-D6qcuK5I.d.mts.map +0 -1
- package/dist/application-Bs30gJF1.mjs +0 -14
- package/dist/application-Bs30gJF1.mjs.map +0 -1
- package/dist/application-D5Iiy7rt.d.mts.map +0 -1
- package/dist/bootstrap-B_sGJNSz.mjs +0 -12
- package/dist/breach-padding-C-Dnq8CS.d.mts.map +0 -1
- package/dist/context-CRJzl_Mj.mjs +0 -12
- package/dist/context-CRJzl_Mj.mjs.map +0 -1
- package/dist/core-CsMDdzNE.mjs +0 -12
- package/dist/cors-2Bwhyhpt.d.mts.map +0 -1
- package/dist/csrf-BDAZK2mm.d.mts.map +0 -1
- package/dist/decorate-CLeX6hbL.mjs +0 -13
- package/dist/di-hooks-CiNaIu12.mjs.map +0 -1
- package/dist/handler-Cw4mr3ls.mjs +0 -12
- package/dist/helmet-CEOmo516.d.mts.map +0 -1
- package/dist/lazy-serve-static-D94xvah5.mjs +0 -12
- package/dist/lazy-serve-static-D94xvah5.mjs.map +0 -1
- package/dist/rate-limit-BgoeahE5.d.mts.map +0 -1
- package/dist/reply-tlUaowib.mjs +0 -12
- package/dist/reply-tlUaowib.mjs.map +0 -1
- package/dist/request-id-CVzJ1uHD.d.mts.map +0 -1
- package/dist/session-ChXx7jG5.d.mts.map +0 -1
- package/dist/upload-DkT2p1gd.d.mts +0 -104
- package/dist/upload-DkT2p1gd.d.mts.map +0 -1
- package/dist/upload-config-Be7w0Dfx.mjs.map +0 -1
- package/dist/validate-CzjCbRUn.d.mts.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.6.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}from"../../core/logger.mjs";import{r as registerDisposable}from"../../disposables-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import{r as registerDisposable}from"../../disposables-BgUIg4s1.mjs";import{t as isProduction}from"../../is-production-MYGnN2Nv.mjs";import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-DR7zkOUf.mjs";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=/* @__PURE__ */ new Map;empty=/* @__PURE__ */ new Set;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear(),this.empty.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),this.empty.delete(sid),null):entry.data:null}async set(sid,data,maxAge){for(this.sessions.delete(sid),this.sessions.set(sid,{data,expires:Date.now()+maxAge}),this.empty.delete(sid),Object.keys(data).length===0&&this.empty.add(sid);this.sessions.size>1e4;){let victim=this.empty.values().next().value??this.sessions.keys().next().value;this.sessions.delete(victim),this.empty.delete(victim)}}async destroy(sid){this.sessions.delete(sid),this.empty.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge,this.sessions.delete(sid),this.sessions.set(sid,entry))}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&(this.sessions.delete(sid),this.empty.delete(sid))}};function secretList(secret){let list=Array.isArray(secret)?secret:[secret];if(list.length===0||list.some(s=>typeof s!=`string`||s.length===0))throw Error("session(): `secret` must be a non-empty string or list of strings");return list}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secrets){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),provided=Buffer.from(raw.slice(dotIndex+1));for(let[index,secret]of secrets.entries()){let expected=Buffer.from(createHmac(`sha256`,secret).update(value).digest(`base64url`));if(provided.length===expected.length&&timingSafeEqual(provided,expected))return{value,stale:index>0}}return!1}function session(options){if(options.store===`cookie`)return cookieSession(options);let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,secrets=secretList(options.secret),secret=secrets[0],store=options.store??new MemoryStore,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),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,staleSignature=!1;if(signedCookie){let unsigned=unsign(signedCookie,secrets);unsigned&&(sid=unsigned.value,staleSignature=unsigned.stale,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),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,setCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,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))}),!isNew&&(rolling||staleSignature)&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}const cookieLog=createLogger(`Session`);function sealer(secrets,cookieName){let keys=secrets.map(secret=>Buffer.from(hkdfSync(`sha256`,secret,`kick.session`,`cookie-store-v1`,32))),key=keys[0],aad=Buffer.from(cookieName);return{seal(payload){let iv=randomBytes(12),cipher=createCipheriv(`aes-256-gcm`,key,iv).setAAD(aad),body=Buffer.concat([cipher.update(JSON.stringify(payload),`utf8`),cipher.final()]);return`v1.${Buffer.concat([iv,cipher.getAuthTag(),body]).toString(`base64url`)}`},open(value){if(!value.startsWith(`v1.`))return null;let raw;try{raw=Buffer.from(value.slice(3),`base64url`)}catch{return null}if(raw.length<29)return null;for(let[index,k]of keys.entries())try{let decipher=createDecipheriv(`aes-256-gcm`,k,raw.subarray(0,12)).setAAD(aad).setAuthTag(raw.subarray(12,28)),json=Buffer.concat([decipher.update(raw.subarray(28)),decipher.final()]),payload=JSON.parse(json.toString(`utf8`));return typeof payload?.i!=`string`||typeof payload.e!=`number`||!payload.d||typeof payload.d!=`object`?null:payload.e>Date.now()?{payload,stale:index>0}:null}catch{}return null}}}function cookieSession(options){let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,{seal,open}=sealer(secretList(options.secret),cookieName),cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{}},warnedSize=!1;return(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let opened=cookies[cookieName]?open(cookies[cookieName]):null,existing=opened?.payload??null,isNew=!existing,id=existing?.i??randomUUID(),destroyed=!1,written=existing&&!opened?.stale?JSON.stringify(existing.d):void 0,write=(force=!1)=>{if(res.headersSent)return;if(destroyed){replaceCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)});return}let json=JSON.stringify(sessionObj.data);if(json===written&&!force&&(!rolling||isNew)||written===void 0&&json===`{}`&&!saveUninitialized&&!force)return;let value=seal({i:id,d:sessionObj.data,e:Date.now()+maxAge});value.length+cookieName.length>4e3&&!warnedSize&&(warnedSize=!0,cookieLog.warn(`session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, so this session will not be kept. Store less in it, or use a shared store.`)),replaceCookie(res,cookieName,value,{...cookieDefaults,maxAge}),written=json};for(let method of[`writeHead`,`flushHeaders`,`write`,`end`]){let original=res[method];typeof original==`function`&&(res[method]=function(...args){return write(),original.apply(this,args)})}res.on?.(`finish`,()=>write());let sessionObj={get id(){return id},data:existing?{...existing.d}:{},async regenerate(){id=randomUUID(),sessionObj.data={},written=void 0,write(!0)},async destroy(){destroyed=!0,sessionObj.data={},write()},async save(){write()}};req.session=sessionObj,next()}}export{MemoryStore,session};
|
|
12
12
|
//# sourceMappingURL=session.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.mjs","names":[],"sources":["../../../src/http/middleware/session.ts"],"sourcesContent":["import { parseCookieHeader, replaceCookie, setCookie } from './respond'\nimport {\n createCipheriv,\n createDecipheriv,\n createHmac,\n hkdfSync,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from 'node:crypto'\nimport { createLogger } from '../../core/logger'\nimport type { Request, Response, NextFunction } from 'express'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { isProduction } from '../../core/is-production'\n\n/**\n * What a session holds. Augment it to type your keys — undeclared keys stay\n * readable as `unknown`:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface SessionData { userId?: string; cart?: string[] }\n * }\n * ```\n */\nexport interface SessionData {\n [key: string]: unknown\n}\n\nexport interface SessionStore {\n get(sid: string): Promise<SessionData | null>\n set(sid: string, data: SessionData, maxAge: number): Promise<void>\n destroy(sid: string): Promise<void>\n touch?(sid: string, maxAge: number): Promise<void>\n}\n\nexport interface Session {\n id: string\n data: SessionData\n regenerate(): Promise<void>\n destroy(): Promise<void>\n save(): Promise<void>\n}\n\nexport interface SessionOptions {\n /**\n * Secret that signs the session cookie — or, with `store: 'cookie'`,\n * encrypts it (required).\n *\n * Pass a list to rotate without logging everyone out: the first secret signs\n * new cookies, every secret is accepted, and a cookie made with an older one\n * is re-issued with the first. Drop the old secret once sessions have moved\n * over (after `maxAge`).\n *\n * ```ts\n * session({ secret: [process.env.SESSION_SECRET!, process.env.SESSION_SECRET_OLD!] })\n * ```\n */\n secret: string | string[]\n /** Cookie name (default: 'kick.sid') */\n cookieName?: string\n /** Session max age in milliseconds (default: 86400000 = 24h) */\n maxAge?: number\n /** Reset maxAge on every response (default: false) */\n rolling?: boolean\n /** Save new sessions that have not been modified (default: true) */\n saveUninitialized?: boolean\n /** Cookie options */\n cookie?: {\n httpOnly?: boolean\n secure?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n path?: string\n domain?: string\n }\n /**\n * Where session data lives. Default: in memory, in this process.\n *\n * `'cookie'` keeps it in the session cookie itself, encrypted with\n * AES-256-GCM under a key derived from `secret`: every instance reads the\n * same session with nothing shared between them — serverless functions,\n * several containers. The data has to fit a cookie (about 4 KB).\n *\n * Or pass a store shared between instances (`KvSessionStore`, Redis).\n */\n store?: SessionStore | 'cookie'\n}\n\n// ── In-Memory Store ───────────────────────────────────────────────────\n\n// ponytail: fixed cap for the single-instance default; a shared store\n// (KvSessionStore, Redis) is the answer for more.\nconst MAX_SESSIONS = 10_000\n\n/** @internal Exported for tests. */\nexport class MemoryStore implements SessionStore {\n private readonly sessions = new Map<string, { data: SessionData; expires: number }>()\n /** Sessions with no data, oldest first: evicted before any that hold some. */\n private readonly empty = new Set<string>()\n private readonly cleanupInterval: ReturnType<typeof setInterval>\n\n constructor() {\n // Purge expired sessions every 60 seconds\n this.cleanupInterval = setInterval(() => this.purge(), 60_000)\n this.cleanupInterval.unref()\n // Symmetric teardown: Application.shutdown() drains the disposables\n // registry — without this, every in-process app re-create (tests, HMR)\n // leaked one live interval + its session Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all sessions. */\n dispose(): void {\n clearInterval(this.cleanupInterval)\n this.sessions.clear()\n this.empty.clear()\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const entry = this.sessions.get(sid)\n if (!entry) return null\n if (Date.now() > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n return null\n }\n return entry.data\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n // Deleted first so the map stays in last-written order, oldest at the front.\n this.sessions.delete(sid)\n this.sessions.set(sid, { data, expires: Date.now() + maxAge })\n this.empty.delete(sid)\n if (Object.keys(data).length === 0) this.empty.add(sid)\n // A session is created for every visitor without a cookie, so a client\n // can make as many as it sends requests. Past the cap, an empty session\n // goes first — a flood of cookieless requests makes only empty ones, so\n // it can't push out sessions that hold a login; only when none is empty\n // does the least recently written go.\n while (this.sessions.size > MAX_SESSIONS) {\n const victim = this.empty.values().next().value ?? this.sessions.keys().next().value!\n this.sessions.delete(victim)\n this.empty.delete(victim)\n }\n }\n\n async destroy(sid: string): Promise<void> {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const entry = this.sessions.get(sid)\n if (entry) {\n entry.expires = Date.now() + maxAge\n this.sessions.delete(sid)\n this.sessions.set(sid, entry)\n }\n }\n\n private purge() {\n const now = Date.now()\n for (const [sid, entry] of this.sessions) {\n if (now > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n }\n }\n}\n\n// ── Cookie Signing ────────────────────────────────────────────────────\n\n/** `secret` as a non-empty list, newest first. */\nfunction secretList(secret: string | string[]): string[] {\n const list = Array.isArray(secret) ? secret : [secret]\n if (list.length === 0 || list.some((s) => typeof s !== 'string' || s.length === 0)) {\n throw new Error('session(): `secret` must be a non-empty string or list of strings')\n }\n return list\n}\n\nfunction sign(value: string, secret: string): string {\n const signature = createHmac('sha256', secret).update(value).digest('base64url')\n return `s:${value}.${signature}`\n}\n\n/**\n * The signed value, and whether it was signed with an older secret than the\n * first (so the caller re-issues it); false when no secret verifies it.\n */\nfunction unsign(signed: string, secrets: string[]): { value: string; stale: boolean } | false {\n if (!signed.startsWith('s:')) return false\n const raw = signed.slice(2)\n const dotIndex = raw.lastIndexOf('.')\n if (dotIndex === -1) return false\n\n const value = raw.slice(0, dotIndex)\n const provided = Buffer.from(raw.slice(dotIndex + 1))\n\n for (const [index, secret] of secrets.entries()) {\n const expected = Buffer.from(createHmac('sha256', secret).update(value).digest('base64url'))\n if (provided.length === expected.length && timingSafeEqual(provided, expected)) {\n return { value, stale: index > 0 }\n }\n }\n return false\n}\n\n// ── Middleware Factory ────────────────────────────────────────────────\n\n/**\n * Session management middleware.\n *\n * Attaches a `req.session` object with `id`, `data`, `regenerate()`,\n * `destroy()`, and `save()` methods. Session IDs are signed with\n * HMAC-SHA256 to prevent cookie tampering.\n *\n * Reads the session cookie from `req.cookies` when an upstream cookie\n * parser is present; otherwise parses `req.headers.cookie` directly, so\n * no cookie parser is required upstream.\n *\n * @example\n * ```ts\n * import { session } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * session({ secret: process.env.SESSION_SECRET! }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function session(options: SessionOptions) {\n if (options.store === 'cookie') return cookieSession(options)\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n cookie: cookieOpts = {},\n } = options\n const secrets = secretList(options.secret)\n const secret = secrets[0]\n const store = (options.store as SessionStore | undefined) ?? new MemoryStore()\n\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n maxAge,\n }\n\n return async (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const signedCookie = cookies[cookieName]\n let sid: string | false = false\n let sessionData: SessionData | null = null\n let isNew = false\n let staleSignature = false\n\n // Attempt to recover existing session\n if (signedCookie) {\n const unsigned = unsign(signedCookie, secrets)\n if (unsigned) {\n sid = unsigned.value\n staleSignature = unsigned.stale\n sessionData = await store.get(sid)\n }\n }\n\n // Create new session if none found\n if (!sid || !sessionData) {\n sid = randomUUID()\n sessionData = {}\n isNew = true\n }\n\n let currentSid = sid\n let currentData = { ...sessionData }\n let destroyed = false\n\n const sessionObj: Session = {\n get id() {\n return currentSid\n },\n data: currentData,\n\n async regenerate() {\n await store.destroy(currentSid)\n currentSid = randomUUID()\n currentData = {}\n sessionObj.data = currentData\n await store.set(currentSid, currentData, maxAge)\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n },\n\n async destroy() {\n await store.destroy(currentSid)\n destroyed = true\n currentData = {}\n sessionObj.data = currentData\n // Expire the cookie the same way it was set — `res.clearCookie` is\n // Express-only and threw under Fastify and h3.\n setCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n },\n\n async save() {\n if (!destroyed) {\n await store.set(currentSid, currentData, maxAge)\n }\n },\n }\n\n ;(req as any).session = sessionObj\n\n // Set cookie for new sessions\n if (isNew) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n // Auto-save on response finish\n res.on('finish', async () => {\n if (destroyed) return\n if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return\n\n await store.set(currentSid, currentData, maxAge)\n\n if (rolling && !isNew) {\n if (store.touch) {\n await store.touch(currentSid, maxAge)\n }\n }\n })\n\n // Rolling refreshes the cookie on every response; a cookie signed with an\n // older secret is re-signed with the current one.\n if (!isNew && (rolling || staleSignature)) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n next()\n }\n}\n\n// ── Cookie store ──────────────────────────────────────────────────────\n\nconst cookieLog = createLogger('Session')\n\n/** Browsers drop a cookie larger than 4096 bytes, name and attributes included. */\nconst COOKIE_LIMIT = 4000\n\ninterface CookiePayload {\n /** Session id. */\n i: string\n d: SessionData\n /** Expiry, ms since epoch. */\n e: number\n}\n\n/**\n * AES-256-GCM, with the cookie name as associated data: `v1.<iv|tag|ciphertext>`.\n * Seals with the first secret's key; opens with any of them.\n */\nfunction sealer(secrets: string[], cookieName: string) {\n const keys = secrets.map((secret) =>\n Buffer.from(hkdfSync('sha256', secret, 'kick.session', 'cookie-store-v1', 32)),\n )\n const key = keys[0]\n const aad = Buffer.from(cookieName)\n return {\n seal(payload: CookiePayload): string {\n const iv = randomBytes(12)\n const cipher = createCipheriv('aes-256-gcm', key, iv).setAAD(aad)\n const body = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()])\n return `v1.${Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url')}`\n },\n /**\n * The payload and whether an older secret's key opened it, or null for\n * anything forged, altered, expired or malformed.\n */\n open(value: string): { payload: CookiePayload; stale: boolean } | null {\n if (!value.startsWith('v1.')) return null\n let raw: Buffer\n try {\n raw = Buffer.from(value.slice(3), 'base64url')\n } catch {\n return null\n }\n if (raw.length < 29) return null\n for (const [index, k] of keys.entries()) {\n try {\n const decipher = createDecipheriv('aes-256-gcm', k, raw.subarray(0, 12))\n .setAAD(aad)\n .setAuthTag(raw.subarray(12, 28))\n const json = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()])\n const payload = JSON.parse(json.toString('utf8')) as CookiePayload\n if (typeof payload?.i !== 'string' || typeof payload.e !== 'number') return null\n if (!payload.d || typeof payload.d !== 'object') return null\n return payload.e > Date.now() ? { payload, stale: index > 0 } : null\n } catch {\n // Not this key (the auth tag fails) — try the next.\n }\n }\n return null\n },\n }\n}\n\ntype HeaderWriter = (...args: unknown[]) => unknown\n\n/**\n * `session({ store: 'cookie' })`. The cookie is written as late as possible —\n * just before the response's headers go out — so every change made while\n * handling the request is in it, nested ones included. `save()` writes it\n * straight away, for code that redirects right after.\n */\nfunction cookieSession(options: SessionOptions) {\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n cookie: cookieOpts = {},\n } = options\n const { seal, open } = sealer(secretList(options.secret), cookieName)\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n }\n let warnedSize = false\n\n return (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const opened = cookies[cookieName] ? open(cookies[cookieName]) : null\n const existing = opened?.payload ?? null\n const isNew = !existing\n\n let id = existing?.i ?? randomUUID()\n let destroyed = false\n // What the browser already holds, to skip rewriting an unchanged cookie.\n // A cookie sealed with an older secret counts as nothing held, so it is\n // rewritten with the current one.\n let written = existing && !opened?.stale ? JSON.stringify(existing.d) : undefined\n\n const write = (force = false) => {\n if (res.headersSent) return\n if (destroyed) {\n replaceCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n return\n }\n const json = JSON.stringify(sessionObj.data)\n // Unchanged: leave the browser's copy, unless `rolling` renews it.\n if (json === written && !force && !(rolling && !isNew)) return\n // A new, empty session gets a cookie only with saveUninitialized.\n if (written === undefined && json === '{}' && !saveUninitialized && !force) return\n const value = seal({ i: id, d: sessionObj.data, e: Date.now() + maxAge })\n if (value.length + cookieName.length > COOKIE_LIMIT && !warnedSize) {\n warnedSize = true\n cookieLog.warn(\n `session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, ` +\n 'so this session will not be kept. Store less in it, or use a shared store.',\n )\n }\n replaceCookie(res, cookieName, value, { ...cookieDefaults, maxAge })\n written = json\n }\n\n // Just before the headers go out, on whichever call sends them first —\n // Node responses go through writeHead; the web driver's buffered end()\n // does not.\n for (const method of ['writeHead', 'flushHeaders', 'write', 'end'] as const) {\n const original = (res as unknown as Record<string, HeaderWriter | undefined>)[method]\n if (typeof original !== 'function') continue\n ;(res as unknown as Record<string, HeaderWriter>)[method] = function (\n this: unknown,\n ...args: unknown[]\n ) {\n write()\n return original.apply(this, args)\n }\n }\n\n // h3 called through fetch hands middleware a stand-in response whose\n // headers join the route's response after `finish` — the last chance there.\n // On a Node response `finish` comes after the headers, so this is a no-op.\n ;(res as unknown as { on?: (event: string, fn: () => void) => unknown }).on?.('finish', () =>\n write(),\n )\n\n const sessionObj: Session = {\n get id() {\n return id\n },\n data: existing ? { ...existing.d } : {},\n async regenerate() {\n id = randomUUID()\n sessionObj.data = {}\n written = undefined\n write(true)\n },\n async destroy() {\n destroyed = true\n sessionObj.data = {}\n write()\n },\n async save() {\n write()\n },\n }\n ;(req as any).session = sessionObj\n next()\n }\n}\n"],"mappings":";;;;;;;;;;yYAgGA,IAAa,YAAb,KAAiD,CAC/C,yBAA4B,IAAI,IAEhC,sBAAyB,IAAI,IAC7B,gBAEA,aAAc,CAEZ,KAAK,gBAAkB,gBAAkB,KAAK,MAAM,EAAG,GAAM,EAC7D,KAAK,gBAAgB,MAAM,EAI3B,uBAAyB,KAAK,QAAQ,CAAC,CACzC,CAGA,SAAgB,CACd,cAAc,KAAK,eAAe,EAClC,KAAK,SAAS,MAAM,EACpB,KAAK,MAAM,MAAM,CACnB,CAEA,MAAM,IAAI,IAA0C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IAAI,KAAK,CAAC,CAAE,CAAC,EACzF,MACF,CACA,IAAM,KAAO,KAAK,UAAU,WAAW,IAAI,EAI3C,GAFI,OAAS,SAAW,CAAC,QAAW,UAAY,QAE5C,UAAY,IAAA,IAAa,OAAS,MAAQ,CAAC,mBAAqB,CAAC,MAAO,OAC5E,IAAM,MAAQ,KAAK,CAAE,EAAG,GAAI,EAAG,WAAW,KAAM,EAAG,KAAK,IAAI,EAAI,MAAO,CAAC,EACpE,MAAM,OAAS,WAAW,OAAS,KAAgB,CAAC,aACtD,WAAa,GACb,UAAU,KACR,qBAAqB,MAAM,OAAO,oHAEpC,GAEF,cAAc,IAAK,WAAY,MAAO,CAAE,GAAG,eAAgB,MAAO,CAAC,EACnE,QAAU,IACZ,EAKA,IAAK,IAAM,SAAU,CAAC,YAAa,eAAgB,QAAS,KAAK,EAAY,CAC3E,IAAM,SAAY,IAA4D,QAC1E,OAAO,UAAa,aACvB,IAAiD,QAAU,SAE1D,GAAG,KACH,CAEA,OADA,MAAM,EACC,SAAS,MAAM,KAAM,IAAI,CAClC,EACF,CAKC,IAAwE,KAAK,aAC5E,MAAM,CACR,EAEA,IAAM,WAAsB,CAC1B,IAAI,IAAK,CACP,OAAO,EACT,EACA,KAAM,SAAW,CAAE,GAAG,SAAS,CAAE,EAAI,CAAC,EACtC,MAAM,YAAa,CACjB,GAAK,WAAW,EAChB,WAAW,KAAO,CAAC,EACnB,QAAU,IAAA,GACV,MAAM,EAAI,CACZ,EACA,MAAM,SAAU,CACd,UAAY,GACZ,WAAW,KAAO,CAAC,EACnB,MAAM,CACR,EACA,MAAM,MAAO,CACX,MAAM,CACR,CACF,EACC,IAAa,QAAU,WACxB,KAAK,CACP,CACF"}
|
|
1
|
+
{"version":3,"file":"session.mjs","names":[],"sources":["../../../src/http/middleware/session.ts"],"sourcesContent":["import { parseCookieHeader, replaceCookie, setCookie } from './respond'\nimport {\n createCipheriv,\n createDecipheriv,\n createHmac,\n hkdfSync,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from 'node:crypto'\nimport { createLogger } from '../../core/logger'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n\nimport { registerDisposable } from '../../core/disposables'\nimport { isProduction } from '../../core/is-production'\n\n/**\n * What a session holds. Augment it to type your keys — undeclared keys stay\n * readable as `unknown`:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface SessionData { userId?: string; cart?: string[] }\n * }\n * ```\n */\nexport interface SessionData {\n [key: string]: unknown\n}\n\nexport interface SessionStore {\n get(sid: string): Promise<SessionData | null>\n set(sid: string, data: SessionData, maxAge: number): Promise<void>\n destroy(sid: string): Promise<void>\n touch?(sid: string, maxAge: number): Promise<void>\n}\n\nexport interface Session {\n id: string\n data: SessionData\n regenerate(): Promise<void>\n destroy(): Promise<void>\n save(): Promise<void>\n}\n\nexport interface SessionOptions {\n /**\n * Secret that signs the session cookie — or, with `store: 'cookie'`,\n * encrypts it (required).\n *\n * Pass a list to rotate without logging everyone out: the first secret signs\n * new cookies, every secret is accepted, and a cookie made with an older one\n * is re-issued with the first. Drop the old secret once sessions have moved\n * over (after `maxAge`).\n *\n * ```ts\n * session({ secret: [process.env.SESSION_SECRET!, process.env.SESSION_SECRET_OLD!] })\n * ```\n */\n secret: string | string[]\n /** Cookie name (default: 'kick.sid') */\n cookieName?: string\n /** Session max age in milliseconds (default: 86400000 = 24h) */\n maxAge?: number\n /** Reset maxAge on every response (default: false) */\n rolling?: boolean\n /** Save new sessions that have not been modified (default: true) */\n saveUninitialized?: boolean\n /** Cookie options */\n cookie?: {\n httpOnly?: boolean\n secure?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n path?: string\n domain?: string\n }\n /**\n * Where session data lives. Default: in memory, in this process.\n *\n * `'cookie'` keeps it in the session cookie itself, encrypted with\n * AES-256-GCM under a key derived from `secret`: every instance reads the\n * same session with nothing shared between them — serverless functions,\n * several containers. The data has to fit a cookie (about 4 KB).\n *\n * Or pass a store shared between instances (`KvSessionStore`, Redis).\n */\n store?: SessionStore | 'cookie'\n}\n\n// ── In-Memory Store ───────────────────────────────────────────────────\n\n// ponytail: fixed cap for the single-instance default; a shared store\n// (KvSessionStore, Redis) is the answer for more.\nconst MAX_SESSIONS = 10_000\n\n/** @internal Exported for tests. */\nexport class MemoryStore implements SessionStore {\n private readonly sessions = new Map<string, { data: SessionData; expires: number }>()\n /** Sessions with no data, oldest first: evicted before any that hold some. */\n private readonly empty = new Set<string>()\n private readonly cleanupInterval: ReturnType<typeof setInterval>\n\n constructor() {\n // Purge expired sessions every 60 seconds\n this.cleanupInterval = setInterval(() => this.purge(), 60_000)\n this.cleanupInterval.unref()\n // Symmetric teardown: Application.shutdown() drains the disposables\n // registry — without this, every in-process app re-create (tests, HMR)\n // leaked one live interval + its session Map.\n registerDisposable(() => this.dispose())\n }\n\n /** Clear the cleanup interval and drop all sessions. */\n dispose(): void {\n clearInterval(this.cleanupInterval)\n this.sessions.clear()\n this.empty.clear()\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const entry = this.sessions.get(sid)\n if (!entry) return null\n if (Date.now() > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n return null\n }\n return entry.data\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n // Deleted first so the map stays in last-written order, oldest at the front.\n this.sessions.delete(sid)\n this.sessions.set(sid, { data, expires: Date.now() + maxAge })\n this.empty.delete(sid)\n if (Object.keys(data).length === 0) this.empty.add(sid)\n // A session is created for every visitor without a cookie, so a client\n // can make as many as it sends requests. Past the cap, an empty session\n // goes first — a flood of cookieless requests makes only empty ones, so\n // it can't push out sessions that hold a login; only when none is empty\n // does the least recently written go.\n while (this.sessions.size > MAX_SESSIONS) {\n const victim = this.empty.values().next().value ?? this.sessions.keys().next().value!\n this.sessions.delete(victim)\n this.empty.delete(victim)\n }\n }\n\n async destroy(sid: string): Promise<void> {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const entry = this.sessions.get(sid)\n if (entry) {\n entry.expires = Date.now() + maxAge\n this.sessions.delete(sid)\n this.sessions.set(sid, entry)\n }\n }\n\n private purge() {\n const now = Date.now()\n for (const [sid, entry] of this.sessions) {\n if (now > entry.expires) {\n this.sessions.delete(sid)\n this.empty.delete(sid)\n }\n }\n }\n}\n\n// ── Cookie Signing ────────────────────────────────────────────────────\n\n/** `secret` as a non-empty list, newest first. */\nfunction secretList(secret: string | string[]): string[] {\n const list = Array.isArray(secret) ? secret : [secret]\n if (list.length === 0 || list.some((s) => typeof s !== 'string' || s.length === 0)) {\n throw new Error('session(): `secret` must be a non-empty string or list of strings')\n }\n return list\n}\n\nfunction sign(value: string, secret: string): string {\n const signature = createHmac('sha256', secret).update(value).digest('base64url')\n return `s:${value}.${signature}`\n}\n\n/**\n * The signed value, and whether it was signed with an older secret than the\n * first (so the caller re-issues it); false when no secret verifies it.\n */\nfunction unsign(signed: string, secrets: string[]): { value: string; stale: boolean } | false {\n if (!signed.startsWith('s:')) return false\n const raw = signed.slice(2)\n const dotIndex = raw.lastIndexOf('.')\n if (dotIndex === -1) return false\n\n const value = raw.slice(0, dotIndex)\n const provided = Buffer.from(raw.slice(dotIndex + 1))\n\n for (const [index, secret] of secrets.entries()) {\n const expected = Buffer.from(createHmac('sha256', secret).update(value).digest('base64url'))\n if (provided.length === expected.length && timingSafeEqual(provided, expected)) {\n return { value, stale: index > 0 }\n }\n }\n return false\n}\n\n// ── Middleware Factory ────────────────────────────────────────────────\n\n/**\n * Session management middleware.\n *\n * Attaches a `req.session` object with `id`, `data`, `regenerate()`,\n * `destroy()`, and `save()` methods. Session IDs are signed with\n * HMAC-SHA256 to prevent cookie tampering.\n *\n * Reads the session cookie from `req.cookies` when an upstream cookie\n * parser is present; otherwise parses `req.headers.cookie` directly, so\n * no cookie parser is required upstream.\n *\n * @example\n * ```ts\n * import { session } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middlewares: [\n * session({ secret: process.env.SESSION_SECRET! }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function session(options: SessionOptions) {\n if (options.store === 'cookie') return cookieSession(options)\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n cookie: cookieOpts = {},\n } = options\n const secrets = secretList(options.secret)\n const secret = secrets[0]\n const store = (options.store as SessionStore | undefined) ?? new MemoryStore()\n\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n maxAge,\n }\n\n return async (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const signedCookie = cookies[cookieName]\n let sid: string | false = false\n let sessionData: SessionData | null = null\n let isNew = false\n let staleSignature = false\n\n // Attempt to recover existing session\n if (signedCookie) {\n const unsigned = unsign(signedCookie, secrets)\n if (unsigned) {\n sid = unsigned.value\n staleSignature = unsigned.stale\n sessionData = await store.get(sid)\n }\n }\n\n // Create new session if none found\n if (!sid || !sessionData) {\n sid = randomUUID()\n sessionData = {}\n isNew = true\n }\n\n let currentSid = sid\n let currentData = { ...sessionData }\n let destroyed = false\n\n const sessionObj: Session = {\n get id() {\n return currentSid\n },\n data: currentData,\n\n async regenerate() {\n await store.destroy(currentSid)\n currentSid = randomUUID()\n currentData = {}\n sessionObj.data = currentData\n await store.set(currentSid, currentData, maxAge)\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n },\n\n async destroy() {\n await store.destroy(currentSid)\n destroyed = true\n currentData = {}\n sessionObj.data = currentData\n // Expire the cookie the same way it was set — `res.clearCookie` is\n // Express-only and threw under Fastify and h3.\n setCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n },\n\n async save() {\n if (!destroyed) {\n await store.set(currentSid, currentData, maxAge)\n }\n },\n }\n\n ;(req as any).session = sessionObj\n\n // Set cookie for new sessions\n if (isNew) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n // Auto-save on response finish\n res.on('finish', async () => {\n if (destroyed) return\n if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return\n\n await store.set(currentSid, currentData, maxAge)\n\n if (rolling && !isNew) {\n if (store.touch) {\n await store.touch(currentSid, maxAge)\n }\n }\n })\n\n // Rolling refreshes the cookie on every response; a cookie signed with an\n // older secret is re-signed with the current one.\n if (!isNew && (rolling || staleSignature)) {\n setCookie(res, cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n next()\n }\n}\n\n// ── Cookie store ──────────────────────────────────────────────────────\n\nconst cookieLog = createLogger('Session')\n\n/** Browsers drop a cookie larger than 4096 bytes, name and attributes included. */\nconst COOKIE_LIMIT = 4000\n\ninterface CookiePayload {\n /** Session id. */\n i: string\n d: SessionData\n /** Expiry, ms since epoch. */\n e: number\n}\n\n/**\n * AES-256-GCM, with the cookie name as associated data: `v1.<iv|tag|ciphertext>`.\n * Seals with the first secret's key; opens with any of them.\n */\nfunction sealer(secrets: string[], cookieName: string) {\n const keys = secrets.map((secret) =>\n Buffer.from(hkdfSync('sha256', secret, 'kick.session', 'cookie-store-v1', 32)),\n )\n const key = keys[0]\n const aad = Buffer.from(cookieName)\n return {\n seal(payload: CookiePayload): string {\n const iv = randomBytes(12)\n const cipher = createCipheriv('aes-256-gcm', key, iv).setAAD(aad)\n const body = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()])\n return `v1.${Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url')}`\n },\n /**\n * The payload and whether an older secret's key opened it, or null for\n * anything forged, altered, expired or malformed.\n */\n open(value: string): { payload: CookiePayload; stale: boolean } | null {\n if (!value.startsWith('v1.')) return null\n let raw: Buffer\n try {\n raw = Buffer.from(value.slice(3), 'base64url')\n } catch {\n return null\n }\n if (raw.length < 29) return null\n for (const [index, k] of keys.entries()) {\n try {\n const decipher = createDecipheriv('aes-256-gcm', k, raw.subarray(0, 12))\n .setAAD(aad)\n .setAuthTag(raw.subarray(12, 28))\n const json = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()])\n const payload = JSON.parse(json.toString('utf8')) as CookiePayload\n if (typeof payload?.i !== 'string' || typeof payload.e !== 'number') return null\n if (!payload.d || typeof payload.d !== 'object') return null\n return payload.e > Date.now() ? { payload, stale: index > 0 } : null\n } catch {\n // Not this key (the auth tag fails) — try the next.\n }\n }\n return null\n },\n }\n}\n\ntype HeaderWriter = (...args: unknown[]) => unknown\n\n/**\n * `session({ store: 'cookie' })`. The cookie is written as late as possible —\n * just before the response's headers go out — so every change made while\n * handling the request is in it, nested ones included. `save()` writes it\n * straight away, for code that redirects right after.\n */\nfunction cookieSession(options: SessionOptions) {\n const {\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n cookie: cookieOpts = {},\n } = options\n const { seal, open } = sealer(secretList(options.secret), cookieName)\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? isProduction(),\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n }\n let warnedSize = false\n\n return (req: Request, res: Response, next: NextFunction) => {\n let cookies = (req as any).cookies as Record<string, string> | undefined\n if (!cookies) {\n const header = req.headers.cookie\n cookies = header ? parseCookieHeader(header) : {}\n }\n const opened = cookies[cookieName] ? open(cookies[cookieName]) : null\n const existing = opened?.payload ?? null\n const isNew = !existing\n\n let id = existing?.i ?? randomUUID()\n let destroyed = false\n // What the browser already holds, to skip rewriting an unchanged cookie.\n // A cookie sealed with an older secret counts as nothing held, so it is\n // rewritten with the current one.\n let written = existing && !opened?.stale ? JSON.stringify(existing.d) : undefined\n\n const write = (force = false) => {\n if (res.headersSent) return\n if (destroyed) {\n replaceCookie(res, cookieName, '', { ...cookieDefaults, maxAge: 0, expires: new Date(0) })\n return\n }\n const json = JSON.stringify(sessionObj.data)\n // Unchanged: leave the browser's copy, unless `rolling` renews it.\n if (json === written && !force && !(rolling && !isNew)) return\n // A new, empty session gets a cookie only with saveUninitialized.\n if (written === undefined && json === '{}' && !saveUninitialized && !force) return\n const value = seal({ i: id, d: sessionObj.data, e: Date.now() + maxAge })\n if (value.length + cookieName.length > COOKIE_LIMIT && !warnedSize) {\n warnedSize = true\n cookieLog.warn(\n `session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, ` +\n 'so this session will not be kept. Store less in it, or use a shared store.',\n )\n }\n replaceCookie(res, cookieName, value, { ...cookieDefaults, maxAge })\n written = json\n }\n\n // Just before the headers go out, on whichever call sends them first —\n // Node responses go through writeHead; the web driver's buffered end()\n // does not.\n for (const method of ['writeHead', 'flushHeaders', 'write', 'end'] as const) {\n const original = (res as unknown as Record<string, HeaderWriter | undefined>)[method]\n if (typeof original !== 'function') continue\n ;(res as unknown as Record<string, HeaderWriter>)[method] = function (\n this: unknown,\n ...args: unknown[]\n ) {\n write()\n return original.apply(this, args)\n }\n }\n\n // h3 called through fetch hands middleware a stand-in response whose\n // headers join the route's response after `finish` — the last chance there.\n // On a Node response `finish` comes after the headers, so this is a no-op.\n ;(res as unknown as { on?: (event: string, fn: () => void) => unknown }).on?.('finish', () =>\n write(),\n )\n\n const sessionObj: Session = {\n get id() {\n return id\n },\n data: existing ? { ...existing.d } : {},\n async regenerate() {\n id = randomUUID()\n sessionObj.data = {}\n written = undefined\n write(true)\n },\n async destroy() {\n destroyed = true\n sessionObj.data = {}\n write()\n },\n async save() {\n write()\n },\n }\n ;(req as any).session = sessionObj\n next()\n }\n}\n"],"mappings":";;;;;;;;;;yYAoGA,IAAa,YAAb,KAAiD,CAC/C,yBAA4B,IAAI,IAEhC,sBAA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,EACnB,MAAM,CACR,EACA,MAAM,MAAO,CACX,MAAM,CACR,CACF,EACC,IAAa,QAAU,WACxB,KAAK,CACP,CACF"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { _ as
|
|
2
|
+
import { _ as SpaAdapter, v as SpaAdapterOptions, y as resolveClientDir } from "../../application-BD9LQ2s4.mjs";
|
|
3
3
|
export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.6.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{Logger}from"../../core/logger.mjs";import"../../core-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import"../../core-Ddq8b9hi.mjs";import{t as defineAdapter}from"../../define-adapter-Ce1FDvEo.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=/* @__PURE__ */ new Set;function snapshotClientDir(){let paths=/* @__PURE__ */ 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/* @__PURE__ */ 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`);existsSync(indexPath)?(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}`)):log.warn(`index.html not found in ${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,3 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { A as RawUploadPart, F as buildFileTypeFilter, I as resolveMimeTypes, M as UploadedFile, N as UploadedFileLike, P as applyUploadConfig, j as UploadStorageEngine } from "../../adapter-9sPr_5xt.mjs";
|
|
3
|
+
import { i as upload, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "../../upload-Jgs9BFC4.mjs";
|
|
4
|
+
export { type RawUploadPart, UploadOptions, type UploadStorageEngine, type UploadedFile, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.6.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{HttpException,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-
|
|
11
|
+
import{HttpException,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-DEnNEwL4.mjs";import{unlink}from"node:fs/promises";let _multer;function loadMulter(){return _multer??=import(`multer`).then(mod=>mod.default??mod,()=>{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed. Add it to your dependencies.`)})}function translateMulterErrors(mw,options){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}next(err)})}}function createMulter(options){let limits={fileSize:options.maxSize??5242880},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}},built,lazy=pick=>{let handler;return(req,res,next)=>{handler??=(built??=loadMulter().then(multer=>multer(multerOptions))).then(pick),handler.then(run=>run(req,res,next),err=>{handler=built=_multer=void 0,next(err)})}};return{single:field=>lazy(m=>m.single(field)),array:(field,maxCount)=>lazy(m=>m.array(field,maxCount)),none:()=>lazy(m=>m.none())}}function bothConventions(handler){return((first,second,third)=>third===void 0&&typeof second==`function`&&typeof first==`object`&&first&&`req`in first&&`res`in first?new Promise((resolve,reject)=>{handler(first.req,first.res,err=>{if(err)return reject(err);resolve(),second()})}):handler(first,second,third))}function single(fieldName,options={}){return bothConventions(translateMulterErrors(createMulter(options).single(fieldName),options))}function array(fieldName,maxCount=10,options={}){return bothConventions(translateMulterErrors(createMulter(options).array(fieldName,maxCount),options))}function none(options={}){return bothConventions(translateMulterErrors(createMulter(options).none(),options))}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};
|
|
12
12
|
//# sourceMappingURL=upload.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload.mjs","names":[],"sources":["../../../src/http/middleware/upload.ts"],"sourcesContent":["import { HttpException, HttpStatus } from '../../core/errors'\nimport { unlink } from 'node:fs/promises'\nimport type { Request, Response, NextFunction, RequestHandler } from 'express'\nimport type { Options as MulterOptions } from 'multer'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core'\n\n// `multer` is an optional peer dependency, imported when the first upload\n// arrives — adopters who never take uploads don't need it installed. An\n// `import()`, not `createRequire`: a bundler follows it, so a Netlify or\n// Vercel function built by `kick build:*` carries multer with it.\ntype MulterFactory = typeof import('multer')\ntype Multer = ReturnType<MulterFactory>\nlet _multer: Promise<MulterFactory> | undefined\n\nfunction loadMulter(): Promise<MulterFactory> {\n return (_multer ??= import('multer').then(\n // multer is CJS `export = multer`: the factory is the module's default.\n (mod) => ((mod as { default?: unknown }).default ?? mod) as MulterFactory,\n () => {\n throw new Error(\n \"@forinda/kickjs: file uploads require the 'multer' package, which is not installed. \" +\n 'Add it to your dependencies.',\n )\n },\n ))\n}\n\n// Pure upload core (MIME map, type filter, applyUploadConfig) moved to\n// `./upload-config` so the edge-safe web entry can use it without this\n// module's node-only surface. Re-exported here for compatibility.\nexport {\n buildFileTypeFilter,\n resolveMimeTypes,\n applyUploadConfig,\n type UploadedFileLike,\n type RawUploadPart,\n} from './upload-config'\nimport { buildFileTypeFilter } from './upload-config'\n\n/**\n * Upload options for the middleware.\n * Extends BaseUploadOptions from core (shared with @FileUpload decorator)\n * and adds Multer-specific storage options.\n */\nexport interface UploadOptions extends BaseUploadOptions {\n /** Multer storage config (default: memory storage) */\n storage?: MulterOptions['storage']\n /** Multer dest for disk storage shorthand */\n dest?: string\n}\n\n/**\n * Turn multer's own errors into the exceptions the other runtimes raise.\n *\n * multer reports a file over the limit as `MulterError: File too large`, a\n * plain error the handler maps to 500 — so an oversized upload was reported as\n * a server fault on Express while Fastify and h3 answered 413. The message is\n * matched to `applyUploadConfig` so the response does not depend on the engine.\n */\nfunction translateMulterErrors(mw: RequestHandler, options: UploadOptions): RequestHandler {\n const maxSize = options.maxSize ?? 5 * 1024 * 1024\n return (req, res, next) => {\n mw(req, res, (err?: unknown) => {\n if (err && (err as { code?: string }).code === 'LIMIT_FILE_SIZE') {\n const name = (err as { field?: string }).field ?? 'file'\n return next(\n new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${name} exceeds the ${maxSize}-byte limit`,\n ),\n )\n }\n next(err as never)\n })\n }\n}\n\nfunction createMulter(options: UploadOptions) {\n const limits: MulterOptions['limits'] = {\n fileSize: options.maxSize ?? 5 * 1024 * 1024,\n }\n\n let fileFilter: MulterOptions['fileFilter'] | undefined\n if (options.allowedTypes) {\n const typeAllowed = buildFileTypeFilter(options.allowedTypes, options.customMimeMap)\n fileFilter = (_req, file, cb) => {\n if (typeAllowed(file.mimetype, file.originalname)) {\n cb(null, true)\n } else {\n // Same exception the Fastify and h3 path raises from\n // `applyUploadConfig`. A plain Error here reached the handler as a 500,\n // so Express blamed itself for the client's file — and leaked a multer\n // stack doing it.\n cb(\n new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${file.mimetype} is not allowed`,\n ),\n )\n }\n }\n }\n\n const multerOptions: MulterOptions = {\n limits,\n ...(fileFilter ? { fileFilter } : {}),\n ...(options.storage ? { storage: options.storage } : {}),\n ...(options.dest ? { dest: options.dest } : {}),\n }\n\n // Built on the first request that needs it, then reused.\n let built: Promise<Multer> | undefined\n const lazy = (pick: (multer: Multer) => RequestHandler): RequestHandler => {\n let handler: Promise<RequestHandler> | undefined\n return (req, res, next) => {\n handler ??= (built ??= loadMulter().then((multer) => multer(multerOptions))).then(pick)\n handler.then(\n (run) => run(req, res, next),\n (err) => {\n // Not cached: multer installed while `kick dev` runs works on the next upload.\n handler = built = _multer = undefined\n next(err)\n },\n )\n }\n }\n return {\n single: (field: string) => lazy((m) => m.single(field) as RequestHandler),\n array: (field: string, maxCount: number) =>\n lazy((m) => m.array(field, maxCount) as RequestHandler),\n none: () => lazy((m) => m.none() as RequestHandler),\n }\n}\n\n/**\n * Single file upload middleware. Attaches the file to `req.file`.\n *\n * @example\n * ```ts\n * @Post('/avatar')\n * @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))\n * async uploadAvatar(ctx: RequestContext) {\n * ctx.json({ filename: ctx.file.originalname })\n * }\n * ```\n */\n/**\n * The handler, callable both ways it gets used: as Express middleware\n * `(req, res, next)` — `middlewares: [upload.single(...)]`, and what\n * `@FileUpload` builds — and as a route middleware `(ctx, next)`, which is\n * how `@Middleware(upload.single(...))` calls it. Called the second way,\n * Multer got the context as its request and failed on every upload.\n */\nfunction bothConventions(handler: RequestHandler): RequestHandler {\n return ((first: any, second: any, third?: any) => {\n const isRouteMiddleware =\n third === undefined &&\n typeof second === 'function' &&\n first !== null &&\n typeof first === 'object' &&\n 'req' in first &&\n 'res' in first\n if (!isRouteMiddleware) return handler(first, second, third)\n return new Promise<void>((resolve, reject) => {\n handler(first.req, first.res, (err?: unknown) => {\n if (err) return reject(err)\n resolve()\n second()\n })\n })\n }) as RequestHandler\n}\n\nfunction single(fieldName: string, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.single(fieldName), options))\n}\n\n/**\n * Multiple file upload middleware. Attaches files to `req.files`.\n */\nfunction array(fieldName: string, maxCount = 10, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.array(fieldName, maxCount), options))\n}\n\n/**\n * No file upload — just parse multipart form data without file fields.\n */\nfunction none(options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.none(), options))\n}\n\n/**\n * Removes temporary files from disk after the response is sent.\n * Attach this as Express middleware after the upload middleware.\n * Works with both `req.file` (single) and `req.files` (array).\n *\n * @example\n * ```ts\n * @Post('/process')\n * @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())\n * async processDocument(ctx: RequestContext) {\n * ctx.json({ ok: true })\n * }\n * ```\n */\nexport function cleanupFiles() {\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', async () => {\n const files: any[] = []\n\n if ((req as any).file?.path) {\n files.push((req as any).file)\n }\n if (Array.isArray((req as any).files)) {\n for (const f of (req as any).files) {\n if (f?.path) files.push(f)\n }\n }\n\n for (const file of files) {\n try {\n await unlink(file.path)\n } catch {\n // File may already be moved/deleted by the handler — ignore\n }\n }\n })\n\n next()\n }\n}\n\n/**\n * Build upload middleware from a @FileUpload decorator config.\n * Used internally by the router builder when it detects FILE_UPLOAD metadata.\n * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.\n */\nexport function buildUploadMiddleware(config: FileUploadConfig): RequestHandler {\n const options: UploadOptions = {}\n if (config.maxSize) options.maxSize = config.maxSize\n if (config.allowedTypes) options.allowedTypes = config.allowedTypes\n if (config.customMimeMap) options.customMimeMap = config.customMimeMap\n\n const fieldName = config.fieldName ?? 'file'\n\n switch (config.mode) {\n case 'single':\n return single(fieldName, options)\n case 'array':\n return array(fieldName, config.maxCount ?? 10, options)\n case 'none':\n return none(options)\n }\n}\n\n/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */\nexport const upload = { single, array, none }\n"],"mappings":";;;;;;;;;;qNAYA,IAAI,QAEJ,SAAS,YAAqC,CAC5C,MAAQ,WAAY,OAAO,SAAS,CAAC,KAElC,KAAU,IAA8B,SAAW,QAC9C,CACJ,MAAU,MACR,kHAEF,CACF,CACF,CACF,CAkCA,SAAS,sBAAsB,GAAoB,QAAwC,CACzF,IAAM,QAAU,QAAQ,SAAW,QACnC,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAG,IAAK,IAAM,KAAkB,CAC9B,GAAI,KAAQ,IAA0B,OAAS,kBAAmB,CAChE,IAAM,KAAQ,IAA2B,OAAS,OAClD,OAAO,KACL,IAAI,cACF,WAAW,kBACX,QAAQ,KAAK,eAAe,QAAQ,YACtC,CACF,CACF,CACA,KAAK,GAAY,CACnB,CAAC,CACH,CACF,CAEA,SAAS,aAAa,QAAwB,CAC5C,IAAM,OAAkC,CACtC,SAAU,QAAQ,SAAW,OAC/B,EAEI,WACJ,GAAI,QAAQ,aAAc,CACxB,IAAM,YAAc,oBAAoB,QAAQ,aAAc,QAAQ,aAAa,EACnF,YAAc,KAAM,KAAM,KAAO,CAC3B,YAAY,KAAK,SAAU,KAAK,YAAY,EAC9C,GAAG,KAAM,EAAI,EAMb,GACE,IAAI,cACF,WAAW,uB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,GAAI,QAAyB,CAAC,EAAmB,CAE5F,OAAO,gBAAgB,sBADb,aAAa,OACsB,CAAC,CAAC,MAAM,UAAW,QAAQ,EAAG,OAAO,CAAC,CACrF,CAKA,SAAS,KAAK,QAAyB,CAAC,EAAmB,CAEzD,OAAO,gBAAgB,sBADb,aAAa,OACsB,CAAC,CAAC,KAAK,EAAG,OAAO,CAAC,CACjE,CAgBA,SAAgB,cAAe,CAC7B,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAI,GAAG,SAAU,SAAY,CAC3B,IAAM,MAAe,CAAC,EAKtB,GAHK,IAAY,MAAM,MACrB,MAAM,KAAM,IAAY,IAAI,EAE1B,MAAM,QAAS,IAAY,KAAK,EAC7B,IAAA,IAAM,KAAM,IAAY,MACvB,GAAG,MAAM,MAAM,KAAK,CAAC,EAI7B,IAAK,IAAM,QAAQ,MACjB,GAAI,CACF,MAAM,OAAO,KAAK,IAAI,CACxB,MAAQ,CAER,CAEJ,CAAC,EAED,KAAK,CACP,CACF,CAOA,SAAgB,sBAAsB,OAA0C,CAC9E,IAAM,QAAyB,CAAC,EAC5B,OAAO,UAAS,QAAQ,QAAU,OAAO,SACzC,OAAO,eAAc,QAAQ,aAAe,OAAO,cACnD,OAAO,gBAAe,QAAQ,cAAgB,OAAO,eAEzD,IAAM,UAAY,OAAO,WAAa,OAEtC,OAAQ,OAAO,KAAf,CACE,IAAK,SACH,OAAO,OAAO,UAAW,OAAO,EAClC,IAAK,QACH,OAAO,MAAM,UAAW,OAAO,UAAY,GAAI,OAAO,EACxD,IAAK,OACH,OAAO,KAAK,OAAO,CACvB,CACF,CAGA,MAAa,OAAS,CAAE,OAAQ,MAAO,IAAK"}
|
|
1
|
+
{"version":3,"file":"upload.mjs","names":[],"sources":["../../../src/http/middleware/upload.ts"],"sourcesContent":["import { HttpException, HttpStatus } from '../../core/errors'\nimport { unlink } from 'node:fs/promises'\nimport type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n ConnectHandler as RequestHandler,\n} from '../connect'\nimport type { Options as MulterOptions } from 'multer'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core'\n\n// `multer` is an optional peer dependency, imported when the first upload\n// arrives — adopters who never take uploads don't need it installed. An\n// `import()`, not `createRequire`: a bundler follows it, so a Netlify or\n// Vercel function built by `kick build:*` carries multer with it.\ntype MulterFactory = typeof import('multer')\ntype Multer = ReturnType<MulterFactory>\nlet _multer: Promise<MulterFactory> | undefined\n\nfunction loadMulter(): Promise<MulterFactory> {\n return (_multer ??= import('multer').then(\n // multer is CJS `export = multer`: the factory is the module's default.\n (mod) => ((mod as { default?: unknown }).default ?? mod) as MulterFactory,\n () => {\n throw new Error(\n \"@forinda/kickjs: file uploads require the 'multer' package, which is not installed. \" +\n 'Add it to your dependencies.',\n )\n },\n ))\n}\n\n// Pure upload core (MIME map, type filter, applyUploadConfig) moved to\n// `./upload-config` so the edge-safe web entry can use it without this\n// module's node-only surface. Re-exported here for compatibility.\nexport {\n buildFileTypeFilter,\n resolveMimeTypes,\n applyUploadConfig,\n type UploadedFileLike,\n type UploadedFile,\n type UploadStorageEngine,\n type RawUploadPart,\n} from './upload-config'\nimport { buildFileTypeFilter, type UploadStorageEngine } from './upload-config'\n\n/**\n * Upload options for the middleware.\n * Extends BaseUploadOptions from core (shared with @FileUpload decorator)\n * and adds Multer-specific storage options.\n */\nexport interface UploadOptions extends BaseUploadOptions {\n /** Multer storage engine (default: memory storage) */\n storage?: UploadStorageEngine\n /** Multer dest for disk storage shorthand */\n dest?: string\n}\n\n/**\n * Turn multer's own errors into the exceptions the other runtimes raise.\n *\n * multer reports a file over the limit as `MulterError: File too large`, a\n * plain error the handler maps to 500 — so an oversized upload was reported as\n * a server fault on Express while Fastify and h3 answered 413. The message is\n * matched to `applyUploadConfig` so the response does not depend on the engine.\n */\nfunction translateMulterErrors(mw: RequestHandler, options: UploadOptions): RequestHandler {\n const maxSize = options.maxSize ?? 5 * 1024 * 1024\n return (req, res, next) => {\n mw(req, res, (err?: unknown) => {\n if (err && (err as { code?: string }).code === 'LIMIT_FILE_SIZE') {\n const name = (err as { field?: string }).field ?? 'file'\n return next(\n new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${name} exceeds the ${maxSize}-byte limit`,\n ),\n )\n }\n next(err as never)\n })\n }\n}\n\nfunction createMulter(options: UploadOptions) {\n const limits: MulterOptions['limits'] = {\n fileSize: options.maxSize ?? 5 * 1024 * 1024,\n }\n\n let fileFilter: MulterOptions['fileFilter'] | undefined\n if (options.allowedTypes) {\n const typeAllowed = buildFileTypeFilter(options.allowedTypes, options.customMimeMap)\n fileFilter = (_req, file, cb) => {\n if (typeAllowed(file.mimetype, file.originalname)) {\n cb(null, true)\n } else {\n // Same exception the Fastify and h3 path raises from\n // `applyUploadConfig`. A plain Error here reached the handler as a 500,\n // so Express blamed itself for the client's file — and leaked a multer\n // stack doing it.\n cb(\n new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${file.mimetype} is not allowed`,\n ),\n )\n }\n }\n }\n\n const multerOptions: MulterOptions = {\n limits,\n ...(fileFilter ? { fileFilter } : {}),\n ...(options.storage ? { storage: options.storage } : {}),\n ...(options.dest ? { dest: options.dest } : {}),\n }\n\n // Built on the first request that needs it, then reused.\n let built: Promise<Multer> | undefined\n const lazy = (pick: (multer: Multer) => RequestHandler): RequestHandler => {\n let handler: Promise<RequestHandler> | undefined\n return (req, res, next) => {\n handler ??= (built ??= loadMulter().then((multer) => multer(multerOptions))).then(pick)\n handler.then(\n (run) => run(req, res, next),\n (err) => {\n // Not cached: multer installed while `kick dev` runs works on the next upload.\n handler = built = _multer = undefined\n next(err)\n },\n )\n }\n }\n return {\n single: (field: string) => lazy((m) => m.single(field) as RequestHandler),\n array: (field: string, maxCount: number) =>\n lazy((m) => m.array(field, maxCount) as RequestHandler),\n none: () => lazy((m) => m.none() as RequestHandler),\n }\n}\n\n/**\n * Single file upload middleware. Attaches the file to `req.file`.\n *\n * @example\n * ```ts\n * @Post('/avatar')\n * @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))\n * async uploadAvatar(ctx: RequestContext) {\n * ctx.json({ filename: ctx.file.originalname })\n * }\n * ```\n */\n/**\n * The handler, callable both ways it gets used: as Express middleware\n * `(req, res, next)` — `middlewares: [upload.single(...)]`, and what\n * `@FileUpload` builds — and as a route middleware `(ctx, next)`, which is\n * how `@Middleware(upload.single(...))` calls it. Called the second way,\n * Multer got the context as its request and failed on every upload.\n */\nfunction bothConventions(handler: RequestHandler): RequestHandler {\n return ((first: any, second: any, third?: any) => {\n const isRouteMiddleware =\n third === undefined &&\n typeof second === 'function' &&\n first !== null &&\n typeof first === 'object' &&\n 'req' in first &&\n 'res' in first\n if (!isRouteMiddleware) return handler(first, second, third)\n return new Promise<void>((resolve, reject) => {\n handler(first.req, first.res, (err?: unknown) => {\n if (err) return reject(err)\n resolve()\n second()\n })\n })\n }) as RequestHandler\n}\n\nfunction single(fieldName: string, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.single(fieldName), options))\n}\n\n/**\n * Multiple file upload middleware. Attaches files to `req.files`.\n */\nfunction array(fieldName: string, maxCount = 10, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.array(fieldName, maxCount), options))\n}\n\n/**\n * No file upload — just parse multipart form data without file fields.\n */\nfunction none(options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.none(), options))\n}\n\n/**\n * Removes temporary files from disk after the response is sent.\n * Attach this as Express middleware after the upload middleware.\n * Works with both `req.file` (single) and `req.files` (array).\n *\n * @example\n * ```ts\n * @Post('/process')\n * @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())\n * async processDocument(ctx: RequestContext) {\n * ctx.json({ ok: true })\n * }\n * ```\n */\nexport function cleanupFiles() {\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', async () => {\n const files: any[] = []\n\n if ((req as any).file?.path) {\n files.push((req as any).file)\n }\n if (Array.isArray((req as any).files)) {\n for (const f of (req as any).files) {\n if (f?.path) files.push(f)\n }\n }\n\n for (const file of files) {\n try {\n await unlink(file.path)\n } catch {\n // File may already be moved/deleted by the handler — ignore\n }\n }\n })\n\n next()\n }\n}\n\n/**\n * Build upload middleware from a @FileUpload decorator config.\n * Used internally by the router builder when it detects FILE_UPLOAD metadata.\n * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.\n */\nexport function buildUploadMiddleware(config: FileUploadConfig): RequestHandler {\n const options: UploadOptions = {}\n if (config.maxSize) options.maxSize = config.maxSize\n if (config.allowedTypes) options.allowedTypes = config.allowedTypes\n if (config.customMimeMap) options.customMimeMap = config.customMimeMap\n\n const fieldName = config.fieldName ?? 'file'\n\n switch (config.mode) {\n case 'single':\n return single(fieldName, options)\n case 'array':\n return array(fieldName, config.maxCount ?? 10, options)\n case 'none':\n return none(options)\n }\n}\n\n/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */\nexport const upload = { single, array, none }\n"],"mappings":";;;;;;;;;;qNAiBA,IAAI,QAEJ,SAAS,YAAqC,CAC5C,MAAQ,WAAY,OAAO,SAAS,CAAC,KAElC,KAAU,IAA8B,SAAW,QAC9C,CACJ,MAAU,MACR,kHAEF,CACF,CACF,CACF,CAoCA,SAAS,sBAAsB,GAAoB,QAAwC,CACzF,IAAM,QAAU,QAAQ,SAAW,QACnC,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAG,IAAK,IAAM,KAAkB,CAC9B,GAAI,KAAQ,IAA0B,OAAS,kBAAmB,CAChE,IAAM,KAAQ,IAA2B,OAAS,OAClD,OAAO,KACL,IAAI,cACF,WAAW,kBACX,QAAQ,KAAK,eAAe,QAAQ,YACtC,CACF,CACF,CACA,KAAK,GAAY,CACnB,CAAC,CACH,CACF,CAEA,SAAS,aAAa,QAAwB,CAC5C,IAAM,OAAkC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vB,CACF,CAGA,MAAa,OAAS,CAAE,OAAQ,MAAO,IAAK"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as validate, i as defaultValidationError, n as ValidationFailure, r as ValidationSchema, t as ValidationErrorFactory } from "../../validate-
|
|
2
|
+
import { a as validate, i as defaultValidationError, n as ValidationFailure, r as ValidationSchema, t as ValidationErrorFactory } from "../../validate-D4Poe2EE.mjs";
|
|
3
3
|
export { ValidationErrorFactory, ValidationFailure, ValidationSchema, defaultValidationError, validate };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate.mjs","names":[],"sources":["../../../src/http/middleware/validate.ts"],"sourcesContent":["import type { Request
|
|
1
|
+
{"version":3,"file":"validate.mjs","names":[],"sources":["../../../src/http/middleware/validate.ts"],"sourcesContent":["import type {\n ConnectRequest as Request,\n ConnectResponse as Response,\n ConnectNext as NextFunction,\n} from '../connect'\n// core/errors directly (not the barrel) — keeps the edge-safe web entry\n// graph free of the barrel's eager node:fs asset-manager import.\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport { detectSchema, type KickSchema, type SchemaIssue } from '@forinda/kickjs-schema'\n\nexport interface ValidationSchema {\n body?: any\n query?: any\n params?: any\n}\n\n/** A request that failed route validation — what a `validationError` hook receives. */\nexport interface ValidationFailure {\n /** The part of the request that failed. */\n source: 'body' | 'query' | 'params'\n /** Every issue the schema reported, adapter-neutral (Zod, Valibot, Yup, …). */\n issues: SchemaIssue[]\n /** The request, as the runtime hands it to middleware. */\n req: unknown\n}\n\n/**\n * Turns a validation failure into the error the request fails with. Return\n * (or throw) any error — an `HttpException` or `ProblemException` keeps the\n * error handler's problem-details response — or return `undefined` to use\n * {@link defaultValidationError} for this one.\n */\nexport type ValidationErrorFactory = (failure: ValidationFailure) => unknown\n\n/**\n * The built-in failure: 422 with `details` as `[{ field, message }]`. A body\n * failure leads with its first issue's message. `@forinda/kickjs-inertia`\n * reads these `details` for the page's `errors`, so a custom factory serving\n * Inertia pages should keep the shape — or call this and adjust the result.\n */\nexport function defaultValidationError({ source, issues }: ValidationFailure): HttpException {\n const details = issues.map((i) => ({\n field: i.path.join('.') || '',\n message: i.message,\n }))\n const message =\n source === 'body'\n ? (issues[0]?.message ?? 'Validation failed')\n : source === 'query'\n ? 'Invalid query parameters'\n : 'Invalid path parameters'\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n}\n\nfunction validationError(\n factory: ValidationErrorFactory | undefined,\n failure: ValidationFailure,\n): unknown {\n if (!factory) return defaultValidationError(failure)\n try {\n return factory(failure) ?? defaultValidationError(failure)\n } catch (thrown) {\n return thrown\n }\n}\n\n/**\n * Express 5 installs `req.query` as a getter-only property (so pluggable\n * `query parser` functions can run lazily). Direct assignment throws in\n * strict mode: `Cannot set property query of #<IncomingMessage> which\n * has only a getter`. `Object.defineProperty` replaces the getter with\n * a plain value slot and sidesteps the throw. Used for `query` and\n * defensively for `params` too — Express 5 currently leaves `params`\n * writable, but swapping the descriptor costs the same and future-proofs\n * against upstream changes.\n */\nfunction assignReqProperty(req: Request, key: 'query' | 'params', value: unknown): void {\n Object.defineProperty(req, key, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n })\n}\n\n/**\n * Express middleware that validates request body/query/params against schemas.\n *\n * Accepts any schema supported by `@forinda/kickjs-schema`:\n * - Zod schemas (auto-detected)\n * - Standard Schema v1 objects\n * - KickSchema instances (from adapters like fromZod, fromValibot, etc.)\n * - Plain validator functions\n *\n * Validation failures are forwarded via `next(err)` as an `HttpException`, so\n * they flow through the application's global error handler (`onError`) and\n * produce a uniform response envelope.\n */\nexport function validate(\n schema: ValidationSchema,\n options: {\n /** What a failure throws — see `bootstrap({ validationError })`. Default: a 422. */\n validationError?: ValidationErrorFactory\n } = {},\n) {\n const factory = options.validationError\n // Detected on the first request, not per request: detection walks every\n // registered adapter and allocates a wrapper. Not at construction either —\n // a custom adapter registered during boot must still be seen.\n let wrapped: { body?: KickSchema; query?: KickSchema; params?: KickSchema } | undefined\n const schemas = () =>\n (wrapped ??= {\n body: schema.body ? detectSchema(schema.body) : undefined,\n query: schema.query ? detectSchema(schema.query) : undefined,\n params: schema.params ? detectSchema(schema.params) : undefined,\n })\n\n return (req: Request, _res: Response, next: NextFunction) => {\n try {\n const { body, query, params } = schemas()\n if (body) {\n const result = body.safeParse(req.body)\n if (!result.success) {\n return next(validationError(factory, { source: 'body', issues: result.issues, req }))\n }\n req.body = result.data\n }\n\n if (query) {\n const result = query.safeParse(req.query)\n if (!result.success) {\n return next(validationError(factory, { source: 'query', issues: result.issues, req }))\n }\n assignReqProperty(req, 'query', result.data)\n }\n\n if (params) {\n const result = params.safeParse(req.params)\n if (!result.success) {\n return next(validationError(factory, { source: 'params', issues: result.issues, req }))\n }\n assignReqProperty(req, 'params', result.data)\n }\n\n next()\n } catch (err) {\n next(err)\n }\n }\n}\n"],"mappings":";;;;;;;;;;6GAwCA,SAAgB,uBAAuB,CAAE,OAAQ,QAA4C,CAC3F,IAAM,QAAU,OAAO,IAAK,IAAO,CACjC,MAAO,EAAE,KAAK,KAAK,GAAG,GAAK,GAC3B,QAAS,EAAE,OACb,EAAE,EACI,QACJ,SAAW,OACN,OAAO,EAAE,EAAE,SAAW,oBACvB,SAAW,QACT,2BACA,0BACR,OAAO,IAAI,cAAc,WAAW,qBAAsB,QAAS,OAAO,CAC5E,CAEA,SAAS,gBACP,QACA,QACS,CACT,GAAI,CAAC,QAAS,OAAO,uBAAuB,OAAO,EACnD,GAAI,CACF,OAAO,QAAQ,OAAO,GAAK,uBAAuB,OAAO,CAC3D,OAAS,OAAQ,CACf,OAAO,MACT,CACF,CAYA,SAAS,kBAAkB,IAAc,IAAyB,MAAsB,CACtF,OAAO,eAAe,IAAK,IAAK,CAC9B,MACA,SAAU,GACV,aAAc,GACd,WAAY,EACd,CAAC,CACH,CAeA,SAAgB,SACd,OACA,QAGI,CAAC,EACL,CACA,IAAM,QAAU,QAAQ,gBAIpB,QACE,YACH,UAAY,CACX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.mjs";import"../../core-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import"../../core-Ddq8b9hi.mjs";import{t as defineAdapter}from"../../define-adapter-Ce1FDvEo.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app:engineApp}){let app=engineApp,{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`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
|
|
12
12
|
//# sourceMappingURL=views.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { dirname, 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 /**\n * Directory containing template files (default: 'src/views'), relative to\n * the project. Also looked up beside the running entry file, where\n * `copyDirs: ['src/views']` puts it in a build (`dist/src/views`), so a\n * deployment holding only `dist/` still finds it.\n */\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', viewDirs(viewsDir))\n\n log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(', ')})`)\n },\n }),\n})\n\n/**\n * Where to look for `viewsDir`: the project — `KICK_APP_ROOT` when set (the\n * Netlify and Vercel functions `kick build:*` writes set it to where\n * `deploy.include` files land), else the working directory — then beside the\n * running entry file (`node dist/index.js` → `dist/<viewsDir>`, where\n * `copyDirs` copies it). Express tries them in order.\n */\nexport function viewDirs(viewsDir: string): string[] {\n const root = resolve(process.env.KICK_APP_ROOT ?? process.cwd(), viewsDir)\n const entry = process.argv[1] ? resolve(dirname(resolve(process.argv[1])), viewsDir) : root\n return [...new Set([root, entry])]\n}\n"],"mappings":";;;;;;;;;;mLAGA,MAAM,IAAM,OAAO,IAAI,YAAY,EA+DtB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,
|
|
1
|
+
{"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { dirname, 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 /**\n * Directory containing template files (default: 'src/views'), relative to\n * the project. Also looked up beside the running entry file, where\n * `copyDirs: ['src/views']` puts it in a build (`dist/src/views`), so a\n * deployment holding only `dist/` still finds it.\n */\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: engineApp }) {\n // Express-only: template engines register on Express's app settings.\n const app = engineApp as {\n engine(ext: string, fn: unknown): unknown\n set(setting: string, value: unknown): unknown\n }\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', viewDirs(viewsDir))\n\n log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(', ')})`)\n },\n }),\n})\n\n/**\n * Where to look for `viewsDir`: the project — `KICK_APP_ROOT` when set (the\n * Netlify and Vercel functions `kick build:*` writes set it to where\n * `deploy.include` files land), else the working directory — then beside the\n * running entry file (`node dist/index.js` → `dist/<viewsDir>`, where\n * `copyDirs` copies it). Express tries them in order.\n */\nexport function viewDirs(viewsDir: string): string[] {\n const root = resolve(process.env.KICK_APP_ROOT ?? process.cwd(), viewsDir)\n const entry = process.argv[1] ? resolve(dirname(resolve(process.argv[1])), viewsDir) : root\n return [...new Set([root, entry])]\n}\n"],"mappings":";;;;;;;;;;mLAGA,MAAM,IAAM,OAAO,IAAI,YAAY,EA+DtB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,IAAK,WAAa,CAE9B,IAAM,IAAM,UAIN,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,EAClF,IAAI,OAAO,IAAK,MAAM,GAGxB,IAAI,IAAI,cAAe,GAAG,EAC1B,IAAI,IAAI,QAAS,SAAS,QAAQ,CAAC,EAEnC,IAAI,MAAM,gBAAgB,IAAI,IAAI,SAAS,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,EAAE,CACpE,CACF,EACF,CAAC,EASD,SAAgB,SAAS,SAA4B,CACnD,IAAM,KAAO,QAAQ,QAAQ,IAAI,eAAiB,QAAQ,IAAI,EAAG,QAAQ,EACnE,MAAQ,QAAQ,KAAK,GAAK,QAAQ,QAAQ,QAAQ,QAAQ,KAAK,EAAE,CAAC,EAAG,QAAQ,EAAI,KACvF,MAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,KAAM,KAAK,CAAC,CAAC,CACnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-
|
|
11
|
+
export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-KMR84Kwu.mjs";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-
|
|
2
|
+
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-BfbEdxew.mjs";
|
|
3
3
|
export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.6.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-
|
|
11
|
+
export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-U-kiHlqo.mjs";
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
|
|
2
|
+
import { d as HttpRuntime, h as RouteEntry } from "../../adapter-9sPr_5xt.mjs";
|
|
3
|
+
import { n as ConnectHandler } from "../../connect-BlIamapT.mjs";
|
|
4
|
+
import { t as BuildRoutesOptions } from "../../router-builder-BfbEdxew.mjs";
|
|
5
|
+
import { Express, Request, Response } from "express";
|
|
6
|
+
//#region src/http/runtimes/express.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.
|
|
9
|
+
* Reproduces the legacy handler ordering precisely: validation → upload →
|
|
10
|
+
* `(ctx, next)` middleware → contributor runner → terminal handler, with
|
|
11
|
+
* `beforeValidation` contributors ahead of validation. Each step
|
|
12
|
+
* constructs its own `RequestContext` over the same `req`/`res` — request-scoped
|
|
13
|
+
* state lives in the AsyncLocalStorage store, not on the ctx instance, so the
|
|
14
|
+
* per-step instances share state exactly as before.
|
|
15
|
+
*/
|
|
16
|
+
export declare function materializeRouter(entries: RouteEntry[]): ConnectHandler;
|
|
17
|
+
/**
|
|
18
|
+
* Build an Express Router from a controller class decorated with @Get, @Post,
|
|
19
|
+
* etc. The public, back-compatible entry point: a thin shim over
|
|
20
|
+
* {@link buildRouteTable} + {@link materializeRouter}. Returns an
|
|
21
|
+
* `express.Router` exactly as before — modules pass it to `app.use(path, router)`.
|
|
22
|
+
*
|
|
23
|
+
* @see buildRouteTable for the engine-neutral route-table form.
|
|
24
|
+
*/
|
|
25
|
+
export declare function buildRoutes(controllerClass: any, options?: BuildRoutesOptions): ConnectHandler;
|
|
26
|
+
/**
|
|
27
|
+
* The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;
|
|
28
|
+
* apps that pass no `runtime` get this and behave exactly as before.
|
|
29
|
+
*/
|
|
30
|
+
export declare function expressRuntime(): HttpRuntime;
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/http/runtimes/express-types.d.ts
|
|
33
|
+
/**
|
|
34
|
+
* The Express runtime's native types — what `AdapterContext.app` and
|
|
35
|
+
* `getRuntimeApp()` are typed as once `kick typegen` writes the
|
|
36
|
+
* `KickRuntimeRegister` augmentation for `runtime: 'express'`. Mirrors
|
|
37
|
+
* `FastifyRuntimeTypes` / `H3RuntimeTypes`; import it from
|
|
38
|
+
* `@forinda/kickjs/express`, which needs `@types/express`.
|
|
39
|
+
*/
|
|
40
|
+
interface ExpressRuntimeTypes {
|
|
41
|
+
request: Request;
|
|
42
|
+
response: Response;
|
|
43
|
+
app: Express;
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export type { ExpressRuntimeTypes };
|
|
47
|
+
//# sourceMappingURL=express.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"express.d.mts","names":[],"sources":["../../../src/http/runtimes/express.ts","../../../src/http/runtimes/express-types.ts"],"mappings":";;;;;;;;;;;;;;;wBA6CgB,kBAAkB,SAAS,eAAe;;;;;;;;;wBAsF1C,YACd,sBACA,UAAS,qBACR;;;;;wBAQa,kBAAkB;;;;;;;;;;UCnIjB;EACf,SAAS;EACT,UAAU;EACV,KAAK"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v10.6.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
export{t as buildRoutes,n as expressRuntime,i as materializeRouter}from"../../express-BcfJgvBP.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.6.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{createLogger}from"../../core/logger.mjs";import{HttpException}from"../../core/errors.mjs";import{
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import{HttpException}from"../../core/errors.mjs";import{n as applyHandlerResult,p as unsupportedMediaTypeError,u as parseForm}from"../../reply-BQTif5Iu.mjs";import{s as requestStore}from"../../background-DSztbyc4.mjs";import{n as disposeRequestStore,t as createRequestStore}from"../../request-scope-L71-nmRe.mjs";import{i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"../../context-UaQ6cv0K.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-DEnNEwL4.mjs";import"../middleware/upload.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-Zge6_pKo.mjs";import Fastify from"fastify";const pluginOf=mod=>mod.default??mod,createFastify=Fastify,log=createLogger(`FastifyRuntime`),QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),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.headersSent?this.reply.raw.end(data):this.reply.send(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,{validationError:entry.validationError}):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`],requestId=raw.requestId||(Array.isArray(headerId)?headerId[0]:headerId),store=createRequestStore(requestId);raw.requestId=store.requestId,reply.getHeader(`x-request-id`)||reply.header(`x-request-id`,store.requestId),reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(raw,entry);let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),reply.sent))return;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&&!await applyHandlerResult(ctx,result)&&reply.callNotFound()})}}function hopTrust(hops){return(_ip,hopIndex)=>hopIndex<hops}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=createFastify({logger:!1,routerOptions:{ignoreTrailingSlash:!0},...options.bodyLimit===void 0?{}:{bodyLimit:options.bodyLimit},trustProxy:typeof options.trustProxy==`number`?hopTrust(options.trustProxy):options.trustProxy});app[QUEUE]=[];let addParser=app.addContentTypeParser?.bind(app);return addParser&&(addParser(/^application\/[\w.+-]+\+json$/,{parseAs:`string`},(_req,body,done)=>{if(body===``)return done(null,void 0);try{done(null,JSON.parse(body))}catch(err){done(HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`),void 0)}}),addParser(`application/x-www-form-urlencoded`,{parseAs:`string`},(_req,body,done)=>{done(null,parseForm(body))}),addParser(/^text\//,{parseAs:`string`},(_req,body,done)=>{done(null,body)}),addParser(`*`,{parseAs:`string`},(req,body,done)=>{if(!body)return done(null,void 0);done(unsupportedMediaTypeError(req.headers?.[`content-type`]),void 0)})),options.notFoundFallthrough===!1&&(app[NO_FALLTHROUGH]=!0),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=pluginOf(await import(`@fastify/multipart`));await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=pluginOf(await import(`@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],ready=!1;return readyP.then(()=>ready=!0,()=>{}),(req,res,next)=>{next&&(req[NEXT]=next),ready?app.routing(req,res):readyP.then(()=>app.routing(req,res)).catch(err=>{if(next)return next(err);log.error(err,`Fastify failed to start`),res.statusCode=500,res.end(`Internal Server Error`)})}},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){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];next&&!app[NO_FALLTHROUGH]?(reply.hijack(),next()):settleOrFail(reply,mw(request.raw,replyDriver(reply),NOOP_NEXT))})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{settleOrFail(reply,mw(err,request.raw,replyDriver(reply),NOOP_NEXT))})},close(app){return app.close()},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!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
|