vite-plugin-mock-dev-server 2.0.5 → 2.0.7
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/helper.d.mts +125 -2
- package/dist/helper.mjs +3 -2
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +14 -801
- package/dist/server-BEkc6AaK.mjs +1 -0
- package/dist/{server-CvrNrvvb.d.mts → server-lwszq3fl.d.mts} +1 -1
- package/dist/server.d.mts +1 -2
- package/dist/server.mjs +1 -3
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs +1 -1
- package/package.json +8 -8
- package/dist/helper-ChmPhNrY.mjs +0 -176
- package/dist/index-u_3ZZqGO.d.mts +0 -126
- package/dist/server-BetGF1ME.mjs +0 -1005
- /package/dist/{types-DF6NPJx4.d.mts → types-C8ZwTU-4.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{hasOwn as e,isArray as t,isBoolean as n,isEmptyObject as r,isFunction as i,isPlainObject as a,random as o,sleep as s,sortBy as c,timestamp as l,toArray as u,uniq as d}from"@pengzhanbo/utils";import f from"node:path";import p from"ansis";import m from"picomatch";import{match as h,parse as g,pathToRegexp as _}from"path-to-regexp";import v from"node:os";import y from"debug";import{parse as b}from"node:querystring";import x from"co-body";import S from"formidable";import C from"node:http";import w from"node:crypto";import{Buffer as T}from"node:buffer";import E from"http-status";import*as D from"mime-types";import{WebSocketServer as O}from"ws";function k(e,t){let n=[],r=[`**/node_modules/**`,...u(t)];return u(e).forEach(e=>{e[0]===`!`?r.push(e.slice(1)):n.push(e)}),{pattern:n,ignore:r,isMatch:m(n,{ignore:r})}}function A(e,t){return e[0]===`^`&&new RegExp(e).test(t)||t.startsWith(e)}function j(e){return typeof e==`object`&&!!e&&typeof e.pipe==`function`}function M(e){return j(e)&&e.readable!==!1&&typeof e._read==`function`&&typeof e._readableState==`object`}const N={};async function P(t){if(e(N,t))return N[t];try{return import.meta.resolve?N[t]=!!import.meta.resolve(t):(await import(t),N[t]=!0),N[t]}catch{}return N[t]=!1,!1}function F(e,t){if(!t)return!0;for(let n in t)if(!ee(e[n],t[n]))return!1;return!0}function ee(e,n){if(t(e)&&t(n)){let t=new Set;return n.every(n=>e.some((e,r)=>{if(t.has(r))return!1;let i=ee(e,n);return i&&t.add(r),i}))}return a(e)&&a(n)?F(e,n):Object.is(e,n)}const I=new Map;function L(e,t){let n=I.get(e);return n||(n=_(e).regexp,I.set(e,n)),n.test(t)}const R={silent:0,error:1,warn:2,info:3,debug:4};function te(e,t=`info`){e=`[${e}]`;function r(r,i,a){if(a=n(a)?a?t:`error`:a,R[a]>=R[r]){let t=r===`info`||r===`debug`?`log`:r,n=r===`debug`?p.magenta.bold(e):r===`info`?p.cyan.bold(e):r===`warn`?p.yellow.bold(e):p.red.bold(e),a=`${p.dim(new Date().toLocaleTimeString())} ${n} ${i}`;console[t](a)}}return{debug(e,n=t){r(`debug`,e,n)},info(e,n=t){r(`info`,e,n)},warn(e,n=t){r(`warn`,e,n)},error(e,n=t){r(`error`,e,n)}}}const ne=y(`vite:mock-dev-server`),re=/\\/g,ie=v.platform()===`win32`;function ae(e){return e.replace(re,`/`)}function oe(e){return f.posix.normalize(ie?ae(e):e)}function z(e){let t=new URL(e,`http://example.com`);return{pathname:decodeURIComponent(t.pathname),query:b(t.search.replace(/^\?/,``))}}function se(e,n){let r;return t(e)?r=e.map(e=>({...e,__filepath__:n})):`url`in e?r={...e,__filepath__:n}:(r=[],Object.keys(e).forEach(i=>{let a=e[i];t(a)?r.push(...a.map(e=>({...e,__filepath__:n}))):r.push({...a,__filepath__:n})})),r}function ce(e){let t=[];for(let[,n]of e.entries())n&&t.push(...u(n));let n={};return t.filter(e=>a(e)&&e.enabled!==!1&&e.url).forEach(e=>{let{pathname:t,query:a}=z(e.url),o=n[t]??=[],s={...e,url:t};if(s.ws!==!0){let e=s.validator;r(a)||(i(e)?s.validator=function(t){return F(t.query,a)&&e(t)}:e?(s.validator={...e},s.validator.query=s.validator.query?{...a,...s.validator.query}:a):s.validator={query:a})}o.push(s)}),Object.keys(n).forEach(e=>{n[e]=B(n[e])}),n}function B(e){return c(e,e=>{if(e.ws===!0)return 0;let{validator:t}=e;return!t||r(t)?2:i(t)?0:1/Object.keys(t).reduce((e,n)=>e+le(t[n]),0)})}function le(e){return e?Object.keys(e).length:0}async function ue(e,t,n={}){let r=e.method.toUpperCase();if([`HEAD`,`OPTIONS`].includes(r))return;let i=e.headers[`content-type`]?.toLocaleLowerCase()||``,{limit:a,formLimit:o,jsonLimit:s,textLimit:c,...l}=n;try{if(i.startsWith(`application/json`))return await x.json(e,{limit:s||a,...l});if(i.startsWith(`application/x-www-form-urlencoded`))return await x.form(e,{limit:o||a,...l});if(i.startsWith(`text/plain`))return await x.text(e,{limit:c||a,...l});if(i.startsWith(`multipart/form-data`))return await fe(e,t)}catch(e){console.error(e)}}const de={keepExtensions:!0,filename(e,t,n){return n?.originalFilename||`${e}.${Date.now()}${t?`.${t}`:``}`}};async function fe(e,t){let n=S({...de,...t});return new Promise((t,r)=>{n.parse(e,(e,n,i)=>{if(e){r(e);return}t({...n,...i})})})}const V=new Map;function H(e,t){let n=V.get(e);n||(n=h(e,{decode:decodeURIComponent}),V.set(e,n));let r=n(t);return r?r.params:{}}function pe(e,t){return F(e.headers,t.headers)&&F(e.body,t.body)&&F(e.params,t.params)&&F(e.query,t.query)&&F(e.refererQuery,t.refererQuery)}function U(e,t){return!t||r(t)?``:` ${p.gray(`${e}:`)}${JSON.stringify(t)}`}function me(e,t){let{url:n,method:r,query:i,params:a,body:o}=e,{pathname:s}=new URL(n,`http://example.com`);s=p.green(decodeURIComponent(s));let c=p.magenta.bold(r),l=U(`query`,i),u=U(`params`,a),d=U(`body`,o),f=` ${p.dim.underline(`(${t})`)}`;return`${c} ${s}${l}${u}${d}${f}`}function he(e,n,{pathname:r,method:a,request:o}){return e.find(e=>{if(!r||!e||!e.url||e.ws||!(e.method?t(e.method)?e.method:[e.method]:[`GET`,`POST`]).includes(a))return!1;let s=L(e.url,r);if(s&&e.validator){let t=H(e.url,r);if(i(e.validator))return e.validator({params:t,...o});try{return pe({params:t,...o},e.validator)}catch(t){let i=e.__filepath__;return n.error(`${p.red(`mock error at ${r}`)}\n${t}\n at validator (${p.underline(i)})`,e.log),!1}}return s})}const W=/^[\t\u0020-\u007E\u0080-\u00FF]+$/,ge=/^(?:low|medium|high)$/i,G=Object.create(null),_e=/[\^$\\.*+?()[\]{}|]/g,ve=/[;=]/,ye=/;/,be=/^(?:lax|none|strict)$/i;var xe=class{name;value;maxAge;expires;path=`/`;domain;secure=!1;httpOnly=!0;sameSite=!1;overwrite=!1;priority;partitioned;constructor(e,t,n={}){if(!W.test(e)||ve.test(e))throw TypeError(`argument name is invalid`);if(t&&(!W.test(t)||ye.test(t)))throw TypeError(`argument value is invalid`);if(this.name=e,this.value=t,Object.assign(this,n),this.value||(this.expires=new Date(0),this.maxAge=void 0),this.path&&!W.test(this.path))throw TypeError(`[Cookie] option path is invalid`);if(this.domain&&!W.test(this.domain))throw TypeError(`[Cookie] option domain is invalid`);if(typeof this.maxAge==`number`?Number.isNaN(this.maxAge)||!Number.isFinite(this.maxAge):this.maxAge)throw TypeError(`[Cookie] option maxAge is invalid`);if(this.priority&&!ge.test(this.priority))throw TypeError(`[Cookie] option priority is invalid`);if(this.sameSite&&this.sameSite!==!0&&!be.test(this.sameSite))throw TypeError(`[Cookie] option sameSite is invalid`)}toString(){return`${this.name}=${this.value}`}toHeader(){let e=this.toString();return this.maxAge&&(this.expires=new Date(Date.now()+this.maxAge)),this.path&&(e+=`; path=${this.path}`),this.expires&&(e+=`; expires=${this.expires.toUTCString()}`),this.domain&&(e+=`; domain=${this.domain}`),this.priority&&(e+=`; priority=${this.priority.toLowerCase()}`),this.sameSite&&(e+=`; samesite=${this.sameSite===!0?`strict`:this.sameSite.toLowerCase()}`),this.secure&&(e+=`; secure`),this.httpOnly&&(e+=`; httponly`),this.partitioned&&(e+=`; partitioned`),e}};function Se(e,t){if(e.length!==t.length)return!1;if(w.timingSafeEqual)return w.timingSafeEqual(e,t);for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function K(e,t){return w.createHmac(`sha256`,e).update(t).digest()}function Ce(e,t){let n=String(e),r=String(t),i=w.randomBytes(32);return Se(K(i,n),K(i,r))&&e===t}const we=/[/+=]/g,Te={"/":`_`,"+":`-`,"=":``};var q=class{algorithm;encoding;keys=[];constructor(e,t,n){this.keys=e,this.algorithm=t||`sha256`,this.encoding=n||`base64`}sign(e,t=this.keys[0]){return w.createHmac(this.algorithm,t).update(e).digest(this.encoding).replace(we,e=>Te[e])}index(e,t){for(let n=0,r=this.keys.length;n<r;n++)if(Ce(t,this.sign(e,this.keys[n])))return n;return-1}verify(e,t){return this.index(e,t)>-1}},J=class{request;response;secure;keys;constructor(e,n,r={}){this.request=e,this.response=n,this.secure=r.secure,r.keys instanceof q?this.keys=r.keys:t(r.keys)&&(this.keys=new q(r.keys))}set(e,t,n){let r=this.request,i=this.response,a=u(i.getHeader(`Set-Cookie`)),o=new xe(e,t,n),s=n?.signed??!!this.keys,c=this.secure===void 0?r.protocol===`https`||De(r):!!this.secure;if(!c&&n?.secure)throw Error(`Cannot send secure cookie over unencrypted connection`);if(o.secure=n?.secure??c,Y(a,o),s&&n){if(!this.keys)throw Error(`.keys required for signed cookies`);o.value=this.keys.sign(o.toString()),o.name+=`.sig`,Y(a,o)}return(i.set?C.OutgoingMessage.prototype.setHeader:i.setHeader).call(i,`Set-Cookie`,a),this}get(e,t){let n=`${e}.sig`,r=t?.signed??!!this.keys,i=this.request.headers.cookie;if(!i)return;let a=i.match(Ee(e));if(!a)return;let o=a[1];if(o[0]===`"`&&(o=o.slice(1,-1)),!t||!r)return o;let s=this.get(n);if(!s)return;let c=`${e}=${o}`;if(!this.keys)throw Error(`.keys required for signed cookies`);let l=this.keys.index(c,s);if(l<0)this.set(n,null,{path:`/`,signed:!1});else return l&&this.set(n,this.keys.sign(c),{signed:!1}),o}};function Ee(e){return G[e]||(G[e]=RegExp(`(?:^|;) *${e.replace(_e,`\\$&`)}=([^;]*)`)),G[e]}function De(e){return!!(e.socket?e.socket.encrypted:e.connection.encrypted)}function Y(e,t){if(t.overwrite)for(let n=e.length-1;n>=0;n--)e[n].indexOf(`${t.name}=`)===0&&e.splice(n,1);e.push(t.toHeader())}const X={};function Z(e){if(X[e])return X[e];let t=[],n=(e,r=!1)=>{for(let i of e)if(i.type===`text`){let e=i.value.split(`/`).filter(Boolean);e.length&&t.push(...e.map(e=>({type:`text`,value:e})))}else i.type===`group`?n(i.tokens,!0):(r&&(i.optional=!0),t.push(i))};return n(g(e).tokens),X[e]=t,t}function Oe(e){let t=e.map(e=>Z(e).length);return t=t.length===0?[1]:t,Math.max(...t)+2}function ke(e){let t=Z(e),n=0;for(let e=0;e<t.length;e++)t[e].type!==`text`&&(n+=10**(e+1)),n+=10**(e+1);return n}function Ae(e){let t=[],n=[];for(let t of e){let e=Z(t).filter(e=>e.type!==`text`).length;n[e]||(n[e]=[]),n[e].push(t)}for(let e of n.filter(e=>e&&e.length>0))t=[...t,...c(e,ke).reverse()];return t}function je(e){let t=Oe(e);return c(e,e=>{let n=Z(e),r=n.filter(e=>e.type!==`text`);if(r.length===0)return 0;let i=r.length,a=0;for(let e=0;e<n.length;e++){let r=n[e],o=r.type!==`text`,s=r.type===`wildcard`,c=!!r.optional;a+=o?1:0,e===n.length-1&&s?i+=(c?5:4)*10**(n.length===1?t+1:t):(s?i+=3*10**(t-1):i+=2*10**a,c&&(i+=10**a))}return i})}function Me(e,n,i){let a=je(Ae(e.filter(e=>L(e,n)))),{global:o=[],special:s={}}=i;if(o.length===0&&r(s)||a.length===0)return a;let[c,l]=Ne(a),u=o.filter(e=>l.includes(e));if(u.length>0&&(a=d([...c,...u,...l])),r(s))return a;let f=Object.keys(s).filter(e=>a.includes(e))[0];if(!f)return a;let p=s[f],{rules:m,when:h}=t(p)?{rules:p,when:[]}:p;return m.includes(a[0])&&(h.length===0||h.some(e=>_(e).regexp.test(n)))&&(a=d([f,...a])),a}function Ne(e){let t=[],n=[];for(let r of e)Z(r).filter(e=>e.type!==`text`).length>0?n.push(r):t.push(r);return[t,n]}const Q=new WeakMap;function Pe(e){let t=[];e.addListener(`data`,e=>{t.push(T.from(e))}),e.addListener(`end`,()=>{t.length&&Q.set(e,T.concat(t))})}function Fe(e){if(!e.server)return;let t=e.server.proxy||{};Object.keys(t).forEach(e=>{let n=t[e],r=typeof n==`string`?{target:n}:n;if(r.ws)return;let{configure:i,...a}=r;t[e]={...a,configure(e,t){i?.(e,t),e.on(`proxyReq`,(e,t)=>{let n=Q.get(t);n&&(Q.delete(t),e.headersSent||e.setHeader(`Content-Length`,n.byteLength),e.writableEnded||e.write(n))})}}})}function Ie(e){return E[e]||`Unknown`}function $(e,t=200,n){e.statusCode=t,e.statusMessage=n||Ie(t)}async function Le(e,t,n,r){let{headers:a,type:o=`json`}=n,s=n.__filepath__,c=D.contentType(o)||D.contentType(D.lookup(o)||``);if(c&&t.setHeader(`Content-Type`,c),t.setHeader(`Cache-Control`,`no-cache,max-age=0`),t.setHeader(`X-Mock-Power-By`,`vite-plugin-mock-dev-server`),s&&t.setHeader(`X-File-Path`,s),a)try{let n=i(a)?await a(e):a;Object.keys(n).forEach(e=>{t.setHeader(e,n[e])})}catch(t){r.error(`${p.red(`mock error at ${e.url.split(`?`)[0]}`)}\n${t}\n at headers (${p.underline(s)})`,n.log)}}async function Re(e,n,r,a){let{cookies:o}=r,s=r.__filepath__;if(o)try{let r=i(o)?await o(e):o;Object.keys(r).forEach(e=>{let i=r[e];if(t(i)){let[t,r]=i;n.setCookie(e,t,r)}else n.setCookie(e,i)})}catch(t){a.error(`${p.red(`mock error at ${e.url.split(`?`)[0]}`)}\n${t}\n at cookies (${p.underline(s)})`,r.log)}}function ze(e,t,n){if(M(t))t.pipe(e);else if(T.isBuffer(t))e.end(n===`text`||n===`json`?t.toString(`utf-8`):t);else{let r=typeof t==`string`?t:JSON.stringify(t);e.end(n===`buffer`?T.from(r):r)}}async function Be(e,n){if(!n||typeof n==`number`&&n<=0||t(n)&&n.length!==2)return;let r=0;if(t(n)){let[e,t]=n;r=o(e,t)}else r=n-(l()-e);r>0&&await s(r)}function Ve(e,{formidableOptions:t={},bodyParserOptions:n={},proxies:r,cookiesOptions:a,logger:o,priority:s={}}){return async function(c,u,d){let f=l(),{query:m,pathname:h}=z(c.url);if(!h||r.length===0||!r.some(e=>A(e,c.url)))return d();let g=e.mockData,_=Me(Object.keys(g),h,s);if(_.length===0)return d();Pe(c);let{query:v}=z(c.headers.referer||``),y=await ue(c,t,n),b=new J(c,u,a),x=b.get.bind(b),S=c.method.toUpperCase(),C,w;for(let e of _)if(C=he(g[e],o,{pathname:h,method:S,request:{query:m,refererQuery:v,body:y,headers:c.headers,getCookie:x}}),C){w=e;break}if(!C){let e=_.map(e=>e===w?p.underline.bold(e):p.dim(e)).join(`, `);return o.warn(`${p.green(h)} matches ${e} , but mock data is not found.`),d()}let T=c,E=u;T.body=y,T.query=m,T.refererQuery=v,T.params=H(C.url,h),T.getCookie=x,E.setCookie=b.set.bind(b);let{body:D,delay:O,type:k=`json`,response:j,status:M=200,statusText:N,log:P,__filepath__:F}=C;if($(E,M,N),await Le(T,E,C,o),await Re(T,E,C,o),o.info(me(T,F),P),o.debug(`${p.magenta(`DEBUG`)} ${p.underline(h)} matches: [ ${_.map(e=>e===w?p.underline.bold(e):p.dim(e)).join(`, `)} ]\n`),D){try{let e=i(D)?await D(T):D;await Be(f,O),ze(E,e,k)}catch(e){o.error(`${p.red(`mock error at ${h}`)}\n${e}\n at body (${p.underline(F)})`,P),$(E,500),u.end(``)}return}if(j){try{await Be(f,O),await j(T,E,d)}catch(e){o.error(`${p.red(`mock error at ${h}`)}\n${e}\n at response (${p.underline(F)})`,P),$(E,500),u.end(``)}return}u.end(``)}}function He(e,t,{wsProxies:n,cookiesOptions:r,logger:i}){let a=new Map,o=new Map,s=new WeakMap,c=e=>{let t=o.get(e);return t||o.set(e,t=new Map),t},l=(e,t)=>{let n=e.get(t);return n||e.set(t,n=new O({noServer:!0})),n},u=(e,t)=>{let n=a.get(e);n||a.set(e,n=new Set),n.add(t)},d=(e,t,n,r,a,o)=>{try{n.setup?.(t,r),t.on(`close`,()=>e.delete(a)),t.on(`error`,e=>{i.error(`${p.red(`WebSocket mock error at ${t.path}`)}\n${e}\n at setup (${o})`,n.log)})}catch(e){i.error(`${p.red(`WebSocket mock error at ${t.path}`)}\n${e}\n at setup (${o})`,n.log)}},f=(e,t,n,r)=>{e.emit(`connection`,t,n),t.on(`close`,()=>{let e=r.findIndex(e=>e.ws===t);e!==-1&&r.splice(e,1)})},m=(e,t,n,r,i)=>{let{cleanupList:a,connectionList:o,context:c}=s.get(t);Ue(a),o.forEach(({ws:e})=>e.removeAllListeners()),t.removeAllListeners(),d(e,t,n,c,r,i),o.forEach(({ws:e,req:n})=>f(t,e,n,o))};e.on?.(`mock:update-end`,t=>{if(!a.has(t))return;let n=a.get(t);if(n)for(let r of n.values())for(let n of e.mockData[r]){if(!n.ws||n.__filepath__!==t)return;let e=c(r);for(let[r,i]of e.entries())m(e,i,n,r,t)}}),t?.on(`upgrade`,(t,a,o)=>{let{pathname:m,query:h}=z(t.url);if(!m||n.length===0||!n.some(e=>A(e,t.url)))return;let g=e.mockData,_=Object.keys(g).find(e=>L(e,m));if(!_)return;let v=g[_].find(e=>e.url&&e.ws&&L(e.url,m));if(!v)return;let y=v.__filepath__;u(y,_);let b=c(_),x=l(b,m),S=s.get(x);if(!S){let e=[],t={onCleanup:t=>e.push(t)};S={cleanupList:e,context:t,connectionList:[]},s.set(x,S),d(b,x,v,t,m,y)}let C=t,w=new J(t,t,r),{query:T}=z(t.headers.referer||``);C.query=h,C.refererQuery=T,C.params=H(_,m),C.getCookie=w.get.bind(w),x.handleUpgrade(C,a,o,e=>{i.info(`${p.magenta.bold(`WebSocket`)} ${p.green(t.url)} connected ${p.dim(`(${y})`)}`,v.log),S.connectionList.push({req:C,ws:e}),f(x,e,C,S.connectionList)})}),t?.on(`close`,()=>{for(let e of o.values()){for(let t of e.values())Ue(s.get(t).cleanupList),t.close();e.clear()}o.clear(),a.clear()})}function Ue(e){let t;for(;t=e.shift();)t?.()}export{se as a,ne as c,R as d,L as f,k as h,ce as i,oe as l,A as m,Ve as n,B as o,P as p,Fe as r,z as s,He as t,te as u};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { g as ServerBuildOption, i as LogLevel, m as MockWebsocketItem, p as MockServerPluginOptions, s as MockHttpItem, u as MockOptions } from "./types-
|
|
1
|
+
import { g as ServerBuildOption, i as LogLevel, m as MockWebsocketItem, p as MockServerPluginOptions, s as MockHttpItem, u as MockOptions } from "./types-C8ZwTU-4.mjs";
|
|
2
2
|
import { Matcher } from "picomatch";
|
|
3
3
|
import Debug from "debug";
|
|
4
4
|
import EventEmitter from "node:events";
|
package/dist/server.d.mts
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import "./
|
|
2
|
-
import { a as createLogger, c as processRawData, i as Logger, l as sortByValidator, n as CreateMockMiddlewareOptions, o as logLevels, r as createMockMiddleware, s as processMockData, t as mockWebSocket } from "./server-CvrNrvvb.mjs";
|
|
1
|
+
import { a as createLogger, c as processRawData, i as Logger, l as sortByValidator, n as CreateMockMiddlewareOptions, o as logLevels, r as createMockMiddleware, s as processMockData, t as mockWebSocket } from "./server-lwszq3fl.mjs";
|
|
3
2
|
export { CreateMockMiddlewareOptions, Logger, createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
|
package/dist/server.mjs
CHANGED
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
export { createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
|
|
1
|
+
import{a as e,d as t,i as n,n as r,o as i,t as a,u as o}from"./server-BEkc6AaK.mjs";export{o as createLogger,r as createMockMiddleware,t as logLevels,a as mockWebSocket,n as processMockData,e as processRawData,i as sortByValidator};
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-
|
|
1
|
+
import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-C8ZwTU-4.mjs";
|
|
2
2
|
export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext };
|
package/dist/types.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export{};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-mock-dev-server",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.7",
|
|
5
5
|
"author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"homepage": "https://vite-plugin-mock-dev-server.netlify.app",
|
|
@@ -44,12 +44,12 @@
|
|
|
44
44
|
"dist"
|
|
45
45
|
],
|
|
46
46
|
"engines": {
|
|
47
|
-
"node": "^
|
|
47
|
+
"node": "^20 || >=22"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
50
|
"esbuild": ">=0.21.0",
|
|
51
|
-
"rolldown": ">=1.0.0-beta.
|
|
52
|
-
"vite": ">=
|
|
51
|
+
"rolldown": ">=1.0.0-beta.1",
|
|
52
|
+
"vite": ">=5.0.0"
|
|
53
53
|
},
|
|
54
54
|
"peerDependenciesMeta": {
|
|
55
55
|
"esbuild": {
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"dependencies": {
|
|
63
63
|
"@pengzhanbo/utils": "^2.1.2",
|
|
64
64
|
"ansis": "^4.2.0",
|
|
65
|
-
"chokidar": "^
|
|
65
|
+
"chokidar": "^5.0.0",
|
|
66
66
|
"co-body": "^6.2.0",
|
|
67
67
|
"cors": "^2.8.5",
|
|
68
68
|
"debug": "^4.4.3",
|
|
@@ -78,9 +78,9 @@
|
|
|
78
78
|
"ws": "^8.18.3"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
|
-
"esbuild": "^0.27.
|
|
82
|
-
"rolldown": "^1.0.0-beta.
|
|
83
|
-
"vite": "
|
|
81
|
+
"esbuild": "^0.27.2",
|
|
82
|
+
"rolldown": "^1.0.0-beta.56",
|
|
83
|
+
"vite": "^8.0.0-beta.4"
|
|
84
84
|
},
|
|
85
85
|
"publishConfig": {
|
|
86
86
|
"access": "public",
|
package/dist/helper-ChmPhNrY.mjs
DELETED
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
import { deepClone, deepEqual, isArray, isFunction } from "@pengzhanbo/utils";
|
|
2
|
-
import { Transform } from "node:stream";
|
|
3
|
-
|
|
4
|
-
//#region src/helper/createSSEStream.ts
|
|
5
|
-
/**
|
|
6
|
-
* Transforms "messages" to W3C event stream content.
|
|
7
|
-
* See https://html.spec.whatwg.org/multipage/server-sent-events.html
|
|
8
|
-
* A message is an object with one or more of the following properties:
|
|
9
|
-
* - data (String or object, which gets turned into JSON)
|
|
10
|
-
* - event
|
|
11
|
-
* - id
|
|
12
|
-
* - retry
|
|
13
|
-
* - comment
|
|
14
|
-
*
|
|
15
|
-
* If constructed with a HTTP Request, it will optimise the socket for streaming.
|
|
16
|
-
* If this stream is piped to an HTTP Response, it will set appropriate headers.
|
|
17
|
-
*/
|
|
18
|
-
var SSEStream = class extends Transform {
|
|
19
|
-
constructor(req) {
|
|
20
|
-
super({ objectMode: true });
|
|
21
|
-
req.socket.setKeepAlive(true);
|
|
22
|
-
req.socket.setNoDelay(true);
|
|
23
|
-
req.socket.setTimeout(0);
|
|
24
|
-
}
|
|
25
|
-
pipe(destination, options) {
|
|
26
|
-
if (destination.writeHead) {
|
|
27
|
-
destination.writeHead(200, {
|
|
28
|
-
"Content-Type": "text/event-stream; charset=utf-8",
|
|
29
|
-
"Transfer-Encoding": "identity",
|
|
30
|
-
"Cache-Control": "no-cache",
|
|
31
|
-
"Connection": "keep-alive"
|
|
32
|
-
});
|
|
33
|
-
destination.flushHeaders?.();
|
|
34
|
-
}
|
|
35
|
-
destination.write(":ok\n\n");
|
|
36
|
-
return super.pipe(destination, options);
|
|
37
|
-
}
|
|
38
|
-
_transform(message, encoding, callback) {
|
|
39
|
-
if (message.comment) this.push(`: ${message.comment}\n`);
|
|
40
|
-
if (message.event) this.push(`event: ${message.event}\n`);
|
|
41
|
-
if (message.id) this.push(`id: ${message.id}\n`);
|
|
42
|
-
if (message.retry) this.push(`retry: ${message.retry}\n`);
|
|
43
|
-
if (message.data) this.push(dataString(message.data));
|
|
44
|
-
this.push("\n");
|
|
45
|
-
callback();
|
|
46
|
-
}
|
|
47
|
-
write(message, ...args) {
|
|
48
|
-
return super.write(message, ...args);
|
|
49
|
-
}
|
|
50
|
-
destroy(error) {
|
|
51
|
-
if (error) this.write({
|
|
52
|
-
event: "error",
|
|
53
|
-
data: error.message
|
|
54
|
-
});
|
|
55
|
-
this.end();
|
|
56
|
-
return this;
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
function dataString(data) {
|
|
60
|
-
if (typeof data === "object") return dataString(JSON.stringify(data));
|
|
61
|
-
return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}\n`).join("");
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* 创建一个 Server-sent events 写入流,用于支持模拟 EventSource
|
|
65
|
-
*
|
|
66
|
-
* @example
|
|
67
|
-
* ```ts
|
|
68
|
-
* import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
|
|
69
|
-
*
|
|
70
|
-
* export default defineMock({
|
|
71
|
-
* url: '/api',
|
|
72
|
-
* response: (req, res) => {
|
|
73
|
-
* const sse = createSSEStream(req, res)
|
|
74
|
-
* sse.write({ event: 'message', data: { message: 'hello world' } })
|
|
75
|
-
* }
|
|
76
|
-
* })
|
|
77
|
-
* ```
|
|
78
|
-
*/
|
|
79
|
-
function createSSEStream(req, res) {
|
|
80
|
-
const sse = new SSEStream(req);
|
|
81
|
-
sse.pipe(res);
|
|
82
|
-
return sse;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
//#endregion
|
|
86
|
-
//#region src/helper/defineMock.ts
|
|
87
|
-
function defineMock(config) {
|
|
88
|
-
return config;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Return a custom defineMock function to support preprocessing of mock config.
|
|
92
|
-
*
|
|
93
|
-
* 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
|
|
94
|
-
* @param transformer preprocessing function
|
|
95
|
-
* @example
|
|
96
|
-
* ```ts
|
|
97
|
-
* const definePostMock = createDefineMock((mock) => {
|
|
98
|
-
* mock.url = '/api/post/' + mock.url
|
|
99
|
-
* })
|
|
100
|
-
* export default definePostMock({
|
|
101
|
-
* url: 'list',
|
|
102
|
-
* body: [{ title: '1' }, { title: '2' }],
|
|
103
|
-
* })
|
|
104
|
-
* ```
|
|
105
|
-
*/
|
|
106
|
-
function createDefineMock(transformer) {
|
|
107
|
-
const define = (config) => {
|
|
108
|
-
if (isArray(config)) config = config.map((item) => transformer(item) || item);
|
|
109
|
-
else config = transformer(config) || config;
|
|
110
|
-
return config;
|
|
111
|
-
};
|
|
112
|
-
return define;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
//#endregion
|
|
116
|
-
//#region src/helper/defineMockData.ts
|
|
117
|
-
/**
|
|
118
|
-
* 由于插件是 分别独立对 `*.mock.*` 等文件作为单独入口进行编译的,
|
|
119
|
-
* 这导致了 mock 文件编译后的依赖关系不一致,每个 mock 文件拥有独立的作用域,
|
|
120
|
-
* 使得即使多个 `*.mock.*` 虽然引入了同一个 `data.ts` 文件,然而确是完全不同两份 `data`,
|
|
121
|
-
* 使得对 `data` 的操作,在不同的 `*.mock.*` 文件中并不能共享。
|
|
122
|
-
*
|
|
123
|
-
* 为此,插件提供了一种基于 memory 的数据共享机制。
|
|
124
|
-
*/
|
|
125
|
-
const mockDataCache = /* @__PURE__ */ new Map();
|
|
126
|
-
const responseCache = /* @__PURE__ */ new WeakMap();
|
|
127
|
-
const staleInterval = 70;
|
|
128
|
-
var CacheImpl = class {
|
|
129
|
-
value;
|
|
130
|
-
#initialValue;
|
|
131
|
-
#lastUpdate;
|
|
132
|
-
constructor(value) {
|
|
133
|
-
this.value = value;
|
|
134
|
-
this.#initialValue = deepClone(value);
|
|
135
|
-
this.#lastUpdate = Date.now();
|
|
136
|
-
}
|
|
137
|
-
hotUpdate(value) {
|
|
138
|
-
if (Date.now() - this.#lastUpdate < staleInterval) return;
|
|
139
|
-
if (!deepEqual(value, this.#initialValue)) {
|
|
140
|
-
this.value = value;
|
|
141
|
-
this.#initialValue = deepClone(value);
|
|
142
|
-
this.#lastUpdate = Date.now();
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
function defineMockData(key, initialData) {
|
|
147
|
-
let cache = mockDataCache.get(key);
|
|
148
|
-
if (!cache) {
|
|
149
|
-
const newCache = new CacheImpl(initialData);
|
|
150
|
-
const existing = mockDataCache.get(key);
|
|
151
|
-
if (existing) cache = existing;
|
|
152
|
-
else {
|
|
153
|
-
mockDataCache.set(key, newCache);
|
|
154
|
-
cache = newCache;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
cache.hotUpdate(initialData);
|
|
158
|
-
if (responseCache.has(cache)) return responseCache.get(cache);
|
|
159
|
-
const res = [() => cache.value, (val) => {
|
|
160
|
-
if (isFunction(val)) val = val(cache.value) ?? cache.value;
|
|
161
|
-
cache.value = val;
|
|
162
|
-
}];
|
|
163
|
-
Object.defineProperty(res, "value", {
|
|
164
|
-
get() {
|
|
165
|
-
return cache.value;
|
|
166
|
-
},
|
|
167
|
-
set(val) {
|
|
168
|
-
cache.value = val;
|
|
169
|
-
}
|
|
170
|
-
});
|
|
171
|
-
responseCache.set(cache, res);
|
|
172
|
-
return res;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
//#endregion
|
|
176
|
-
export { createSSEStream as i, createDefineMock as n, defineMock as r, defineMockData as t };
|
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
import { m as MockWebsocketItem, s as MockHttpItem, u as MockOptions } from "./types-DF6NPJx4.mjs";
|
|
2
|
-
import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
3
|
-
import { Transform } from "node:stream";
|
|
4
|
-
|
|
5
|
-
//#region src/helper/createSSEStream.d.ts
|
|
6
|
-
interface SSEMessage {
|
|
7
|
-
data?: string | object;
|
|
8
|
-
comment?: string;
|
|
9
|
-
event?: string;
|
|
10
|
-
id?: string;
|
|
11
|
-
retry?: number;
|
|
12
|
-
}
|
|
13
|
-
interface WriteHeaders {
|
|
14
|
-
writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
|
|
15
|
-
flushHeaders?: () => void;
|
|
16
|
-
}
|
|
17
|
-
type HeaderStream = NodeJS.WritableStream & WriteHeaders;
|
|
18
|
-
/**
|
|
19
|
-
* Transforms "messages" to W3C event stream content.
|
|
20
|
-
* See https://html.spec.whatwg.org/multipage/server-sent-events.html
|
|
21
|
-
* A message is an object with one or more of the following properties:
|
|
22
|
-
* - data (String or object, which gets turned into JSON)
|
|
23
|
-
* - event
|
|
24
|
-
* - id
|
|
25
|
-
* - retry
|
|
26
|
-
* - comment
|
|
27
|
-
*
|
|
28
|
-
* If constructed with a HTTP Request, it will optimise the socket for streaming.
|
|
29
|
-
* If this stream is piped to an HTTP Response, it will set appropriate headers.
|
|
30
|
-
*/
|
|
31
|
-
declare class SSEStream extends Transform {
|
|
32
|
-
constructor(req: IncomingMessage);
|
|
33
|
-
pipe<T extends HeaderStream>(destination: T, options?: {
|
|
34
|
-
end?: boolean;
|
|
35
|
-
}): T;
|
|
36
|
-
_transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
|
|
37
|
-
write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
|
|
38
|
-
write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
|
|
39
|
-
destroy(error?: Error): this;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* 创建一个 Server-sent events 写入流,用于支持模拟 EventSource
|
|
43
|
-
*
|
|
44
|
-
* @example
|
|
45
|
-
* ```ts
|
|
46
|
-
* import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
|
|
47
|
-
*
|
|
48
|
-
* export default defineMock({
|
|
49
|
-
* url: '/api',
|
|
50
|
-
* response: (req, res) => {
|
|
51
|
-
* const sse = createSSEStream(req, res)
|
|
52
|
-
* sse.write({ event: 'message', data: { message: 'hello world' } })
|
|
53
|
-
* }
|
|
54
|
-
* })
|
|
55
|
-
* ```
|
|
56
|
-
*/
|
|
57
|
-
declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
|
|
58
|
-
//#endregion
|
|
59
|
-
//#region src/helper/defineMock.d.ts
|
|
60
|
-
/**
|
|
61
|
-
* mock config Type helper
|
|
62
|
-
*
|
|
63
|
-
* mock配置 类型帮助函数
|
|
64
|
-
* @param config see config docs:
|
|
65
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config en-US DOC} |
|
|
66
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/zh/guide/mock-config zh-CN DOC}
|
|
67
|
-
*
|
|
68
|
-
* @example
|
|
69
|
-
* Mock Http Request
|
|
70
|
-
* ```ts
|
|
71
|
-
* export default defineMock({
|
|
72
|
-
* url: '/api/example',
|
|
73
|
-
* method: ['GET', 'POST'],
|
|
74
|
-
* body: { a: 1 },
|
|
75
|
-
* })
|
|
76
|
-
* ```
|
|
77
|
-
* ```ts
|
|
78
|
-
* export default defineMock({
|
|
79
|
-
* url: '/api/example',
|
|
80
|
-
* method: 'GET',
|
|
81
|
-
* body: ({ query }) => ({ a: 1, b: query.b }),
|
|
82
|
-
* })
|
|
83
|
-
* ```
|
|
84
|
-
* @example
|
|
85
|
-
* Mock WebSocket
|
|
86
|
-
* ```ts
|
|
87
|
-
* export default defineMock({
|
|
88
|
-
* url: '/socket.io',
|
|
89
|
-
* ws: true,
|
|
90
|
-
* setup(wss) {
|
|
91
|
-
* wss.on('connection', (ws) => {
|
|
92
|
-
* ws.on('message', (rawData) => console.log(rawData))
|
|
93
|
-
* ws.send('data')
|
|
94
|
-
* })
|
|
95
|
-
* },
|
|
96
|
-
* })
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
declare function defineMock(config: MockHttpItem): MockHttpItem;
|
|
100
|
-
declare function defineMock(config: MockWebsocketItem): MockWebsocketItem;
|
|
101
|
-
declare function defineMock(config: MockOptions): MockOptions;
|
|
102
|
-
/**
|
|
103
|
-
* Return a custom defineMock function to support preprocessing of mock config.
|
|
104
|
-
*
|
|
105
|
-
* 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
|
|
106
|
-
* @param transformer preprocessing function
|
|
107
|
-
* @example
|
|
108
|
-
* ```ts
|
|
109
|
-
* const definePostMock = createDefineMock((mock) => {
|
|
110
|
-
* mock.url = '/api/post/' + mock.url
|
|
111
|
-
* })
|
|
112
|
-
* export default definePostMock({
|
|
113
|
-
* url: 'list',
|
|
114
|
-
* body: [{ title: '1' }, { title: '2' }],
|
|
115
|
-
* })
|
|
116
|
-
* ```
|
|
117
|
-
*/
|
|
118
|
-
declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;
|
|
119
|
-
//#endregion
|
|
120
|
-
//#region src/helper/defineMockData.d.ts
|
|
121
|
-
type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) => void] & {
|
|
122
|
-
value: T;
|
|
123
|
-
};
|
|
124
|
-
declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
|
|
125
|
-
//#endregion
|
|
126
|
-
export { HeaderStream as a, defineMock as i, defineMockData as n, SSEMessage as o, createDefineMock as r, createSSEStream as s, MockData as t };
|