@schmock/express 2.2.3 → 2.3.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Khalic Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # @schmock/express
2
+
3
+ Express middleware adapter for Schmock.
4
+
5
+ Part of [Schmock](https://github.com/khalic-lab/schmock) — mock APIs from OpenAPI specs or hand-crafted routes.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add -d @schmock/express
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ import express from "express";
17
+ import { schmock } from "@schmock/core";
18
+ import { toExpress } from "@schmock/express";
19
+
20
+ const mock = schmock();
21
+ mock("GET /users", [{ id: 1, name: "Alice" }]);
22
+
23
+ const app = express();
24
+ app.use("/api", toExpress(mock));
25
+ ```
26
+
27
+ ## Documentation
28
+
29
+ - [Express adapter](https://github.com/khalic-lab/schmock/blob/main/docs/express.md)
30
+ - [API reference](https://github.com/khalic-lab/schmock/blob/main/docs/api.md)
31
+
32
+ ## License
33
+
34
+ MIT © Khalic Lab
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type * as Schmock from "@schmock/core";
1
2
  import type { Request, RequestHandler, Response } from "express";
2
3
  /**
3
4
  * Configuration options for Express adapter
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAgB,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAE/E;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC;IAEzD;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE3E;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAErE;;;;;OAKG;IACH,aAAa,CAAC,EAAE,CACd,GAAG,EAAE,OAAO,EACZ,GAAG,EAAE,QAAQ,KAEX,OAAO,CAAC,sBAAsB,GAC9B,SAAS,GACT,OAAO,CAAC,OAAO,CAAC,sBAAsB,GAAG,SAAS,CAAC,CAAC;IAExD;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,CACf,eAAe,EAAE,OAAO,CAAC,QAAQ,EACjC,GAAG,EAAE,OAAO,EACZ,GAAG,EAAE,QAAQ,KACV,OAAO,CAAC,QAAQ,GAAG,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC;CAC3E;AAqED;;GAEG;AACH,wBAAgB,SAAS,CACvB,IAAI,EAAE,OAAO,CAAC,oBAAoB,EAClC,OAAO,GAAE,qBAA0B,GAClC,cAAc,CAyGhB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,OAAO,MAAM,eAAe,CAAC;AAU9C,OAAO,KAAK,EAAgB,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAuF/E;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC;IAEzD;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE3E;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAErE;;;;;OAKG;IACH,aAAa,CAAC,EAAE,CACd,GAAG,EAAE,OAAO,EACZ,GAAG,EAAE,QAAQ,KAEX,OAAO,CAAC,sBAAsB,GAC9B,SAAS,GACT,OAAO,CAAC,OAAO,CAAC,sBAAsB,GAAG,SAAS,CAAC,CAAC;IAExD;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,CACf,eAAe,EAAE,OAAO,CAAC,QAAQ,EACjC,GAAG,EAAE,OAAO,EACZ,GAAG,EAAE,QAAQ,KACV,OAAO,CAAC,QAAQ,GAAG,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC;CAC3E;AAkJD;;GAEG;AACH,wBAAgB,SAAS,CACvB,IAAI,EAAE,OAAO,CAAC,oBAAoB,EAClC,OAAO,GAAE,qBAA0B,GAClC,cAAc,CAsLhB"}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{createRequire as a}from"node:module";var o=a(import.meta.url);var y=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"];function g(V){return y.includes(V)}function F(V){let $=V.toUpperCase();if(!g($))throw Error(`Invalid HTTP method: "${V}"`);return $}function I(V){return V.endsWith("/")&&V!=="/"?V.slice(0,-1):V}function x(V){let{status:$,body:J}=V;return $===404&&J!==null&&typeof J==="object"&&"code"in J&&J.code==="ROUTE_NOT_FOUND"}function E(V){return Array.isArray(V)&&(V.length===2||V.length===3)&&typeof V[0]==="number"&&V[0]>=100&&V[0]<=599}function D(V){return V instanceof Error?V.message:"Unknown error"}class T extends Error{code;context;constructor(V,$,J){super(V);this.code=$;this.context=J;if(this.name="SchmockError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor)}}class P extends T{constructor(V,$){super(`Route not found: ${V} ${$}`,"ROUTE_NOT_FOUND",{method:V,path:$});this.name="RouteNotFoundError"}}class b extends T{constructor(V,$){super(`Invalid route key format: "${V}". ${$}`,"ROUTE_PARSE_ERROR",{routeKey:V,reason:$});this.name="RouteParseError"}}class H extends T{constructor(V,$){super(`Plugin "${V}" failed: ${$.message}`,"PLUGIN_ERROR",{pluginName:V,originalError:$});this.name="PluginError"}}class S extends T{constructor(V,$){super(`Invalid route definition for "${V}": ${$}`,"ROUTE_DEFINITION_ERROR",{routeKey:V,reason:$});this.name="RouteDefinitionError"}}function f(V){let $={};for(let[J,X]of Object.entries(V.headers))if(typeof X==="string")$[J]=X;return $}function k(V){let $={};return V.searchParams.forEach((J,X)=>{$[X]=J}),$}var s=10485760;function R(V,$,J=s){return new Promise((X,Y)=>{let G=[],_=0;V.on("error",Y),V.on("data",(Z)=>{if(_+=Z.length,_>J){V.destroy(),Y(Object.assign(Error("Request body too large"),{status:413}));return}G.push(Z)}),V.on("end",()=>{let Z=Buffer.concat(G).toString();if(!Z){X(void 0);return}if(($["content-type"]??"").includes("json"))try{X(JSON.parse(Z))}catch{X(Z)}else X(Z)})})}function v(V,$,J){let X={...$.headers,...J};if(!X["content-type"]&&$.body!==void 0&&typeof $.body!=="string")X["content-type"]="application/json";let Y=$.body===void 0?void 0:typeof $.body==="string"?$.body:JSON.stringify($.body);V.writeHead($.status,X),V.end(Y)}function t(V){let $=V.indexOf("?"),J=$===-1?V:V.slice(0,$);if(J.includes("://"))try{return new URL(J).pathname}catch{}if(!J.startsWith("/"))return`/${J}`;return J}function r(V){if(!V.includes("://"))return null;try{return new URL(V).origin}catch{return null}}function e(V){if(V.includes("://"))try{let $=new URL(V),J=$.pathname,X=J==="/"?"":J.replace(/\/$/,"");return{origin:$.origin,path:X}}catch{}return{origin:null,path:V.replace(/\/$/,"")}}function V0(V){let $=V.indexOf("?");if($===-1)return{};let J=new URLSearchParams(V.slice($+1)),X={};return J.forEach((Y,G)=>{X[G]=Y}),X}function $0(V,$){let J={},X=$?.headers??(V instanceof Request?V.headers:void 0);if(!X)return J;if(X instanceof Headers)X.forEach((Y,G)=>{J[G.toLowerCase()]=Y});else if(Array.isArray(X))for(let[Y,G]of X)J[Y.toLowerCase()]=G;else for(let Y of Object.keys(X))J[Y.toLowerCase()]=X[Y];return J}async function J0(V,$){let J=$?.body??(V instanceof Request?V.body:null);if(J===null||J===void 0)return;if(typeof J==="string")try{return JSON.parse(J)}catch{return J}if(J instanceof URLSearchParams){let X={};return J.forEach((Y,G)=>{X[G]=Y}),X}if(V instanceof Request&&!$?.body&&V.body)try{return await V.clone().json()}catch{try{return await V.clone().text()}catch{return}}return}function q(V,$={}){let{baseUrl:J,passthrough:X=!0,beforeRequest:Y,beforeResponse:G,errorFormatter:_}=$,Z=globalThis.fetch,L=!0;return globalThis.fetch=async(A,W)=>{let U=A instanceof Request?A.url:A instanceof URL?A.href:A,B=t(U);if(J){let{origin:K,path:z}=e(J);if(K){if(r(U)!==K)return Z(A,W)}if(z){if(!(B===z||B.startsWith(`${z}/`)))return Z(A,W)}}let O=A instanceof Request?A.method:W?.method??"GET",Q=$0(A,W),N=V0(U),j=await J0(A,W),M={method:O,path:B,headers:Q,body:j,query:N};try{if(Y){let C=await Y(M);if(C)M=C}let K=await V(F(M.method),M.path,{headers:M.headers,body:M.body,query:M.query});if(x(K)){if(X)return Z(A,W);return new Response(JSON.stringify({error:"No matching mock route found",code:"ROUTE_NOT_FOUND"}),{status:404,headers:{"content-type":"application/json"}})}let z=K;if(G){let C=await G(z,M);if(C)z=C}let w=new Headers(z.headers);if(!w.has("content-type")&&z.body!==null&&z.body!==void 0)w.set("content-type","application/json");let n=z.body===null||z.body===void 0?null:typeof z.body==="string"?z.body:JSON.stringify(z.body);return new Response(n,{status:z.status,headers:w})}catch(K){if(_){let z=_(K instanceof Error?K:Error(String(K)));return new Response(JSON.stringify(z),{status:500,headers:{"content-type":"application/json"}})}throw K}},{restore(){if(L)globalThis.fetch=Z,L=!1},get active(){return L}}}function d(V){let $=V.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) (.+)$/);if(!$)throw new b(V,'Expected format: "METHOD /path" (e.g., "GET /users")');let[,J,X]=$,Y=[],G=X.split(/(:[a-zA-Z0-9_-]+)/g).map((Z)=>{let L=Z.match(/^:([a-zA-Z0-9_-]+)$/);if(L)return Y.push(L[1]),"([^/]+)";return Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join(""),_=new RegExp(`^${G}$`);return{method:F(J),path:X,pattern:_,params:Y}}async function m(V,$,J,X){let Y=$,G=J;X.log("pipeline",`Running plugin pipeline for ${V.length} plugins`);for(let _ of V){X.log("pipeline",`Processing plugin: ${_.name}`);try{let Z=await _.process(Y,G);if(!Z?.context)throw Error(`Plugin ${_.name} didn't return valid result`);if(Y=Z.context,Z.response!==void 0&&(G===void 0||G===null))X.log("pipeline",`Plugin ${_.name} generated response`),G=Z.response;else if(Z.response!==void 0&&G!==void 0)X.log("pipeline",`Plugin ${_.name} transformed response`),G=Z.response}catch(Z){if(X.log("pipeline",`Plugin ${_.name} failed: ${D(Z)}`),_.onError)try{let A=Z instanceof Error?Z:Error(D(Z)),W=await _.onError(A,Y);if(W){if(X.log("pipeline",`Plugin ${_.name} handled error`),W instanceof Error)throw new H(_.name,W);if(E(W)||typeof W==="object"&&W!==null&&"status"in W){G=W;break}}}catch(A){if(A instanceof H)throw A;X.log("pipeline",`Plugin ${_.name} error handler failed: ${D(A)}`)}let L=Z instanceof Error?Z:Error(D(Z));throw new H(_.name,L)}}return{context:Y,response:G}}function X0(V){return typeof V==="object"&&V!==null&&"status"in V&&typeof V.status==="number"&&"body"in V}function c(V,$){let J=200,X=V,Y={},G=!1;if(X0(V))return{status:V.status,body:V.body,headers:V.headers||{}};if(E(V))[J,X,Y={}]=V,G=!0;if(X===null||X===void 0){if(!G)J=J===200?204:J;X=void 0}if(!Y["content-type"]&&$.contentType&&!G){if(Y["content-type"]=$.contentType,$.contentType==="text/plain"&&X!==void 0){if(typeof X==="object"&&!Buffer.isBuffer(X))X=JSON.stringify(X);else if(typeof X!=="string")X=String(X)}}return{status:J,body:X,headers:Y}}function l(V){return typeof V==="function"}function h(V,$,J,X){let Y=J.get(`${V} ${I($)}`);if(Y)return Y;for(let G of X)if(G.method===V&&G.params.length>0&&G.pattern.test($))return G;return}function i(V,$){let J=$.match(V.pattern);if(!J)return{};let X={};return V.params.forEach((Y,G)=>{X[Y]=J[G+1]}),X}class p{enabled;constructor(V=!1){this.enabled=V}log(V,$,J){if(!this.enabled)return;let Y=`[${new Date().toISOString()}] [SCHMOCK:${V.toUpperCase()}]`;if(J)console.log(`${Y} ${$}`,J);else console.log(`${Y} ${$}`)}time(V){if(!this.enabled)return;console.time(`[SCHMOCK] ${V}`)}timeEnd(V){if(!this.enabled)return;console.timeEnd(`[SCHMOCK] ${V}`)}}class u{globalConfig;routes=[];staticRoutes=new Map;plugins=[];logger;requestHistory=[];callableRef;server;serverInfo;interceptHandle=null;listeners=new Map;constructor(V={}){this.globalConfig=V;if(this.logger=new p(V.debug||!1),V.debug)this.logger.log("config","Debug mode enabled");this.logger.log("config","Callable mock instance created",{debug:V.debug,namespace:V.namespace,delay:V.delay})}defineRoute(V,$,J){let X={...J};if(!X.contentType)if(typeof $==="function")X.contentType="application/json";else if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")X.contentType="text/plain";else if(Buffer.isBuffer($))X.contentType="application/octet-stream";else X.contentType="application/json";if(typeof $!=="function"&&X.contentType==="application/json")try{JSON.stringify($)}catch(L){throw new S(V,"Generator data is not valid JSON but contentType is application/json")}let Y=d(V),G=I(Y.path);if(this.routes.find((L)=>L.method===Y.method&&I(L.path)===G))return this.logger.log("warning",`Duplicate route: ${V} — first registration wins`),this;let Z={pattern:Y.pattern,params:Y.params,method:Y.method,path:Y.path,generator:$,config:X};if(this.routes.push(Z),Y.params.length===0){let L=`${Y.method} ${I(Y.path)}`;this.staticRoutes.set(L,Z)}return this.logger.log("route",`Route defined: ${V}`,{contentType:X.contentType,generatorType:typeof $,hasParams:Y.params.length>0}),this}setCallableRef(V){this.callableRef=V}pipe(V){if(this.plugins.push(V),this.logger.log("plugin",`Registered plugin: ${V.name}@${V.version||"unknown"}`,{name:V.name,version:V.version,hasProcess:typeof V.process==="function",hasOnError:typeof V.onError==="function"}),V.install&&this.callableRef)V.install(this.callableRef);return this}cloneRecord(V){try{return structuredClone(V)}catch{return{...V,response:{...V.response}}}}history(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$)).map((J)=>this.cloneRecord(J));return this.requestHistory.map((J)=>this.cloneRecord(J))}called(V,$){if(V||$)return this.requestHistory.some((J)=>(!V||J.method===V)&&(!$||J.path===$));return this.requestHistory.length>0}callCount(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$)).length;return this.requestHistory.length}lastRequest(V,$){if(V||$){let X=this.requestHistory.filter((G)=>(!V||G.method===V)&&(!$||G.path===$)),Y=X[X.length-1];return Y?this.cloneRecord(Y):void 0}let J=this.requestHistory[this.requestHistory.length-1];return J?this.cloneRecord(J):void 0}getRoutes(){return this.routes.map((V)=>({method:V.method,path:V.path,hasParams:V.params.length>0}))}getState(){return{...this.globalConfig.state||{}}}on(V,$){let J=this.listeners.get(V);if(!J)J=new Set,this.listeners.set(V,J);return J.add($),this}off(V,$){return this.listeners.get(V)?.delete($),this}emit(V,$){let J=this.listeners.get(V);if(J)for(let X of J)X($)}reset(){if(this.interceptHandle?.restore(),this.interceptHandle=null,this.close(),this.routes=[],this.staticRoutes.clear(),this.plugins=[],this.requestHistory=[],this.listeners.clear(),this.globalConfig.state)this.globalConfig.state={};this.logger.log("lifecycle","Mock fully reset")}resetHistory(){this.requestHistory=[],this.logger.log("lifecycle","Request history cleared")}resetState(){if(this.globalConfig.state)this.globalConfig.state={};this.logger.log("lifecycle","State cleared")}listen(V=0,$="127.0.0.1"){if(this.server)throw new T("Server is already running","SERVER_ALREADY_RUNNING");return import("node:http").then(({createServer:J})=>this.#V(J,V,$))}#V(V,$,J){let X=V((Y,G)=>{(async()=>{let Z=new URL(Y.url??"/",`http://${Y.headers.host}`),L=F(Y.method??"GET"),A=Z.pathname,W=f(Y),U=k(Z),B=await R(Y,W),O=await this.handle(L,A,{headers:W,body:B,query:U});v(G,O)})().catch((Z)=>{if(!G.headersSent)G.writeHead(500,{"content-type":"application/json"});G.end(JSON.stringify({error:Z instanceof Error?Z.message:"Internal Server Error",code:"SERVER_ERROR"}))})});return this.server=X,new Promise((Y,G)=>{X.on("error",G),X.listen($,J,()=>{let _=X.address(),Z=_!==null&&typeof _==="object"?_.port:$;this.serverInfo={port:Z,hostname:J},this.logger.log("server",`Listening on ${J}:${Z}`),Y(this.serverInfo)})})}close(){if(!this.server)return;this.server.closeAllConnections(),this.server.close(),this.server=void 0,this.serverInfo=void 0,this.logger.log("server","Server stopped")}intercept(V){if(this.interceptHandle?.active)throw new T("Already intercepting. Call restore() first.","ALREADY_INTERCEPTING");return this.interceptHandle=q(($,J,X)=>this.handle($,J,X),V),this.interceptHandle}async handle(V,$,J){let X=performance.now(),Y=this.globalConfig.debug?crypto.randomUUID():"",G=J?.query||{},_=J?.headers||{};this.logger.log("request",`[${Y}] ${V} ${$}`,{headers:_,query:G,bodyType:J?.body?typeof J.body:"none"}),this.logger.time(`request-${Y}`),this.emit("request:start",{method:V,path:$,headers:_});try{let Z=$;if(this.globalConfig.namespace&&this.globalConfig.namespace!=="/"){let N=this.globalConfig.namespace.startsWith("/")?this.globalConfig.namespace:`/${this.globalConfig.namespace}`,j=$.startsWith("/")?$:`/${$}`;if(!(j===N||j.startsWith(N.endsWith("/")?N:`${N}/`))){this.logger.log("route",`[${Y}] Path doesn't match namespace ${N}`);let z=new P(V,$),w={status:404,body:{error:z.message,code:z.code},headers:{}};return this.emit("request:end",{method:V,path:$,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),w}let K=j.slice(N.length);Z=K.startsWith("/")?K:`/${K}`}let L=h(V,Z,this.staticRoutes,this.routes);if(!L){this.logger.log("route",`[${Y}] No route found for ${V} ${Z}`),this.emit("request:notfound",{method:V,path:Z});let N=new P(V,$),j={status:404,body:{error:N.message,code:N.code},headers:{}};return this.emit("request:end",{method:V,path:Z,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),j}this.logger.log("route",`[${Y}] Matched route: ${V} ${L.path}`);let A=i(L,Z);this.emit("request:match",{method:V,path:Z,routePath:L.path,params:A});let W={method:V,path:Z,params:A,query:G,headers:_,body:J?.body,state:this.globalConfig.state||{}},U;if(l(L.generator))U=await L.generator(W);else U=L.generator;let B={path:Z,route:L.config,method:V,params:A,query:G,headers:_,body:J?.body,state:new Map,routeState:this.globalConfig.state||{}};try{let N=await m(this.plugins,B,U,this.logger);B=N.context,U=N.response}catch(N){throw this.logger.log("error",`[${Y}] Plugin pipeline error: ${D(N)}`),N}let O=c(U,L.config);await this.applyDelay(L.config.delay),this.requestHistory.push({method:V,path:Z,params:A,query:G,headers:_,body:J?.body,timestamp:Date.now(),response:{status:O.status,body:O.body}});let Q=this.globalConfig.maxHistorySize;if(typeof Q==="number"&&Q>=0&&this.requestHistory.length>Q)this.requestHistory.splice(0,this.requestHistory.length-Q);return this.emit("request:end",{method:V,path:Z,status:O.status,duration:performance.now()-X}),this.logger.log("response",`[${Y}] Sending response ${O.status}`,{status:O.status,headers:O.headers,bodyType:typeof O.body}),this.logger.timeEnd(`request-${Y}`),O}catch(Z){this.logger.log("error",`[${Y}] Error processing request: ${D(Z)}`,Z);let L={status:500,body:{error:D(Z),code:Z instanceof T?Z.code:"INTERNAL_ERROR"},headers:{}};return await this.applyDelay(),this.emit("request:end",{method:V,path:$,status:500,duration:performance.now()-X}),this.logger.log("error",`[${Y}] Returning error response 500`),this.logger.timeEnd(`request-${Y}`),L}}async applyDelay(V){let $=V??this.globalConfig.delay;if(!$)return;let J=Array.isArray($)?Math.random()*($[1]-$[0])+$[0]:$;await new Promise((X)=>setTimeout(X,J))}}function Y0(V,$){if(V.status!=null)$.status(V.status);if(V.headers)Object.entries(V.headers).forEach(([J,X])=>{if(typeof X==="string")$.set(J,X)});if(V.body!==void 0)if(typeof V.body==="string")$.send(V.body);else $.json(V.body);else $.end()}function Z0(V){return Object.fromEntries(Object.entries(V).map(([$,J])=>[$,Array.isArray(J)?J[0]:J]).filter(($)=>typeof $[1]==="string"))}function G0(V){let $={};for(let[J,X]of Object.entries(V))if(typeof X==="string")$[J]=X;else if(Array.isArray(X))$[J]=X[0]?String(X[0]):"";else if(X!=null)$[J]=String(X);return $}function J1(V,$={}){let{errorFormatter:J,passErrorsToNext:X=!0,transformHeaders:Y=Z0,transformQuery:G=G0,beforeRequest:_,beforeResponse:Z}=$;return async(L,A,W)=>{try{let U;try{U=F(L.method)}catch{return W()}let B={method:U,path:L.path,headers:Y(L.headers),body:L.body,query:G(L.query)};if(_){let Q=await _(L,A);if(Q)B={...B,...Q,method:F(Q.method||B.method)}}let O=await V.handle(B.method,B.path,{headers:B.headers,body:B.body,query:B.query});if(x(O)){W();return}if(Z){let Q=await Z(O,L,A);if(Q)O=Q}if(J&&O.status===500&&O.body!==null&&typeof O.body==="object"&&"error"in O.body&&"code"in O.body){let Q=O.body,N=typeof Q.error==="string"?Q.error:"Unknown error",j=J(Error(N),L);A.status(500).json(j);return}Y0(O,A)}catch(U){if(J){let B=U instanceof Error?U:Error(String(U)),O=J(B,L);A.status(500).json(O)}else if(X)W(U);else A.status(500).json({error:U instanceof Error?U.message:"Internal Server Error",code:U instanceof T?U.code:"INTERNAL_ERROR"})}}}export{J1 as toExpress};
1
+ import{getResponseException as E,isBinaryBody as y,isRouteNotFound as g,normalizeResponse as b,SchmockError as v,serializeResponseBody as k,toHttpMethod as M}from"@schmock/core";var R=Symbol.for("@schmock/core.request-admission");function q(G){return typeof G==="object"&&G!==null&&"handle"in G&&typeof G.handle==="function"&&"release"in G&&typeof G.release==="function"}function p(G){let K=Reflect.get(G,R);if(typeof K!=="function")return;let L=Reflect.apply(K,G,[]);if(!q(L))throw Error("Schmock returned an invalid request admission");return L}function h(G){let K={};for(let[L,V]of Object.entries(G??{})){if(L.toLowerCase()==="content-type")continue;K[L]=V}return K["content-type"]="application/json",K}function T(G){if("reason"in G&&G.reason!==void 0)return G.reason;let K=Error("Request aborted");return K.name="AbortError",K}function P(G,K){if(K.aborted)return Promise.reject(T(K));return new Promise((L,V)=>{let Z=!1,J=($)=>{if(Z)return;Z=!0,K.removeEventListener("abort",U),$()},U=()=>J(()=>V(T(K)));K.addEventListener("abort",U,{once:!0}),Promise.resolve(G).then(($)=>J(()=>L($)),($)=>J(()=>V($)))})}function w(G,K,L){let V={...G.headers};if(!Object.keys(V).some(($)=>$.toLowerCase()==="content-type")&&G.body!==null&&G.body!==void 0){if(y(G.body))V["content-type"]="application/octet-stream";else if(typeof G.body!=="string")V["content-type"]="application/json"}let J=b({...G,headers:V},K);L.status(J.status);for(let[$,Y]of Object.entries(J.headers))L.set($,Y);let U=k(J);L.end(U===void 0?void 0:Buffer.from(U))}function D(G,K,L,V,Z,J={}){try{let U=G(K,L);try{w({status:500,body:U,headers:h(J)},V,Z)}catch{w({status:500,body:U,headers:{"content-type":"application/json"}},V,Z)}}catch{if(!Z.headersSent)Z.status(500),Z.set("content-type","application/json");if(!Z.writableEnded)Z.end(Z.headersSent?void 0:Buffer.from(JSON.stringify({error:"Internal Server Error",code:"INTERNAL_ERROR"})))}}function u(G){return Object.fromEntries(Object.entries(G).map(([K,L])=>[K,Array.isArray(L)?L[0]:L]).filter((K)=>typeof K[1]==="string"))}function d(G){let K={};for(let[L,V]of Object.entries(G))if(typeof V==="string")K[L]=V;else if(Array.isArray(V))K[L]=V[0]?String(V[0]):"";else if(V!=null)K[L]=String(V);return K}function c(G,K={}){let{errorFormatter:L,passErrorsToNext:V=!0,transformHeaders:Z=u,transformQuery:J=d,beforeRequest:U,beforeResponse:$}=K;return async(Y,X,j)=>{let B=new AbortController,S=()=>B.abort(),H=()=>{if(!X.writableFinished)B.abort()},A=typeof Y.once==="function",F=typeof X.once==="function";if(A)Y.once("aborted",S);if(F)X.once("close",H);let N,Q="GET";try{N=p(G);let _=N?.handle??((I,f,x)=>G.handle(I,f,x));Q=Y.method.toUpperCase()==="HEAD"?"HEAD":"GET";let W;try{W=M(Y.method),Q=W}catch{return j()}let z={method:W,path:Y.path,headers:Z(Y.headers),body:Y.body,query:J(Y.query)};if(U){let I=await P(U(Y,X),B.signal);if(I)z={...z,...I,method:M(I.method||z.method)},Q=z.method}if(X.headersSent||X.writableEnded)return;let O=await P(_(z.method,z.path,{headers:z.headers,body:z.body,query:z.query,signal:B.signal}),B.signal),C=E(O);if(g(O)){j();return}if($){let I=await P($(O,Y,X),B.signal);if(I)O=I}if(X.headersSent||X.writableEnded)return;if(L&&C&&O.status===500){D(L,C,Y,z.method,X,O.headers);return}w(O,z.method,X)}catch(_){if(B.signal.aborted)return;if(X.headersSent){if(V)j(_);else if(!X.writableEnded)X.end();return}if(X.writableEnded)return;if(L){let W=_ instanceof Error?_:Error(String(_));D(L,W,Y,Q,X)}else if(V)j(_);else w({status:500,body:{error:_ instanceof Error?_.message:"Internal Server Error",code:_ instanceof v?_.code:"INTERNAL_ERROR"},headers:{"content-type":"application/json"}},Q,X)}finally{if(A)Y.off("aborted",S);if(F)X.off("close",H);N?.release()}}}export{c as toExpress};
package/package.json CHANGED
@@ -1,8 +1,17 @@
1
1
  {
2
2
  "name": "@schmock/express",
3
- "version": "2.2.3",
3
+ "version": "2.3.1",
4
4
  "description": "Express adapter for Schmock mock API generator",
5
5
  "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/khalic-lab/schmock.git",
9
+ "directory": "packages/express"
10
+ },
11
+ "homepage": "https://github.com/khalic-lab/schmock/tree/main/packages/express#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/khalic-lab/schmock/issues"
14
+ },
6
15
  "main": "./dist/index.js",
7
16
  "types": "./dist/index.d.ts",
8
17
  "exports": {
@@ -16,10 +25,11 @@
16
25
  "dist"
17
26
  ],
18
27
  "scripts": {
19
- "build": "bun build:lib && bun build:types",
20
- "build:lib": "bun build --minify --target node --outdir=dist src/index.ts",
28
+ "clean": "rm -rf dist && rm -f tsconfig.tsbuildinfo",
29
+ "build": "bun run clean && bun run build:lib && bun run build:types",
30
+ "build:lib": "bun build --minify --target node --format esm --outdir=dist src/index.ts --external @schmock/core --external express",
21
31
  "build:types": "tsc -p tsconfig.json",
22
- "test": "vitest",
32
+ "test": "vitest run",
23
33
  "test:watch": "vitest --watch",
24
34
  "test:bdd": "vitest run --config vitest.config.bdd.ts",
25
35
  "lint": "biome check src/",
@@ -36,7 +46,7 @@
36
46
  "vitest": "^4.1.7"
37
47
  },
38
48
  "peerDependencies": {
39
- "@schmock/core": "^2.2.3",
49
+ "@schmock/core": "^2.3.1",
40
50
  "express": "^4.18.0 || ^5.0.0"
41
51
  },
42
52
  "keywords": [