@forinda/kickjs 9.1.0 → 9.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-DhjoIYVI.d.mts → adapter-DjfRMob8.d.mts} +3 -13
- package/dist/{adapter-DhjoIYVI.d.mts.map → adapter-DjfRMob8.d.mts.map} +1 -1
- package/dist/application-BSJpaiSY.mjs +12 -0
- package/dist/{application-nDj-76EX.mjs.map → application-BSJpaiSY.mjs.map} +1 -1
- package/dist/{application-DqD58rhF.d.mts → application-CGxZCYl1.d.mts} +8 -8
- package/dist/{application-DqD58rhF.d.mts.map → application-CGxZCYl1.d.mts.map} +1 -1
- package/dist/{bootstrap-BqcT1h9H.mjs → bootstrap-CbTF6xvv.mjs} +3 -3
- package/dist/{bootstrap-BqcT1h9H.mjs.map → bootstrap-CbTF6xvv.mjs.map} +1 -1
- package/dist/{client-ip-DMKc-Trg.mjs → client-ip-pcINkkPr.mjs} +2 -2
- package/dist/{client-ip-DMKc-Trg.mjs.map → client-ip-pcINkkPr.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-DrgIbebd.mjs → config-DmGiAIuH.mjs} +3 -3
- package/dist/{config-DrgIbebd.mjs.map → config-DmGiAIuH.mjs.map} +1 -1
- package/dist/{container-ZnfelY_a.mjs → container-CAPN7pBG.mjs} +3 -3
- package/dist/{container-ZnfelY_a.mjs.map → container-CAPN7pBG.mjs.map} +1 -1
- package/dist/{context-errors-Cgtrrqfs.mjs → context-errors-DYJjhalQ.mjs} +2 -2
- package/dist/{context-errors-Cgtrrqfs.mjs.map → context-errors-DYJjhalQ.mjs.map} +1 -1
- package/dist/context-gpvcMlG5.mjs +12 -0
- package/dist/context-gpvcMlG5.mjs.map +1 -0
- package/dist/{contributor-runner-BSpshfPN.mjs → contributor-runner-vk9XlOED.mjs} +3 -3
- package/dist/{contributor-runner-BSpshfPN.mjs.map → contributor-runner-vk9XlOED.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.d.mts +1 -1
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- 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-_WNyghl_.mjs → core-DKrKVLfj.mjs} +3 -3
- package/dist/{core-_WNyghl_.mjs.map → core-DKrKVLfj.mjs.map} +1 -1
- package/dist/{csrf-COFjRrUz.d.mts → csrf-C73UkRgc.d.mts} +2 -2
- package/dist/{csrf-COFjRrUz.d.mts.map → csrf-C73UkRgc.d.mts.map} +1 -1
- package/dist/{csrf-BcxqzCZW.mjs → csrf-CxJItZVa.mjs} +3 -3
- package/dist/{csrf-BcxqzCZW.mjs.map → csrf-CxJItZVa.mjs.map} +1 -1
- package/dist/{decorate-BBwu7--P.mjs → decorate-DfH1NIqV.mjs} +1 -1
- package/dist/{decorators-DOcWsXci.d.mts → decorators-BxNSz9Qt.d.mts} +4 -4
- package/dist/{decorators-DOcWsXci.d.mts.map → decorators-BxNSz9Qt.d.mts.map} +1 -1
- package/dist/{define-adapter-CajLeMzM.mjs → define-adapter-C6lFhCL-.mjs} +2 -2
- package/dist/{define-adapter-CajLeMzM.mjs.map → define-adapter-C6lFhCL-.mjs.map} +1 -1
- package/dist/{disposables-DIXt8ze-.mjs → disposables-NlW6Mibk.mjs} +2 -2
- package/dist/{disposables-DIXt8ze-.mjs.map → disposables-NlW6Mibk.mjs.map} +1 -1
- package/dist/{env-DtJ-6gyL.mjs → env-__fzPsHD.mjs} +3 -3
- package/dist/{env-DtJ-6gyL.mjs.map → env-__fzPsHD.mjs.map} +1 -1
- package/dist/{error-handler-DiueQHes.d.mts → error-handler-itG65lj0.d.mts} +2 -2
- package/dist/{error-handler-DiueQHes.d.mts.map → error-handler-itG65lj0.d.mts.map} +1 -1
- package/dist/handler-DnZbcleS.mjs +13 -0
- package/dist/handler-DnZbcleS.mjs.map +1 -0
- package/dist/http/application.d.mts +1 -1
- 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/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- 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/fastify.d.mts +3 -1
- package/dist/http/runtimes/fastify.d.mts.map +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.d.mts +1 -1
- package/dist/http/runtimes/h3-web.mjs +2 -2
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-CDn-p3tq.d.mts → index-CNHSbZTE.d.mts} +4 -4
- package/dist/{index-CDn-p3tq.d.mts.map → index-CNHSbZTE.d.mts.map} +1 -1
- package/dist/index.d.mts +9 -9
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{jobs-dx-MTUUb.mjs → jobs-BmpeFvi0.mjs} +3 -3
- package/dist/{jobs-dx-MTUUb.mjs.map → jobs-BmpeFvi0.mjs.map} +1 -1
- package/dist/{kv-stores-CetFF9N_.d.mts → kv-stores-BZTe23Tw.d.mts} +3 -3
- package/dist/{kv-stores-CetFF9N_.d.mts.map → kv-stores-BZTe23Tw.d.mts.map} +1 -1
- package/dist/{kv-stores-Ba5_rcz-.mjs → kv-stores-DJwxntyw.mjs} +3 -3
- package/dist/{kv-stores-Ba5_rcz-.mjs.map → kv-stores-DJwxntyw.mjs.map} +1 -1
- package/dist/{metadata-CW4I35nN.mjs → metadata-CzzRUnAx.mjs} +2 -2
- package/dist/{metadata-CW4I35nN.mjs.map → metadata-CzzRUnAx.mjs.map} +1 -1
- package/dist/{module-registry-kqozOSo0.mjs → module-registry-BnmRNy-3.mjs} +2 -2
- package/dist/{module-registry-kqozOSo0.mjs.map → module-registry-BnmRNy-3.mjs.map} +1 -1
- package/dist/{observers-CC3sO1BM.mjs → observers-COlQfinD.mjs} +2 -2
- package/dist/{observers-CC3sO1BM.mjs.map → observers-COlQfinD.mjs.map} +1 -1
- package/dist/{query-DPlkWOw6.mjs → query-B5DTq_4W.mjs} +2 -2
- package/dist/{query-DPlkWOw6.mjs.map → query-B5DTq_4W.mjs.map} +1 -1
- package/dist/reply-CbTYIj_e.mjs +12 -0
- package/dist/reply-CbTYIj_e.mjs.map +1 -0
- package/dist/{respond-DjxNwGnN.mjs → respond-wbMSqHYo.mjs} +2 -2
- package/dist/{respond-DjxNwGnN.mjs.map → respond-wbMSqHYo.mjs.map} +1 -1
- package/dist/{route-flag-sIYXay3q.mjs → route-flag-Bb7n9Mnp.mjs} +3 -3
- package/dist/{route-flag-sIYXay3q.mjs.map → route-flag-Bb7n9Mnp.mjs.map} +1 -1
- package/dist/{route-policy-B6_toGJW.mjs → route-policy-C_Wsc-b1.mjs} +2 -2
- package/dist/{route-policy-B6_toGJW.mjs.map → route-policy-C_Wsc-b1.mjs.map} +1 -1
- package/dist/{router-builder-BSBSYgYW.d.mts → router-builder-CDkW88KQ.d.mts} +2 -2
- package/dist/{router-builder-BSBSYgYW.d.mts.map → router-builder-CDkW88KQ.d.mts.map} +1 -1
- package/dist/{router-builder-CzVjPs5y.mjs → router-builder-DawnRzlp.mjs} +3 -3
- package/dist/{router-builder-CzVjPs5y.mjs.map → router-builder-DawnRzlp.mjs.map} +1 -1
- package/dist/{upload-DjhnyHHm.d.mts → upload-Cy7qQy7M.d.mts} +3 -3
- package/dist/{upload-DjhnyHHm.d.mts.map → upload-Cy7qQy7M.d.mts.map} +1 -1
- package/dist/{upload-config-d0pisVsK.mjs → upload-config-D01Ty40f.mjs} +2 -2
- package/dist/{upload-config-d0pisVsK.mjs.map → upload-config-D01Ty40f.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 +2 -2
- package/dist/application-nDj-76EX.mjs +0 -12
- package/dist/context-BGPof8bs.mjs +0 -12
- package/dist/context-BGPof8bs.mjs.map +0 -1
- package/dist/handler-2OebsoPr.mjs +0 -13
- package/dist/handler-2OebsoPr.mjs.map +0 -1
- package/dist/runtime-CDz5ayBt.mjs +0 -12
- package/dist/runtime-CDz5ayBt.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.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-DKrKVLfj.mjs";import{t as defineAdapter}from"../../define-adapter-C6lFhCL-.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=new Set;function snapshotClientDir(){let paths=new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);if(!existsSync(indexPath)){log.warn(`index.html not found in ${clientDir}`);return}indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
|
|
12
12
|
//# sourceMappingURL=spa.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-
|
|
2
|
+
import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-Cy7qQy7M.mjs";
|
|
3
3
|
export { type RawUploadPart, UploadOptions, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.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{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-D01Ty40f.mjs";import{createRequire}from"node:module";import{unlink}from"node:fs/promises";const requireFromHere=createRequire(import.meta.url);let _multer;function loadMulter(){if(_multer)return _multer;try{return _multer=requireFromHere(`multer`),_multer}catch{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed.
|
|
12
12
|
Install it as a peer dependency: pnpm add multer (or npm i multer / yarn add multer).`)}}function 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}:{}};return loadMulter()(multerOptions)}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};
|
|
13
13
|
//# sourceMappingURL=upload.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.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-DKrKVLfj.mjs";import{t as defineAdapter}from"../../define-adapter-C6lFhCL-.mjs";import{resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app}){let{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,resolve(viewsDir)),log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)}})});export{ViewAdapter};
|
|
12
12
|
//# sourceMappingURL=views.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"../../query-
|
|
11
|
+
import{a as parseQuery,c as resetQueryParsingDefaults,i as parsePagination,l as setQueryParsingDefaults,n as getQueryParsingDefaults,o as parseSearchQuery,r as parseFilters,s as parseSort,t as buildQueryParams,u as FILTER_OPERATORS}from"../../query-B5DTq_4W.mjs";export{FILTER_OPERATORS,buildQueryParams,getQueryParsingDefaults,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,resetQueryParsingDefaults,setQueryParsingDefaults};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-
|
|
2
|
+
import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-CDkW88KQ.mjs";
|
|
3
3
|
export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"../router-builder-
|
|
11
|
+
import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"../router-builder-DawnRzlp.mjs";export{_setExternalContributorSources,assertRouteUnique,buildRouteTable};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { p as HttpRuntime } from "../../adapter-
|
|
2
|
+
import { p as HttpRuntime } from "../../adapter-DjfRMob8.mjs";
|
|
3
3
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
4
4
|
//#region src/http/runtimes/fastify.d.ts
|
|
5
5
|
interface FastifyReplyLike {
|
|
@@ -7,6 +7,8 @@ interface FastifyReplyLike {
|
|
|
7
7
|
send(payload?: unknown): FastifyReplyLike;
|
|
8
8
|
header(name: string, value: unknown): FastifyReplyLike;
|
|
9
9
|
type(contentType: string): FastifyReplyLike;
|
|
10
|
+
serializer(fn: (payload: unknown) => string): FastifyReplyLike;
|
|
11
|
+
getHeader(name: string): unknown;
|
|
10
12
|
hijack(): void;
|
|
11
13
|
readonly sent: boolean;
|
|
12
14
|
readonly raw: ServerResponse;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fastify.d.mts","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"mappings":";;;;UAgDU;EACR,KAAK,qBAAqB;EAC1B,KAAK,oBAAoB;EACzB,OAAO,cAAc,iBAAiB;EACtC,KAAK,sBAAsB;EAC3B;WACS;WACA,KAAK;;UAEN;EACR,KAAK;EACL;EACA;EACA;;EAEA,UAAU;;EAEV,cAAc,sBAAsB;EACpC;;KAEG,kBAAkB,SAAS,oBAAoB,OAAO,4BAA4B;UAC7E;EACR,SAAS,iBAAiB,iBAAiB,gBAAgB;EAC3D,IAAI,eAAe;EACnB,MAAM;IAAQ;IAAgB;IAAa,SAAS;;EACpD,mBAAmB,SAAS;EAC5B,gBACE,UAAU,cAAc,KAAK,oBAAoB,OAAO;EAE1D,SAAS;EACT,QAAQ,KAAK,iBAAiB,KAAK;;;;;;EAMnC,sBACE,kBAAkB,mBAClB;IAAQ;KACR,QAAQ;;;KAQP,qBACH,KAAK,oBACL,eAAe,QACf,OAAO,KAAK,cAAc;UAYlB;EACR;EACA;EACA;EACA;EACA;EACA,iBAAiB,QAAQ;;;;;;;
|
|
1
|
+
{"version":3,"file":"fastify.d.mts","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"mappings":";;;;UAgDU;EACR,KAAK,qBAAqB;EAC1B,KAAK,oBAAoB;EACzB,OAAO,cAAc,iBAAiB;EACtC,KAAK,sBAAsB;EAC3B,WAAW,KAAK,8BAA8B;EAC9C,UAAU;EACV;WACS;WACA,KAAK;;UAEN;EACR,KAAK;EACL;EACA;EACA;;EAEA,UAAU;;EAEV,cAAc,sBAAsB;EACpC;;KAEG,kBAAkB,SAAS,oBAAoB,OAAO,4BAA4B;UAC7E;EACR,SAAS,iBAAiB,iBAAiB,gBAAgB;EAC3D,IAAI,eAAe;EACnB,MAAM;IAAQ;IAAgB;IAAa,SAAS;;EACpD,mBAAmB,SAAS;EAC5B,gBACE,UAAU,cAAc,KAAK,oBAAoB,OAAO;EAE1D,SAAS;EACT,QAAQ,KAAK,iBAAiB,KAAK;;;;;;EAMnC,sBACE,kBAAkB,mBAClB;IAAQ;KACR,QAAQ;;;KAQP,qBACH,KAAK,oBACL,eAAe,QACf,OAAO,KAAK,cAAc;UAYlB;EACR;EACA;EACA;EACA;EACA;EACA,iBAAiB,QAAQ;;;;;;;wBAgMX,kBAAkB,YAAY;;;;;;;;iBA8M7B;EACf,2BAA2B;EAC3B,4BAA4B;EAC5B,uBAAuB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.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{HttpException}from"../../core/errors.mjs";import{a as
|
|
11
|
+
import{HttpException}from"../../core/errors.mjs";import{a as disposeRequestStore,d as unsupportedMediaTypeError,i as createRequestStore,t as applyHandlerResult}from"../../reply-CbTYIj_e.mjs";import{d as requestStore,i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"../../context-gpvcMlG5.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-D01Ty40f.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),loadPeer=name=>{let mod=peerRequire(name);return mod&&mod.__esModule&&mod.default?mod.default:mod.default??mod},QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.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}setHeader(name,value){return this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.end(data),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
|
|
12
12
|
Install it as a peer dependency: pnpm add @fastify/multipart.`);let rawParts=[],fields={};for await(let part of request.parts())part.type===`file`&&part.toBuffer?rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer:await part.toBuffer()}):fields[part.fieldname]=part.value;let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...fields}}let headerId=raw.headers[`x-request-id`],requestId=(Array.isArray(headerId)?headerId[0]:headerId)||raw.requestId,store=createRequestStore(requestId);raw.requestId=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||applyHandlerResult(ctx,result)})}}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=loadPeer(`fastify`)({logger:!1,routerOptions:{ignoreTrailingSlash:!0},trustProxy:typeof options.trustProxy!=`function`&&options.trustProxy});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,Object.fromEntries(new URLSearchParams(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)})),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=loadPeer(`@fastify/multipart`);await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=loadPeer(`@fastify/middie`);await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY];return(req,res,next)=>{next&&(req[NEXT]=next),readyP.then(()=>app.routing(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){let serveStatic=loadPeer(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];if(next){reply.hijack(),next();return}mw(request.raw,replyDriver(reply),NOOP_NEXT)})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{mw(err,request.raw,replyDriver(reply),NOOP_NEXT)})},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport { HttpException } from '../../core/errors'\nimport { unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// ESM-safe require for the optional peers (fastify / @fastify/middie /\n// serve-static), resolved from wherever this module is installed.\nconst peerRequire = createRequire(import.meta.url)\nconst loadPeer = (name: string): any => {\n const mod = peerRequire(name)\n return mod && mod.__esModule && mod.default ? mod.default : (mod.default ?? mod)\n}\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n hijack(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: () => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n this.reply.send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n setHeader(name: string, value: unknown): this {\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n this.reply.raw.end(data as never)\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for await (const part of request.parts()) {\n if (part.type === 'file' && part.toBuffer) {\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer: await part.toBuffer(),\n })\n } else {\n fields[part.fieldname] = part.value\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...fields }\n }\n\n const headerId = raw.headers['x-request-id']\n const requestId = (Array.isArray(headerId) ? headerId[0] : headerId) || raw.requestId\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n if (!reply.sent) applyHandlerResult(ctx, result)\n })\n }\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const Fastify = loadPeer('fastify')\n const app = Fastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // trustProxy passed through for now; core X-Forwarded-For\n // normalization (spec §10 Q1) is a follow-up.\n trustProxy: typeof options.trustProxy === 'function' ? false : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, Object.fromEntries(new URLSearchParams(body as string)))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = loadPeer('@fastify/multipart')\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = loadPeer('@fastify/middie')\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) next(err)\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n const serveStatic = loadPeer('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n ;(mw as (req: unknown, res: unknown, next: () => void) => void)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n ;(mw as (e: unknown, req: unknown, res: unknown, next: () => void) => void)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n )\n })\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;seAwCA,MAAM,YAAc,cAAc,YAAY,GAAG,EAC3C,SAAY,MAAsB,CACtC,IAAM,IAAM,YAAY,IAAI,EAC5B,OAAO,KAAO,IAAI,YAAc,IAAI,QAAU,IAAI,QAAW,IAAI,SAAW,GAC9E,EAyDM,MAAQ,OAAO,6BAA6B,EAC5C,MAAQ,OAAO,sBAAsB,EACrC,KAAO,OAAO,qBAAqB,EAGnC,gBAAkB,OAAO,+BAA+B,EACxD,cAAwB,CAAC,EAiB/B,IAAM,mBAAN,KAAoD,CACrB,MAA7B,YAAY,MAA0C,CAAzB,KAAA,MAAA,KAA0B,CACvD,OAAO,KAAoB,CAEzB,OADA,KAAK,MAAM,KAAK,IAAI,EACb,IACT,CACA,KAAK,KAAqB,CAExB,OADA,KAAK,MAAM,KAAK,IAAI,EACb,IACT,CACA,KAAK,KAAqB,CAExB,OADA,KAAK,MAAM,KAAK,IAAI,EACb,IACT,CACA,KAAK,YAA2B,CAE9B,OADA,KAAK,MAAM,KAAK,WAAW,EACpB,IACT,CACA,UAAU,KAAc,MAAsB,CAE5C,OADA,KAAK,MAAM,OAAO,KAAM,KAAK,EACtB,IACT,CACA,QAAgB,CACd,MAAU,MAAM,wEAAwE,CAC1F,CACA,UAAU,WAAoB,QAA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B,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAM7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
|
|
1
|
+
{"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport { HttpException } from '../../core/errors'\nimport { unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// ESM-safe require for the optional peers (fastify / @fastify/middie /\n// serve-static), resolved from wherever this module is installed.\nconst peerRequire = createRequire(import.meta.url)\nconst loadPeer = (name: string): any => {\n const mod = peerRequire(name)\n return mod && mod.__esModule && mod.default ? mod.default : (mod.default ?? mod)\n}\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n serializer(fn: (payload: unknown) => string): FastifyReplyLike\n getHeader(name: string): unknown\n hijack(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: () => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n // A custom serializer drops Fastify's default content-type; keep one the\n // caller chose (`application/problem+json`).\n if (!this.reply.getHeader('content-type')) this.reply.type('application/json; charset=utf-8')\n this.reply.serializer(stringifyJson).send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n setHeader(name: string, value: unknown): this {\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n this.reply.raw.end(data as never)\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for await (const part of request.parts()) {\n if (part.type === 'file' && part.toBuffer) {\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer: await part.toBuffer(),\n })\n } else {\n fields[part.fieldname] = part.value\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...fields }\n }\n\n const headerId = raw.headers['x-request-id']\n const requestId = (Array.isArray(headerId) ? headerId[0] : headerId) || raw.requestId\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n if (!reply.sent) applyHandlerResult(ctx, result)\n })\n }\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const Fastify = loadPeer('fastify')\n const app = Fastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // trustProxy passed through for now; core X-Forwarded-For\n // normalization (spec §10 Q1) is a follow-up.\n trustProxy: typeof options.trustProxy === 'function' ? false : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, Object.fromEntries(new URLSearchParams(body as string)))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = loadPeer('@fastify/multipart')\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = loadPeer('@fastify/middie')\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) next(err)\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n const serveStatic = loadPeer('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n ;(mw as (req: unknown, res: unknown, next: () => void) => void)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n ;(mw as (e: unknown, req: unknown, res: unknown, next: () => void) => void)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n )\n })\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;ufAwCA,MAAM,YAAc,cAAc,YAAY,GAAG,EAC3C,SAAY,MAAsB,CACtC,IAAM,IAAM,YAAY,IAAI,EAC5B,OAAO,KAAO,IAAI,YAAc,IAAI,QAAU,IAAI,QAAW,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AK,CAAE,CAAC,CACvE,CAEJ,EAEA,WAAW,IAAK,GAAuB,KAA0B,CAI/D,IADE,MACG,EAAE,KAAK,CAAE,GAAI,IAAK,CAAC,CAC1B,EAEA,YAAY,IAAK,OAAQ,IAAK,CAI5B,IAAM,YAAc,SAAS,cAAc,EAC3C,KAAK,WAAW,IAAK,YAAY,GAAG,EAAwB,CAAE,KAAM,MAAO,CAAC,CAC9E,EAEA,YAAY,IAAK,GAAuB,CACtC,IAAI,oBAAoB,QAAS,QAAU,CACzC,IAAM,KAAQ,QAAQ,IAA+D,MACrF,GAAI,KAAM,CAER,MAAM,OAAO,EACb,KAAK,EACL,MACF,CAGC,GACC,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CAAC,CACH,EAEA,gBAAgB,IAAK,GAAuB,CAC1C,IAAI,iBAAiB,IAAK,QAAS,QAAU,CAG1C,GACC,IACA,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CAAC,CACH,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAgBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAM7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger,describeError}from"../../core/logger.mjs";import{n as WebRequestShim,r as WebResponseDriver,t as compileWebRoute}from"../../handler-
|
|
11
|
+
import{createLogger,describeError}from"../../core/logger.mjs";import{n as WebRequestShim,r as WebResponseDriver,t as compileWebRoute}from"../../handler-DnZbcleS.mjs";import{createRequire}from"node:module";const log=createLogger(`H3WebRuntime`),peerRequire=createRequire(import.meta.url),NOTFOUND_MW=Symbol(`kickjs.h3web.notFoundMw`),ERROR_MW=Symbol(`kickjs.h3web.errorMw`),ASSEMBLED=Symbol(`kickjs.h3web.assembled`),NOOP_NEXT=()=>{};function loadH3v2(injected){let m=injected??peerRequire(`h3`),resolved=m&&m.__esModule&&m.default?{...m.default,...m}:m;if(typeof resolved.H3!=`function`)throw Error("@forinda/kickjs: h3WebRuntime() requires h3 v2 (the web-standards line, npm dist-tag 'latest'), but the installed h3 has no H3 class — that is the v1 line. Either `pnpm add h3@latest` for this runtime, or keep h3 v1 and use h3Runtime() from '@forinda/kickjs/h3'.");return resolved}async function runConnectTerminal(mw,event,err){let req=new WebRequestShim(event.req,event.url),driver=new WebResponseDriver(event.req.signal);return mw&&(err===void 0?mw(req,driver,NOOP_NEXT):mw(err,req,driver,NOOP_NEXT)),driver.settled||(err===void 0?driver.status(404).json({error:`Not Found`}):(log.error(err,`h3-web: error handler did not settle the response — ${describeError(err)}`),driver.status(500).json({error:`Internal Server Error`,...typeof process<`u`&&process.env?.NODE_ENV===`production`?{}:{message:describeError(err)}}))),driver.ready}const FETCH_CONNECT=new WeakMap;function fetchConnectState(event){let state=FETCH_CONNECT.get(event);return state||(state={req:new WebRequestShim(event.req,event.url),headers:new Headers},FETCH_CONNECT.set(event,state)),state}function withConnectHeaders(event,response){let state=FETCH_CONNECT.get(event);if(!state)return response;let missing=[...state.headers].filter(([name])=>name===`set-cookie`||!response.headers.has(name));if(state.headers=new Headers,missing.length===0)return response;try{for(let[name,value]of missing)response.headers.append(name,value);return response}catch{let headers=new Headers(response.headers);for(let[name,value]of missing)headers.append(name,value);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}var FetchConnectResponse=class extends WebResponseDriver{prepared;code=200;listeners=[];constructor(prepared,signal){super(signal),this.prepared=prepared}get statusCode(){return this.code}set statusCode(code){this.status(code)}status(code){return this.code=code,super.status(code)}writeHead(code,headers){return this.code=code,super.writeHead(code,headers)}setHeader(name,value){if(Array.isArray(value)){this.prepared.delete(name);for(let v of value)this.prepared.append(name,String(v))}else this.prepared.set(name,String(value));return this}getHeader(name){return this.prepared.get(name)??void 0}hasHeader(name){return this.prepared.has(name)}removeHeader(name){this.prepared.delete(name)}once(event,listener){return this.listeners.push([event,listener]),this}on(event,listener){return this.once(event,listener)}removeListener(event,listener){return this.listeners=this.listeners.filter(([e,l])=>e!==event||l!==listener),this}off(event,listener){return this.removeListener(event,listener)}done(){for(let event of[`finish`,`close`]){for(let[e,listener]of this.listeners)e===event&&listener();this.listeners=this.listeners.filter(([e])=>e!==event)}}};function runConnectOnFetch(mw,event,next){let state=fetchConnectState(event),res=new FetchConnectResponse(state.headers,event.req.signal);return new Promise((resolve,reject)=>{let respond=response=>{res.done(),resolve(withConnectHeaders(event,response))},fail=err=>{res.done(),reject(err)};res.ready.then(respond);let connectNext=err=>{if(err)return fail(err);if(res.settled)return;let id=state.req.requestId;if(id&&event.req.headers.get(`x-request-id`)!==id)try{event.req.headers.set(`x-request-id`,id)}catch{}let downstream;try{downstream=next()}catch(e){return fail(e)}Promise.resolve(downstream).then(value=>{if(value instanceof Response)return respond(value);res.done(),resolve(value)},fail)};try{mw(state.req,res,connectNext)}catch(err){fail(err)}})}function assembleCatchAll(app){let state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,app.all(`/**`,event=>{let mw=state[NOTFOUND_MW];return runConnectTerminal(mw,event)}))}function h3WebRuntime(options={}){let{H3,toNodeHandler,fromNodeHandler}=loadH3v2(options.h3);return{name:`h3-web`,createApp(_options={}){let holder={},app=new H3({onError:(error,event)=>{let mw=holder.app?.[ERROR_MW];return runConnectTerminal(mw,event,error).then(response=>withConnectHeaders(event,response))}});return holder.app=app,app},nodeHandler(app){assembleCatchAll(app);let listener=toNodeHandler(app);return(req,res,next)=>{try{let result=listener(req,res);result&&typeof result.then==`function`&&result.catch(err=>next?.(err))}catch(err){next?.(err)}}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path),run=compileWebRoute(entry,{onError:async(err,req,driver)=>{let mw=app[ERROR_MW];mw&&mw(err,req,driver,NOOP_NEXT)}});app.on(entry.method,url,event=>run({request:event.req,url:event.url,params:event.context.params??{}}))}},useConnect(app,mw,opts){let viaNode=fromNodeHandler(mw),handler=(event,next)=>event.req.runtime?.node?.res?viaNode(event):runConnectOnFetch(mw,event,next);opts?.path===void 0?app.use(handler):app.use(joinPath(String(opts.path),`/**`),handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw,assembleCatchAll(app)},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{h3WebRuntime};
|
|
12
12
|
//# sourceMappingURL=h3-web.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.
|
|
2
|
+
* @forinda/kickjs v9.2.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}from"../../core/errors.mjs";import{a as
|
|
11
|
+
import{HttpException}from"../../core/errors.mjs";import{a as disposeRequestStore,d as unsupportedMediaTypeError,i as createRequestStore,l as classifyMediaType,t as applyHandlerResult}from"../../reply-CbTYIj_e.mjs";import{d as requestStore,i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"../../context-gpvcMlG5.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-D01Ty40f.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),h3=()=>peerRequire(`h3`),NEXT=Symbol(`kickjs.h3.next`),ERROR_MW=Symbol(`kickjs.h3.errorMw`),ROUTER=Symbol(`kickjs.h3.router`),NOTFOUND_MW=Symbol(`kickjs.h3.notFoundMw`),ASSEMBLED=Symbol(`kickjs.h3.assembled`),NOOP_NEXT=()=>{},BODY_METHODS=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]);var NodeResDriver=class{res;constructor(res){this.res=res}status(code){return this.res.statusCode=code,this}json(data){return!this.res.headersSent&&!this.res.getHeader(`content-type`)&&this.res.setHeader(`content-type`,`application/json; charset=utf-8`),this.res.end(stringifyJson(data)),this}send(data){return this.res.end(data),this}type(contentType){return this.res.setHeader(`content-type`,contentType),this}setHeader(name,value){return this.res.setHeader(name,value),this}render(){throw Error(`ctx.render() is not supported on the h3 runtime (no view engine).`)}writeHead(statusCode,headers){return this.res.writeHead(statusCode,headers),this}flushHeaders(){return this.res.flushHeaders(),this}write(chunk){return this.res.write(chunk)}end(data){return this.res.end(data),this}once(event,listener){return this.res.once(event,listener),this}get headersSent(){return this.res.headersSent}};function resDriver(res){return new NodeResDriver(res)}const TRUST_PROXY=Symbol(`kickjs.h3.trustProxy`);function makeEventHandler(entry,trustProxy){let{getRouterParams,getQuery,readRawBody,readMultipartFormData}=h3(),upload=entry.meta.upload,validator=entry.meta.validation?validate(entry.meta.validation):void 0;return async event=>{let req=event.node.req,res=event.node.res;if(trustProxy&&!req.ip){let forwarded=req.headers[`x-forwarded-for`],first=(Array.isArray(forwarded)?forwarded[0]:forwarded)?.split(`,`)[0]?.trim();first&&(req.ip=first)}if(req.params=getRouterParams(event)??{},req.query=getQuery(event)??{},req.httpVersionMajor===2&&req.headers[`content-length`]===void 0&&BODY_METHODS.has(req.method??`GET`)&&(req.rawBody=await readStreamBuffer(req)),upload&&upload.mode!==`none`){let form=await readMultipartFormData(event).catch(()=>void 0),rawParts=[],fields={};for(let part of form??[])part.filename?rawParts.push({fieldname:part.name??``,filename:part.filename,mimetype:part.type??`application/octet-stream`,buffer:part.data}):part.name&&(fields[part.name]=part.data.toString(`utf-8`));let{file,files}=applyUploadConfig(rawParts,upload);req.file=file,req.files=files,req.body=fields}else if(BODY_METHODS.has(req.method??`GET`)){let{"content-length":length,"transfer-encoding":encoding}=req.headers;if(encoding!==void 0||length!==void 0&&length!==`0`||req.httpVersionMajor===2&&length!==`0`){let kind=classifyMediaType(req.headers[`content-type`]);if(kind!==`multipart`){let raw=await readRawBody(event,`utf8`);if(raw){if(kind===`unsupported`)throw unsupportedMediaTypeError(req.headers[`content-type`]);if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){throw HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`)}else req.body=kind===`urlencoded`?Object.fromEntries(new URLSearchParams(raw)):raw}}}}let headerId=req.headers[`x-request-id`],requestId=(Array.isArray(headerId)?headerId[0]:headerId)||req.requestId,store=createRequestStore(requestId);req.requestId=store.requestId,res.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(req,entry);let ctx=new RequestContext(req,res,NOOP_NEXT,resDriver(res));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),res.writableEnded))return;validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||res.writableEnded)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),res.writableEnded)return;let result=await entry.handler(ctx);!res.writableEnded&&!res.headersSent&&applyHandlerResult(ctx,result)})}}function unwrapH3Error(error){if(!(error instanceof Error))return error;let{cause}=error;return cause instanceof Error?cause:error}async function readStreamBuffer(req){let chunks=[];for await(let chunk of req)chunks.push(typeof chunk==`string`?Buffer.from(chunk):chunk);return Buffer.concat(chunks)}function h3Runtime(){return{name:`h3`,createApp(options={}){let{createApp}=h3(),app=createApp({onError:(error,event)=>{let res=event.node.res;if(res.writableEnded)return;let state=app,status=error?.statusCode,thrownByHandler=error?.cause instanceof Error;if(status===404&&!thrownByHandler){let next=event.node.req[NEXT];if(next){next();return}let nf=state[NOTFOUND_MW];if(nf){nf(event.node.req,resDriver(res),NOOP_NEXT);return}}let mw=state[ERROR_MW];mw&&mw(unwrapH3Error(error),event.node.req,resDriver(res),NOOP_NEXT)}});return app[TRUST_PROXY]=options.trustProxy,app},nodeHandler(app){let{toNodeListener}=h3(),state=app;state[ASSEMBLED]||(state[ASSEMBLED]=!0,state[ROUTER]&&app.use(state[ROUTER]));let listener=toNodeListener(app);return(req,res,next)=>{next&&(req[NEXT]=next),Promise.resolve(listener(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){let{createRouter,eventHandler}=h3(),trustProxy=!!app[TRUST_PROXY],state=app;state[ROUTER]||(state[ROUTER]=createRouter());let router=state[ROUTER];for(let{mountPath,routes}of table)for(let entry of routes){let url=joinPath(mountPath,entry.path);router[entry.method.toLowerCase()](url,eventHandler(makeEventHandler(entry,trustProxy)))}},useConnect(app,mw,opts){let{fromNodeMiddleware}=h3(),handler=fromNodeMiddleware(mw);opts?.path===void 0?app.use(handler):app.use(opts.path,handler)},serveStatic(app,prefix,dir){let serveStatic=peerRequire(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app[NOTFOUND_MW]=mw},setErrorHandler(app,mw){app[ERROR_MW]=mw},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,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{h3Runtime};
|
|
12
12
|
//# sourceMappingURL=h3.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"h3.mjs","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"sourcesContent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// h3 (unjs) is the HTTP layer behind Nitro / Nuxt. This binds it to the same\n// HttpRuntime contract as Express and Fastify: routes become native h3 router\n// routes, and the node `ServerResponse` (h3 exposes it as `event.node.res`) is\n// wrapped in a RuntimeResponse so `ctx.json` / `ctx.html` / `ctx.sse` work\n// unchanged.\n//\n// Targets h3 **v1** (stable, node-based: `createApp` / `createRouter` /\n// `toNodeListener`, with `event.node.req` / `event.node.res`). `h3` is an\n// optional peer pinned to `^1`.\n//\n// h3 v2 (https://h3.dev/migration) moves to a web-standard `Request`/`Response`\n// core. Adopting it is the spec's §8 \"web-standard driver\" — `RuntimeResponse`\n// was shaped so a future `webRuntime()` can implement it over WHATWG streams,\n// at which point h3 v2 (and edge/Bun/Deno) become a driver swap rather than a\n// rewrite. Until that lands, this binding uses the node-compatible v1 surface.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport { classifyMediaType, unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { HttpException } from '../../core/errors'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\nconst peerRequire = createRequire(import.meta.url)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst h3 = (): any => peerRequire('h3')\n\ninterface H3EventLike {\n node: { req: IncomingMessage; res: ServerResponse }\n}\ninterface H3AppLike {\n use(arg1: unknown, arg2?: unknown): unknown\n handler: unknown\n}\n\nconst NEXT = Symbol('kickjs.h3.next')\nconst ERROR_MW = Symbol('kickjs.h3.errorMw')\n// h3's `createRouter` is terminal — on no match it THROWS a 404, it does not\n// fall through to the next `app.use` layer like an Express Router. So every\n// route source (controllers, /health, devtools /_debug, ad-hoc adapter routes)\n// must live on ONE shared router, registered AFTER all connect middleware.\nconst ROUTER = Symbol('kickjs.h3.router')\nconst NOTFOUND_MW = Symbol('kickjs.h3.notFoundMw')\nconst ASSEMBLED = Symbol('kickjs.h3.assembled')\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Wrap a node ServerResponse (from `event.node.res`) as a RuntimeResponse.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass NodeResDriver implements RuntimeResponse {\n constructor(private readonly res: ServerResponse) {}\n status(code: number): this {\n this.res.statusCode = code\n return this\n }\n json(data: unknown): this {\n // Do not clobber a content-type the caller already chose. This used to set\n // `application/json` unconditionally, so every `application/problem+json`\n // response — RFC 9457 problem details, which the error handler sets the\n // header for before serialising — went out as plain JSON on this runtime\n // alone. Express and Fastify both leave an existing value alone.\n if (!this.res.headersSent && !this.res.getHeader('content-type')) {\n this.res.setHeader('content-type', 'application/json; charset=utf-8')\n }\n this.res.end(JSON.stringify(data))\n return this\n }\n send(data: unknown): this {\n this.res.end(data as never)\n return this\n }\n type(contentType: string): this {\n this.res.setHeader('content-type', contentType)\n return this\n }\n setHeader(name: string, value: unknown): this {\n this.res.setHeader(name, value as never)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the h3 runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this.res.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n this.res.flushHeaders()\n return this\n }\n write(chunk: unknown): boolean {\n return this.res.write(chunk as never)\n }\n end(data?: unknown): this {\n this.res.end(data as never)\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.res.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.res.headersSent\n }\n}\n\nfunction resDriver(res: ServerResponse): RuntimeResponse {\n return new NodeResDriver(res) as unknown as RuntimeResponse\n}\n\n/** Carries `trustProxy` from createApp() to the per-route handlers. */\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\n\n/** Build the h3 event handler that runs the kickjs pipeline for one route. */\nfunction makeEventHandler(\n entry: RouteEntry,\n trustProxy: boolean,\n): (event: H3EventLike) => Promise<void> {\n const { getRouterParams, getQuery, readRawBody, readMultipartFormData } = h3()\n const upload = entry.meta.upload\n // Validation middleware built ONCE per route (parity with Express) — calling\n // validate() per request re-allocated the closure every time.\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n return async (event: H3EventLike) => {\n const req = event.node.req as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n const res = event.node.res\n\n // h3 computes no client address of its own, so `resolveClientIp` fell\n // straight through to the socket — which behind a proxy is the proxy, and\n // put every caller in one rate-limit bucket with no way to configure out\n // of it (#614). Express and Fastify derive `req.ip` from their own\n // trust-proxy settings; this is h3's equivalent, and like theirs it is\n // OFF unless the app opts in, because an unverified `x-forwarded-for` is\n // client-controllable.\n if (trustProxy && !(req as { ip?: string }).ip) {\n const forwarded = req.headers['x-forwarded-for']\n const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(',')[0]?.trim()\n if (first) (req as { ip?: string }).ip = first\n }\n\n // Populate the express-shaped request fields h3 keeps elsewhere.\n req.params = getRouterParams(event) ?? {}\n req.query = getQuery(event) ?? {}\n\n // HTTP/2 frames a body in DATA frames: no `transfer-encoding`, and\n // `content-length` is optional. h3's `readRawBody` — behind both the\n // JSON/text path and `readMultipartFormData` — returns `undefined` when\n // neither header is present, dropping the body. Read it once as bytes and\n // hand it over on `req.rawBody`, which `readRawBody` checks first.\n if (\n req.httpVersionMajor === 2 &&\n req.headers['content-length'] === undefined &&\n BODY_METHODS.has(req.method ?? 'GET')\n ) {\n ;(req as { rawBody?: Buffer }).rawBody = await readStreamBuffer(req)\n }\n if (upload && upload.mode !== 'none') {\n // @FileUpload: read the multipart body once (readBody would consume the\n // same stream, so the two are mutually exclusive). File parts → the\n // multer-shaped ctx.file/ctx.files; non-file fields → req.body.\n const form = (await readMultipartFormData(event).catch(() => undefined)) as\n | Array<{ name?: string; filename?: string; type?: string; data: Buffer }>\n | undefined\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const part of form ?? []) {\n if (part.filename) {\n rawParts.push({\n fieldname: part.name ?? '',\n filename: part.filename,\n mimetype: part.type ?? 'application/octet-stream',\n buffer: part.data,\n })\n } else if (part.name) {\n fields[part.name] = part.data.toString('utf-8')\n }\n }\n const { file, files } = applyUploadConfig(rawParts, upload)\n req.file = file\n req.files = files\n req.body = fields\n } else if (BODY_METHODS.has(req.method ?? 'GET')) {\n // Swallow ONLY the absent-body case. `.catch(() => undefined)` also\n // swallowed a malformed one, so h3 answered 200 with the handler running\n // on `undefined` where Express and Fastify both answer 400 — a client\n // sending broken JSON got a success response, and the handler executed\n // against data that was never valid.\n // HTTP/2 frames the body in DATA frames: no `transfer-encoding`, and\n // `content-length` is optional, so there a body may be present with\n // neither header — only an explicit `content-length: 0` rules it out.\n const { 'content-length': length, 'transfer-encoding': encoding } = req.headers\n const sentBody =\n encoding !== undefined ||\n (length !== undefined && length !== '0') ||\n (req.httpVersionMajor === 2 && length !== '0')\n if (sentBody) {\n // Read raw and apply the shared policy rather than calling `readBody`,\n // whose own content-type dispatch is the source of the divergence:\n // it matches `application/json` with `===` (so `; charset=utf-8` misses)\n // and routes everything unrecognised through `destr`, which returns the\n // RAW STRING for malformed input instead of throwing (#590).\n const kind = classifyMediaType(req.headers['content-type'])\n if (kind !== 'multipart') {\n const raw = await readRawBody(event, 'utf8')\n // Reject only once the body is known to be non-empty. `sentBody` is\n // true for an empty CHUNKED post — `transfer-encoding` is present\n // with no payload — and rejecting on that alone would 415 a request\n // that sent nothing, contradicting the rule the other runtimes apply.\n if (raw) {\n if (kind === 'unsupported') {\n // A body was sent in a format the framework does not parse. Say\n // so rather than handing the handler `undefined` and letting it\n // fail somewhere less obvious.\n throw unsupportedMediaTypeError(req.headers['content-type'])\n }\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n throw HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = Object.fromEntries(new URLSearchParams(raw))\n } else {\n req.body = raw\n }\n }\n }\n }\n }\n\n const headerId = req.headers['x-request-id']\n const requestId = (Array.isArray(headerId) ? headerId[0] : headerId) || req.requestId\n const store = createRequestStore(requestId)\n req.requestId = store.requestId\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n res.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(req, entry)\n const ctx = new RequestContext(req as never, res as never, NOOP_NEXT, resDriver(res))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (res.writableEnded) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || res.writableEnded) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (res.writableEnded) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n if (!res.writableEnded && !res.headersSent) applyHandlerResult(ctx, result)\n })\n }\n}\n\n/**\n * The original error h3 wrapped.\n *\n * h3 routes every thrown value through `createError()`, which returns its own\n * error with the original on `cause`. Handing that wrapper to the shared error\n * middleware means it sees something Express and Fastify never give it, and the\n * responses diverge: `instanceof HttpException` fails, so a thrown\n * `HttpException(418)` falls through to the generic branch and picks up a\n * `requestId` the other two omit, and `describeError` walks the cause chain to\n * report `kaboom ← caused by kaboom`.\n *\n * Only an `Error` cause is unwrapped. h3's own 404 carries no cause, so the\n * not-found path above is unaffected.\n */\nfunction unwrapH3Error(error: unknown): unknown {\n if (!(error instanceof Error)) return error\n const { cause } = error as { cause?: unknown }\n return cause instanceof Error ? cause : error\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * h3 parses bodies itself (`readBody`), so the Application skips its default\n * `express.json()` (see `nativeBodyParsing`).\n */\n/** Collect a request stream as bytes — never decoded, so file parts stay intact. */\nasync function readStreamBuffer(req: AsyncIterable<Buffer | string>): Promise<Buffer> {\n const chunks: Buffer[] = []\n for await (const chunk of req) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)\n return Buffer.concat(chunks)\n}\n\nexport function h3Runtime(): HttpRuntime<H3AppLike> {\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const { createApp } = h3()\n const app = createApp({\n onError: (error: unknown, event: H3EventLike) => {\n const res = event.node.res\n if (res.writableEnded) return\n const state = app as {\n [ERROR_MW]?: ConnectMiddleware\n [NOTFOUND_MW]?: ConnectMiddleware\n }\n // The shared router throws a 404 on no match (it's terminal). Treat\n // that as \"not found\", not a server error: hand back to the outer\n // chain (Vite dev fall-through) when present, else run the framework's\n // notFound handler so it returns a proper 404 — only genuine handler\n // errors reach the error middleware (and the ErrorHandler log).\n //\n // Only the ROUTER's no-match counts: h3 builds it from a plain object,\n // so its `cause` is not an Error. A handler that throws\n // `HttpException(404, '…')` arrives wrapped with the exception as\n // `cause` — that is a handler error and belongs to the error\n // middleware, which keeps its detail (and reports it to observers).\n const status = (error as { statusCode?: number } | undefined)?.statusCode\n const thrownByHandler = (error as { cause?: unknown } | undefined)?.cause instanceof Error\n if (status === 404 && !thrownByHandler) {\n const next = (event.node.req as IncomingMessage & { [NEXT]?: () => void })[NEXT]\n if (next) {\n next()\n return\n }\n const nf = state[NOTFOUND_MW]\n if (nf) {\n ;(nf as (req: unknown, res: unknown, next: () => void) => void)(\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n return\n }\n }\n const mw = state[ERROR_MW]\n if (mw) {\n ;(mw as (e: unknown, req: unknown, res: unknown, next: () => void) => void)(\n unwrapH3Error(error),\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n }\n },\n })\n // Stash the setting for mountRoutes — h3 has no app-level config object\n // of its own to hang it on.\n ;(app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY] = options.trustProxy\n return app as H3AppLike\n },\n\n nodeHandler(app) {\n const { toNodeListener } = h3()\n // Register the shared router exactly once, AFTER all connect middleware\n // (serveStatic / useConnect) the setup phase added via `app.use` — the\n // router is terminal, so anything that must run for non-route paths has to\n // sit before it in the stack.\n const state = app as { [ROUTER]?: unknown; [ASSEMBLED]?: boolean }\n if (!state[ASSEMBLED]) {\n state[ASSEMBLED] = true\n if (state[ROUTER]) app.use(state[ROUTER])\n }\n const listener = toNodeListener(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n Promise.resolve(listener(req, res)).catch((err) => {\n if (next) next(err)\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n const { createRouter, eventHandler } = h3()\n const trustProxy = Boolean((app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY])\n // One shared router per app — every mountRoutes call (controllers, health,\n // devtools, ad-hoc adapter routes) adds to it. `app.use(router)` is\n // deferred to nodeHandler so the router lands after connect middleware.\n const state = app as { [ROUTER]?: ReturnType<typeof createRouter> }\n if (!state[ROUTER]) state[ROUTER] = createRouter()\n const router = state[ROUTER]\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n router[method](url, eventHandler(makeEventHandler(entry, trustProxy)))\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const { fromNodeMiddleware } = h3()\n const handler = fromNodeMiddleware(mw)\n if (opts?.path !== undefined) app.use(opts.path, handler)\n else app.use(handler)\n },\n\n serveStatic(app, prefix, dir) {\n // `serve-static` (the standalone connect middleware behind express.static)\n // so the h3 runtime carries no `express` dependency — bridged via\n // fromNodeMiddleware like any other connect middleware.\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n // Stash it — the shared router throws a 404 on no match, which `onError`\n // (createApp) dispatches to this handler (or to the Vite fall-through when\n // a `next` is present). A post-router `app.use` could never run, since the\n // terminal router throws before the stack advances.\n ;(app as { [NOTFOUND_MW]?: ConnectMiddleware })[NOTFOUND_MW] = mw\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as { [ERROR_MW]?: ConnectMiddleware })[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types — what the runtime-typed escape hatches\n * resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become the h3 `App`; `ctx.req` / `ctx.res` the per-request `H3Event` (h3 v1\n * routes everything through the event). Mirrors `ExpressRuntimeTypes`.\n */\n// Resolved conditionally so this file typechecks against EITHER installed h3\n// major: v1 exports `App`; v2 (used by the sibling h3-web runtime) does not.\n// Runtime behavior is untouched — this block is type-only.\ntype H3AppType = typeof import('h3') extends { App: infer A } ? A : unknown\ntype H3EventType = typeof import('h3') extends { H3Event: new (...args: never[]) => infer E }\n ? E\n : unknown\n\nexport interface H3RuntimeTypes {\n request: H3EventType\n response: H3EventType\n app: H3AppType\n}\n\n/** Join a mount prefix and a route path; a root path maps to the prefix itself. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;6fAwCA,MAAM,YAAc,cAAc,YAAY,GAAG,EAE3C,OAAgB,YAAY,IAAI,EAUhC,KAAO,OAAO,gBAAgB,EAC9B,SAAW,OAAO,mBAAmB,EAKrC,OAAS,OAAO,kBAAkB,EAClC,YAAc,OAAO,sBAAsB,EAC3C,UAAY,OAAO,qBAAqB,EACxC,cAAwB,CAAC,EACzB,aAAe,IAAI,IAAI,CAAC,OAAQ,MAAO,QAAS,QAAQ,CAAC,EAO/D,IAAM,cAAN,KAA+C,CAChB,IAA7B,YAAY,IAAsC,CAArB,KAAA,IAAA,GAAsB,CACnD,OAAO,KAAoB,CAEzB,MADA,MAAK,IAAI,WAAa,KACf,IACT,CACA,KAAK,KAAqB,CAUxB,MAJI,CAAC,KAAK,IAAI,aAAe,CAAC,KAAK,IAAI,UAAU,cAAc,GAC7D,KAAK,IAAI,UAAU,eAAgB,iCAAiC,EAEtE,KAAK,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC,EAC1B,IACT,CACA,KAAK,KAAqB,CAExB,OADA,KAAK,IAAI,IAAI,IAAa,EACnB,IACT,CACA,KAAK,YAA2B,CAE9B,OADA,KAAK,IAAI,UAAU,eAAgB,WAAW,EACvC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SAAS,OAAQ,CAC1B,IAAM,IAAM,SAAS,UAAW,MAAM,IAAI,EAE1C,OADe,MAAM,OAAO,YAChB,EAAE,CAAC,IAAK,aAAa,iBAAiB,MAAO,UAAU,CAAC,CAAC,CACvE,CAEJ,EAEA,WAAW,IAAK,GAAuB,KAA0B,CAC/D,GAAM,CAAE,oBAAuB,GAAG,EAC5B,QAAU,mBAAmB,EAAE,EACjC,MAAM,OAAS,IAAA,GACd,IAAI,IAAI,OAAO,EADU,IAAI,IAAI,KAAK,KAAM,OAAO,CAE1D,EAEA,YAAY,IAAK,OAAQ,IAAK,CAI5B,IAAM,YAAc,YAAY,cAAc,EAC9C,KAAK,WAAW,IAAK,YAAY,GAAG,EAAwB,CAAE,KAAM,MAAO,CAAC,CAC9E,EAEA,YAAY,IAAK,GAAuB,CAKrC,IAA+C,aAAe,EACjE,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAA4C,UAAY,EAC3D,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAwBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
|
|
1
|
+
{"version":3,"file":"h3.mjs","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"sourcesContent":["// The h3 runtime — `@forinda/kickjs/h3`.\n//\n// h3 (unjs) is the HTTP layer behind Nitro / Nuxt. This binds it to the same\n// HttpRuntime contract as Express and Fastify: routes become native h3 router\n// routes, and the node `ServerResponse` (h3 exposes it as `event.node.res`) is\n// wrapped in a RuntimeResponse so `ctx.json` / `ctx.html` / `ctx.sse` work\n// unchanged.\n//\n// Targets h3 **v1** (stable, node-based: `createApp` / `createRouter` /\n// `toNodeListener`, with `event.node.req` / `event.node.res`). `h3` is an\n// optional peer pinned to `^1`.\n//\n// h3 v2 (https://h3.dev/migration) moves to a web-standard `Request`/`Response`\n// core. Adopting it is the spec's §8 \"web-standard driver\" — `RuntimeResponse`\n// was shaped so a future `webRuntime()` can implement it over WHATWG streams,\n// at which point h3 v2 (and edge/Bun/Deno) become a driver swap rather than a\n// rewrite. Until that lands, this binding uses the node-compatible v1 surface.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport { classifyMediaType, unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { HttpException } from '../../core/errors'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\nconst peerRequire = createRequire(import.meta.url)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst h3 = (): any => peerRequire('h3')\n\ninterface H3EventLike {\n node: { req: IncomingMessage; res: ServerResponse }\n}\ninterface H3AppLike {\n use(arg1: unknown, arg2?: unknown): unknown\n handler: unknown\n}\n\nconst NEXT = Symbol('kickjs.h3.next')\nconst ERROR_MW = Symbol('kickjs.h3.errorMw')\n// h3's `createRouter` is terminal — on no match it THROWS a 404, it does not\n// fall through to the next `app.use` layer like an Express Router. So every\n// route source (controllers, /health, devtools /_debug, ad-hoc adapter routes)\n// must live on ONE shared router, registered AFTER all connect middleware.\nconst ROUTER = Symbol('kickjs.h3.router')\nconst NOTFOUND_MW = Symbol('kickjs.h3.notFoundMw')\nconst ASSEMBLED = Symbol('kickjs.h3.assembled')\nconst NOOP_NEXT = (): void => {}\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * Wrap a node ServerResponse (from `event.node.res`) as a RuntimeResponse.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass NodeResDriver implements RuntimeResponse {\n constructor(private readonly res: ServerResponse) {}\n status(code: number): this {\n this.res.statusCode = code\n return this\n }\n json(data: unknown): this {\n // Do not clobber a content-type the caller already chose. This used to set\n // `application/json` unconditionally, so every `application/problem+json`\n // response — RFC 9457 problem details, which the error handler sets the\n // header for before serialising — went out as plain JSON on this runtime\n // alone. Express and Fastify both leave an existing value alone.\n if (!this.res.headersSent && !this.res.getHeader('content-type')) {\n this.res.setHeader('content-type', 'application/json; charset=utf-8')\n }\n this.res.end(stringifyJson(data))\n return this\n }\n send(data: unknown): this {\n this.res.end(data as never)\n return this\n }\n type(contentType: string): this {\n this.res.setHeader('content-type', contentType)\n return this\n }\n setHeader(name: string, value: unknown): this {\n this.res.setHeader(name, value as never)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the h3 runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this.res.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n this.res.flushHeaders()\n return this\n }\n write(chunk: unknown): boolean {\n return this.res.write(chunk as never)\n }\n end(data?: unknown): this {\n this.res.end(data as never)\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.res.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.res.headersSent\n }\n}\n\nfunction resDriver(res: ServerResponse): RuntimeResponse {\n return new NodeResDriver(res) as unknown as RuntimeResponse\n}\n\n/** Carries `trustProxy` from createApp() to the per-route handlers. */\nconst TRUST_PROXY = Symbol('kickjs.h3.trustProxy')\n\n/** Build the h3 event handler that runs the kickjs pipeline for one route. */\nfunction makeEventHandler(\n entry: RouteEntry,\n trustProxy: boolean,\n): (event: H3EventLike) => Promise<void> {\n const { getRouterParams, getQuery, readRawBody, readMultipartFormData } = h3()\n const upload = entry.meta.upload\n // Validation middleware built ONCE per route (parity with Express) — calling\n // validate() per request re-allocated the closure every time.\n const validator = entry.meta.validation ? validate(entry.meta.validation) : undefined\n return async (event: H3EventLike) => {\n const req = event.node.req as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n const res = event.node.res\n\n // h3 computes no client address of its own, so `resolveClientIp` fell\n // straight through to the socket — which behind a proxy is the proxy, and\n // put every caller in one rate-limit bucket with no way to configure out\n // of it (#614). Express and Fastify derive `req.ip` from their own\n // trust-proxy settings; this is h3's equivalent, and like theirs it is\n // OFF unless the app opts in, because an unverified `x-forwarded-for` is\n // client-controllable.\n if (trustProxy && !(req as { ip?: string }).ip) {\n const forwarded = req.headers['x-forwarded-for']\n const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(',')[0]?.trim()\n if (first) (req as { ip?: string }).ip = first\n }\n\n // Populate the express-shaped request fields h3 keeps elsewhere.\n req.params = getRouterParams(event) ?? {}\n req.query = getQuery(event) ?? {}\n\n // HTTP/2 frames a body in DATA frames: no `transfer-encoding`, and\n // `content-length` is optional. h3's `readRawBody` — behind both the\n // JSON/text path and `readMultipartFormData` — returns `undefined` when\n // neither header is present, dropping the body. Read it once as bytes and\n // hand it over on `req.rawBody`, which `readRawBody` checks first.\n if (\n req.httpVersionMajor === 2 &&\n req.headers['content-length'] === undefined &&\n BODY_METHODS.has(req.method ?? 'GET')\n ) {\n ;(req as { rawBody?: Buffer }).rawBody = await readStreamBuffer(req)\n }\n if (upload && upload.mode !== 'none') {\n // @FileUpload: read the multipart body once (readBody would consume the\n // same stream, so the two are mutually exclusive). File parts → the\n // multer-shaped ctx.file/ctx.files; non-file fields → req.body.\n const form = (await readMultipartFormData(event).catch(() => undefined)) as\n | Array<{ name?: string; filename?: string; type?: string; data: Buffer }>\n | undefined\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for (const part of form ?? []) {\n if (part.filename) {\n rawParts.push({\n fieldname: part.name ?? '',\n filename: part.filename,\n mimetype: part.type ?? 'application/octet-stream',\n buffer: part.data,\n })\n } else if (part.name) {\n fields[part.name] = part.data.toString('utf-8')\n }\n }\n const { file, files } = applyUploadConfig(rawParts, upload)\n req.file = file\n req.files = files\n req.body = fields\n } else if (BODY_METHODS.has(req.method ?? 'GET')) {\n // Swallow ONLY the absent-body case. `.catch(() => undefined)` also\n // swallowed a malformed one, so h3 answered 200 with the handler running\n // on `undefined` where Express and Fastify both answer 400 — a client\n // sending broken JSON got a success response, and the handler executed\n // against data that was never valid.\n // HTTP/2 frames the body in DATA frames: no `transfer-encoding`, and\n // `content-length` is optional, so there a body may be present with\n // neither header — only an explicit `content-length: 0` rules it out.\n const { 'content-length': length, 'transfer-encoding': encoding } = req.headers\n const sentBody =\n encoding !== undefined ||\n (length !== undefined && length !== '0') ||\n (req.httpVersionMajor === 2 && length !== '0')\n if (sentBody) {\n // Read raw and apply the shared policy rather than calling `readBody`,\n // whose own content-type dispatch is the source of the divergence:\n // it matches `application/json` with `===` (so `; charset=utf-8` misses)\n // and routes everything unrecognised through `destr`, which returns the\n // RAW STRING for malformed input instead of throwing (#590).\n const kind = classifyMediaType(req.headers['content-type'])\n if (kind !== 'multipart') {\n const raw = await readRawBody(event, 'utf8')\n // Reject only once the body is known to be non-empty. `sentBody` is\n // true for an empty CHUNKED post — `transfer-encoding` is present\n // with no payload — and rejecting on that alone would 415 a request\n // that sent nothing, contradicting the rule the other runtimes apply.\n if (raw) {\n if (kind === 'unsupported') {\n // A body was sent in a format the framework does not parse. Say\n // so rather than handing the handler `undefined` and letting it\n // fail somewhere less obvious.\n throw unsupportedMediaTypeError(req.headers['content-type'])\n }\n if (kind === 'json') {\n try {\n req.body = JSON.parse(raw)\n } catch (err) {\n throw HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n )\n }\n } else if (kind === 'urlencoded') {\n req.body = Object.fromEntries(new URLSearchParams(raw))\n } else {\n req.body = raw\n }\n }\n }\n }\n }\n\n const headerId = req.headers['x-request-id']\n const requestId = (Array.isArray(headerId) ? headerId[0] : headerId) || req.requestId\n const store = createRequestStore(requestId)\n req.requestId = store.requestId\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n res.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(req, entry)\n const ctx = new RequestContext(req as never, res as never, NOOP_NEXT, resDriver(res))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (res.writableEnded) return\n }\n\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(req as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || res.writableEnded) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (res.writableEnded) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n if (!res.writableEnded && !res.headersSent) applyHandlerResult(ctx, result)\n })\n }\n}\n\n/**\n * The original error h3 wrapped.\n *\n * h3 routes every thrown value through `createError()`, which returns its own\n * error with the original on `cause`. Handing that wrapper to the shared error\n * middleware means it sees something Express and Fastify never give it, and the\n * responses diverge: `instanceof HttpException` fails, so a thrown\n * `HttpException(418)` falls through to the generic branch and picks up a\n * `requestId` the other two omit, and `describeError` walks the cause chain to\n * report `kaboom ← caused by kaboom`.\n *\n * Only an `Error` cause is unwrapped. h3's own 404 carries no cause, so the\n * not-found path above is unaffected.\n */\nfunction unwrapH3Error(error: unknown): unknown {\n if (!(error instanceof Error)) return error\n const { cause } = error as { cause?: unknown }\n return cause instanceof Error ? cause : error\n}\n\n/**\n * The h3 HTTP runtime. Pass to `bootstrap({ runtime: h3Runtime() })`.\n * h3 parses bodies itself (`readBody`), so the Application skips its default\n * `express.json()` (see `nativeBodyParsing`).\n */\n/** Collect a request stream as bytes — never decoded, so file parts stay intact. */\nasync function readStreamBuffer(req: AsyncIterable<Buffer | string>): Promise<Buffer> {\n const chunks: Buffer[] = []\n for await (const chunk of req) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)\n return Buffer.concat(chunks)\n}\n\nexport function h3Runtime(): HttpRuntime<H3AppLike> {\n return {\n name: 'h3',\n\n createApp(options: RuntimeAppOptions = {}): H3AppLike {\n const { createApp } = h3()\n const app = createApp({\n onError: (error: unknown, event: H3EventLike) => {\n const res = event.node.res\n if (res.writableEnded) return\n const state = app as {\n [ERROR_MW]?: ConnectMiddleware\n [NOTFOUND_MW]?: ConnectMiddleware\n }\n // The shared router throws a 404 on no match (it's terminal). Treat\n // that as \"not found\", not a server error: hand back to the outer\n // chain (Vite dev fall-through) when present, else run the framework's\n // notFound handler so it returns a proper 404 — only genuine handler\n // errors reach the error middleware (and the ErrorHandler log).\n //\n // Only the ROUTER's no-match counts: h3 builds it from a plain object,\n // so its `cause` is not an Error. A handler that throws\n // `HttpException(404, '…')` arrives wrapped with the exception as\n // `cause` — that is a handler error and belongs to the error\n // middleware, which keeps its detail (and reports it to observers).\n const status = (error as { statusCode?: number } | undefined)?.statusCode\n const thrownByHandler = (error as { cause?: unknown } | undefined)?.cause instanceof Error\n if (status === 404 && !thrownByHandler) {\n const next = (event.node.req as IncomingMessage & { [NEXT]?: () => void })[NEXT]\n if (next) {\n next()\n return\n }\n const nf = state[NOTFOUND_MW]\n if (nf) {\n ;(nf as (req: unknown, res: unknown, next: () => void) => void)(\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n return\n }\n }\n const mw = state[ERROR_MW]\n if (mw) {\n ;(mw as (e: unknown, req: unknown, res: unknown, next: () => void) => void)(\n unwrapH3Error(error),\n event.node.req,\n resDriver(res),\n NOOP_NEXT,\n )\n }\n },\n })\n // Stash the setting for mountRoutes — h3 has no app-level config object\n // of its own to hang it on.\n ;(app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY] = options.trustProxy\n return app as H3AppLike\n },\n\n nodeHandler(app) {\n const { toNodeListener } = h3()\n // Register the shared router exactly once, AFTER all connect middleware\n // (serveStatic / useConnect) the setup phase added via `app.use` — the\n // router is terminal, so anything that must run for non-route paths has to\n // sit before it in the stack.\n const state = app as { [ROUTER]?: unknown; [ASSEMBLED]?: boolean }\n if (!state[ASSEMBLED]) {\n state[ASSEMBLED] = true\n if (state[ROUTER]) app.use(state[ROUTER])\n }\n const listener = toNodeListener(app)\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n Promise.resolve(listener(req, res)).catch((err) => {\n if (next) next(err)\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n const { createRouter, eventHandler } = h3()\n const trustProxy = Boolean((app as { [TRUST_PROXY]?: unknown })[TRUST_PROXY])\n // One shared router per app — every mountRoutes call (controllers, health,\n // devtools, ad-hoc adapter routes) adds to it. `app.use(router)` is\n // deferred to nodeHandler so the router lands after connect middleware.\n const state = app as { [ROUTER]?: ReturnType<typeof createRouter> }\n if (!state[ROUTER]) state[ROUTER] = createRouter()\n const router = state[ROUTER]\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n const url = joinPath(mountPath, entry.path)\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n router[method](url, eventHandler(makeEventHandler(entry, trustProxy)))\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const { fromNodeMiddleware } = h3()\n const handler = fromNodeMiddleware(mw)\n if (opts?.path !== undefined) app.use(opts.path, handler)\n else app.use(handler)\n },\n\n serveStatic(app, prefix, dir) {\n // `serve-static` (the standalone connect middleware behind express.static)\n // so the h3 runtime carries no `express` dependency — bridged via\n // fromNodeMiddleware like any other connect middleware.\n const serveStatic = peerRequire('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n // Stash it — the shared router throws a 404 on no match, which `onError`\n // (createApp) dispatches to this handler (or to the Vite fall-through when\n // a `next` is present). A post-router `app.use` could never run, since the\n // terminal router throws before the stack advances.\n ;(app as { [NOTFOUND_MW]?: ConnectMiddleware })[NOTFOUND_MW] = mw\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as { [ERROR_MW]?: ConnectMiddleware })[ERROR_MW] = mw\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The h3 runtime's engine-native types — what the runtime-typed escape hatches\n * resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become the h3 `App`; `ctx.req` / `ctx.res` the per-request `H3Event` (h3 v1\n * routes everything through the event). Mirrors `ExpressRuntimeTypes`.\n */\n// Resolved conditionally so this file typechecks against EITHER installed h3\n// major: v1 exports `App`; v2 (used by the sibling h3-web runtime) does not.\n// Runtime behavior is untouched — this block is type-only.\ntype H3AppType = typeof import('h3') extends { App: infer A } ? A : unknown\ntype H3EventType = typeof import('h3') extends { H3Event: new (...args: never[]) => infer E }\n ? E\n : unknown\n\nexport interface H3RuntimeTypes {\n request: H3EventType\n response: H3EventType\n app: H3AppType\n}\n\n/** Join a mount prefix and a route path; a root path maps to the prefix itself. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `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AAM,MAAO,CAAC,CAC9E,EAEA,YAAY,IAAK,GAAuB,CAKrC,IAA+C,aAAe,EACjE,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAA4C,UAAY,EAC3D,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAwBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAG7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { p as EnvKey } from "./decorators-
|
|
2
|
+
import { p as EnvKey } from "./decorators-BxNSz9Qt.mjs";
|
|
3
3
|
import { InferSchemaOutput } from "@forinda/kickjs-schema";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
//#region src/config/env.d.ts
|
|
@@ -140,8 +140,8 @@ declare function reloadEnv(): void;
|
|
|
140
140
|
declare function resetEnvCache(): void;
|
|
141
141
|
/**
|
|
142
142
|
* Schema-agnostic env loader. Accepts any schema supported by
|
|
143
|
-
* `@forinda/kickjs-schema` (Zod, Valibot, Yup,
|
|
144
|
-
* KickSchema
|
|
143
|
+
* `@forinda/kickjs-schema` (Zod, Valibot, Yup, any Standard Schema, a
|
|
144
|
+
* KickSchema or one from a registered adapter, or a plain validator function).
|
|
145
145
|
*
|
|
146
146
|
* Unlike `loadEnv()` which uses Zod's `.parse()` and throws a
|
|
147
147
|
* `ZodError`, this function uses `detectSchema().safeParse()` and
|
|
@@ -310,4 +310,4 @@ declare function createConfigService<T extends z.ZodObject<any>>(schema: T): {
|
|
|
310
310
|
};
|
|
311
311
|
//#endregion
|
|
312
312
|
export { baseEnvSchema as a, loadEnv as c, resetEnvCache as d, withEnv as f, Env as i, loadEnvFromSchema as l, TypedConfigService as n, defineEnv as o, createConfigService as r, getEnv as s, ConfigService as t, reloadEnv as u };
|
|
313
|
-
//# sourceMappingURL=index-
|
|
313
|
+
//# sourceMappingURL=index-CNHSbZTE.d.mts.map
|