Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vite-plugin-mock-dev-server

Package Overview
Dependencies
Maintainers
1
Versions
84
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vite-plugin-mock-dev-server - npm Package Compare versions

Comparing version 1.1.11 to 1.1.12

33

dist/index.d.ts

@@ -413,8 +413,8 @@ import { Connect, Plugin, ResolvedConfig } from 'vite';

/**
* mock config helper
* mock config Type helper
*
* mock配置辅助函数
*
* mock配置 类型帮助函数
* @param config
* @example
* Mock Http Request
* ```ts

@@ -427,2 +427,16 @@ * export default defineMock({

* ```
* @example
* Mock WebSocket
* ```ts
* export default defineMock({
* url: '/socket.io',
* ws: true,
* setup(wss) {
* wss.on('connection', (ws) => {
* ws.on('message', (rawData) => console.log(rawData))
* ws.send('data')
* })
* },
* })
* ```
*/

@@ -433,7 +447,16 @@ declare function defineMock(config: MockHttpItem): MockHttpItem;

/**
* 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
*
* Return a custom defineMock function to support preprocessing of mock config.
*
* 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
* @param transformer preprocessing function
* @example
* ```ts
* const definePostMock = createDefineMock((mock) => {
* mock.url = '/api/post/' + mock.url
* })
* export default definePostMock({
* url: 'list',
* body: [{ title: '1' }, { title: '2' }],
* })
* ```
*/

@@ -440,0 +463,0 @@ declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;

24

dist/index.js

@@ -1,4 +0,4 @@

import Ae from"fs";import Y from"fs/promises";import T from"path";import{build as Ne}from"esbuild";import Ue from"fast-glob";import qe from"is-core-module";import{createFilter as Be,normalizePath as Je}from"vite";var ie="vite-plugin-mock-dev-server",ce="1.1.11";import ae from"fs/promises";import Ee from"path";import Ie from"json5";var B={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Ee.isAbsolute(o))return{external:!0}})}},J={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await ae.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Ie.parse(e))}`,loader:"js"}})}},z={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await ae.readFile(o,"utf-8")}`,loader:"js"}))}},G=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>Le(c,e));if(!r)return null;let{find:n,replacement:s}=r;return{path:(await o.resolve(e.replace(n,s),{kind:"import-statement",resolveDir:s,namespace:"file"})).path,external:!1}})}});function Le(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}import V from"fs";import Z from"path";import{fileURLToPath as _e}from"url";import $e from"debug";import{match as Fe}from"path-to-regexp";import pe from"picocolors";var w=t=>Array.isArray(t),P=t=>typeof t=="function",Te=t=>Object.prototype.toString.call(t)==="[object Object]",le=t=>Te(t)&&Object.keys(t).length===0,He=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",ue=t=>He(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function me(t){return new Promise(o=>setTimeout(o,t))}function de(t){return Z.dirname(_e(t))}var j=$e("vite:plugin-mock-dev-server"),O=t=>w(t)?t:t==null?[]:[t],R={info(...t){console.info(pe.cyan("mock-dev-server: "),...t)},error(...t){console.error(`
`,pe.cyan("mock-dev-server: "),...t,`
`)}};function A(t,o,e){for(let n of o){let s=Z.join(t,n);if(V.existsSync(s)&&V.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:V.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=Z.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return A(r,o,e)}var Q=(t={})=>{let o=[],e=[];return Object.keys(t).forEach(r=>{var s,i;let n=t[r];typeof n=="string"||!n.ws&&!((s=n.target)!=null&&s.toString().startsWith("ws:"))&&!((i=n.target)!=null&&i.toString().startsWith("wss:"))?o.push(r):e.push(r)}),{httpProxies:o,wsProxies:e}};function X(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function N(t,o){return(Fe(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}async function fe(t,o,e){let r=O(e.include),n=O(e.exclude),s={};if(o.define)for(let p in o.define){let m=o.define[p];s[p]=typeof m=="string"?m:JSON.stringify(m)}let{httpProxies:i}=Q(o.server.proxy||{});i.push(...O(e.prefix));let c=O(e.wsPrefix),u={};try{let p=A(o.root,["package.json"]);p&&(u=JSON.parse(p))}catch{}let d=e.build.dist,v=await Xe(process.cwd(),r,n),h=T.join(o.root,`mock-data-${Date.now()}.js`);await Y.writeFile(h,v,"utf-8");let{code:F,deps:D}=await Ye(h,s,o.resolve.alias),a=ze(D);await Y.unlink(h);let l=[{filename:T.join(d,"mock-data.js"),source:F},{filename:T.join(d,"index.js"),source:Qe(i,c,e.cookiesOptions,e.build.serverPort)},{filename:T.join(d,"package.json"),source:Ge(u,a)}];try{if(T.isAbsolute(d)){await Y.rm(d,{recursive:!0}),Ae.mkdirSync(d,{recursive:!0});for(let{filename:p,source:m}of l)await Y.writeFile(p,m,"utf-8")}else for(let{filename:p,source:m}of l)t.emitFile({type:"asset",fileName:p,source:m})}catch{}}function ze(t){let o=new Set,e=[ie,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external).map(s=>s.path).forEach(s=>{!e.includes(s)&&!qe(s)&&o.add(s)})}),Array.from(o)}function Ge(t,o){let{dependencies:e={},devDependencies:r={}}=t,n={...e,...r},s={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ce}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Qe(t,o,e={},r=8080){return`import { createServer } from 'node:http';
import Ue from"fs";import X from"fs/promises";import T from"path";import{build as qe}from"esbuild";import Be from"fast-glob";import Je from"is-core-module";import{createFilter as ze,normalizePath as Ge}from"vite";var ae="vite-plugin-mock-dev-server",pe="1.1.12";var Ee=/import\.meta\.env\.(.+)/;function B(t){let o={},e=process.env.NODE_ENV||t.mode;Object.assign(o,{"process.env.NODE_ENV":JSON.stringify(e),"global.process.env.NODE_ENV":JSON.stringify(e),"globalThis.process.env.NODE_ENV":JSON.stringify(e),__vite_process_env_NODE_ENV:JSON.stringify(e)});let r={},n={};for(let c in t.define){let a=t.define[c];r[c]=typeof a=="string"?a:JSON.stringify(a);let m=c.match(Ee);m&&(n[m[1]]=`__vite__define__${r[c]}`)}let s={},i={};s["import.meta.hot"]="undefined";for(let c in t.env)s[`import.meta.env.${c}`]=JSON.stringify(t.env[c]);return Object.assign(i,{"import.meta.env":JSON.stringify({...t.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(c,a,m)=>`${a.replace(/(^\\")|(\\"$)/g,'"')}${m}`)}),{...s,...i,...o}}import le from"fs/promises";import Ie from"path";import Le from"json5";var J={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Ie.isAbsolute(o))return{external:!0}})}},z={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await le.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Le.parse(e))}`,loader:"js"}})}},G={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await le.readFile(o,"utf-8")}`,loader:"js"}))}},Q=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>$e(c,e));if(!r)return null;let{find:n,replacement:s}=r;return{path:(await o.resolve(e.replace(n,s),{kind:"import-statement",resolveDir:s,namespace:"file"})).path,external:!1}})}});function $e(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}import Z from"fs";import ee from"path";import{fileURLToPath as Fe}from"url";import Te from"debug";import{match as Ne}from"path-to-regexp";import ue from"picocolors";var S=t=>Array.isArray(t),j=t=>typeof t=="function",He=t=>Object.prototype.toString.call(t)==="[object Object]",te=t=>He(t)&&Object.keys(t).length===0,Ae=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",me=t=>Ae(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function de(t){return new Promise(o=>setTimeout(o,t))}function fe(t){return ee.dirname(Fe(t))}var C=Te("vite:plugin-mock-dev-server"),w=t=>S(t)?t:t==null?[]:[t],R={info(...t){console.info(ue.cyan("mock-dev-server: "),...t)},error(...t){console.error(`
`,ue.cyan("mock-dev-server: "),...t,`
`)}};function H(t,o,e){for(let n of o){let s=ee.join(t,n);if(Z.existsSync(s)&&Z.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:Z.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=ee.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return H(r,o,e)}var V=(t={})=>{let o=[],e=[];return Object.keys(t).forEach(r=>{var s,i;let n=t[r];typeof n=="string"||!n.ws&&!((s=n.target)!=null&&s.toString().startsWith("ws:"))&&!((i=n.target)!=null&&i.toString().startsWith("wss:"))?o.push(r):e.push(r)}),{httpProxies:o,wsProxies:e}};function K(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function A(t,o){return(Ne(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}async function ge(t,o,e){let r=w(e.include),n=w(e.exclude),s=B(o),{httpProxies:i}=V(o.server.proxy||{});i.push(...w(e.prefix));let c=w(e.wsPrefix),a={};try{let u=H(o.root,["package.json"]);u&&(a=JSON.parse(u))}catch{}let m=e.build.dist,x=await Xe(process.cwd(),r,n),v=T.join(o.root,`mock-data-${Date.now()}.js`);await X.writeFile(v,x,"utf-8");let{code:F,deps:D}=await Ye(v,s,o.resolve.alias),p=Qe(D);await X.unlink(v);let l=[{filename:T.join(m,"mock-data.js"),source:F},{filename:T.join(m,"index.js"),source:Ke(i,c,e.cookiesOptions,e.build.serverPort)},{filename:T.join(m,"package.json"),source:Ve(a,p)}];try{if(T.isAbsolute(m)){await X.rm(m,{recursive:!0}),Ue.mkdirSync(m,{recursive:!0});for(let{filename:u,source:d}of l)await X.writeFile(u,d,"utf-8")}else for(let{filename:u,source:d}of l)t.emitFile({type:"asset",fileName:u,source:d})}catch{}}function Qe(t){let o=new Set,e=[ae,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Je(s)&&o.add(s)})}),Array.from(o)}function Ve(t,o){let{dependencies:e={},devDependencies:r={}}=t,n={...e,...r},s={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${pe}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Ke(t,o,e={},r=8080){return`import { createServer } from 'node:http';
import connect from 'connect';

@@ -27,4 +27,4 @@ import corsMiddleware from 'cors';

console.log('listen: http://localhost:${r}');
`}async function Xe(t,o,e){let r=await Ue(o,{cwd:t}),n=Be(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((u,d)=>{let v=Je(T.join(t,u));i+=`import * as m${d} from '${v}';
`,c+=`m${d}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server';
`}async function Xe(t,o,e){let r=await Be(o,{cwd:t}),n=ze(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((a,m)=>{let x=Ge(T.join(t,a));i+=`import * as m${m} from '${x}';
`,c+=`m${m}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server';
${i}

@@ -46,8 +46,8 @@ const exporters = [${c}];

});
export default transformMockData(mockList);`}async function Ye(t,o,e){var r;try{let n=await Ne({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:o,plugins:[G(e),B,J,z]});return{code:n.outputFiles[0].text,deps:((r=n.metafile)==null?void 0:r.inputs)||{}}}catch(n){console.error(n)}return{code:"",deps:{}}}import{Buffer as ye}from"buffer";import{parse as he}from"url";import Ze from"cookies";import et from"http-status";import tt from"lodash.sortby";import*as U from"mime-types";import{pathToRegexp as Me}from"path-to-regexp";import W from"picocolors";import ee from"co-body";import Ke from"formidable";async function ke(t,o){var n;let e=t.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((n=t.headers["content-type"])==null?void 0:n.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await ee.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await ee.form(t);if(r.startsWith("text/plain"))return await ee.text(t);if(r.startsWith("multipart/form-data"))return await Ve(t,o)}catch(s){console.error(s)}}async function Ve(t,o){let e=Ke(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function ge(t,o){return _(t.headers,o.headers)&&_(t.body,o.body)&&_(t.params,o.params)&&_(t.query,o.query)&&_(t.refererQuery,o.refererQuery)}function _(t,o){if(!o)return!0;for(let e in o)if(o[e]!==t[e])return!1;return!0}var ot=/:/g;function be(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:u,pathname:d}=he(n.url,!0);if(!d||e.length===0||!e.some(y=>X(y,n.url)))return i();let v=t.mockData,h=tt(Object.keys(v),y=>{var H;return((H=y.match(ot))==null?void 0:H.length)||0}).find(y=>Me(y).test(d));if(!h)return i();let{query:F}=he(n.headers.referer||"",!0),D=await ke(n,o),a=new Ze(n,s,r),l=a.get.bind(a),p=n.method.toUpperCase(),m=rt(v[h],{pathname:d,method:p,request:{query:u,refererQuery:F,body:D,headers:n.headers,getCookie:l}});if(!m)return i();j("middleware: ",p,n.url);let f=n,k=s;f.body=D,f.query=u,f.refererQuery=F,f.params=N(m.url,d),f.getCookie=l,k.setCookie=a.set.bind(a);let{body:g,delay:S,type:C="json",response:E,status:I=200,statusText:L}=m;if(te(k,I,L),await nt(f,k,m),await st(f,k,m),g){try{let y=P(g)?await g(f):g;await ve(c,S),it(k,y,C)}catch(y){R.error(`${W.red("[body error]")} ${n.url}
`,`file: ${W.cyan(m.__filepath__)}`,y),te(k,500),s.end("")}return}if(E){try{await ve(c,S),await E(f,k,i)}catch(y){R.error(`${W.red("[response error]")} ${n.url}
`,`file: ${W.cyan(m.__filepath__)}`,y),te(k,500),s.end("")}return}s.end("")}}function rt(t,{pathname:o,method:e,request:r}){return t.find(n=>{if(!o||!n||!n.url||n.ws===!0||!(n.method?w(n.method)?n.method:[n.method]:["GET","POST"]).includes(e))return!1;let i=Me(n.url).test(o);if(i&&n.validator){let c=N(n.url,o);if(P(n.validator))return n.validator({params:c,...r});try{return ge({params:c,...r},n.validator)}catch(u){return R.error(`${W.red("[validator error]")} ${o}
`,`file: ${W.cyan(n.__filepath__)}`,u),!1}}return i})}function te(t,o=200,e){t.statusCode=o,t.statusMessage=e||ct(o)}async function nt(t,o,{headers:e,type:r="json"}){let n=U.contentType(r)||U.contentType(U.lookup(r)||"");if(n&&o.setHeader("Content-Type",n),o.setHeader("Cache-Control","no-cache,max-age=0"),o.setHeader("X-Mock","generate by vite:plugin-mock-dev-server"),!!e)try{let s=P(e)?await e(t):e;Object.keys(s).forEach(i=>{o.setHeader(i,s[i])})}catch(s){R.error(`${W.red("[headers error]")} ${t.url}
`,s)}}async function st(t,o,{cookies:e}){if(e)try{let r=P(e)?await e(t):e;Object.keys(r).forEach(n=>{let s=r[n];if(w(s)){let[i,c]=s;o.setCookie(n,i,c)}else o.setCookie(n,s)})}catch(r){R.error(`${W.red("[cookies error]")} ${t.url}
`,r)}}function it(t,o,e){if(ue(o))o.pipe(t);else if(ye.isBuffer(o))t.end(e==="text"||e==="json"?o.toString("utf-8"):o);else{let r=typeof o=="string"?o:JSON.stringify(o);t.end(e==="buffer"?ye.from(r):r)}}async function ve(t,o){if(!o||o<=0)return;let e=Date.now()-t,r=o-e;r>0&&await me(r)}function ct(t){return et[t]||"Unknown"}import ut from"events";import oe from"fs";import{createRequire as mt}from"module";import we from"path";import{pathToFileURL as dt}from"url";import Se from"chokidar";import{build as ft}from"esbuild";import kt from"fast-glob";import{createFilter as gt,normalizePath as q}from"vite";import{parse as at}from"url";import pt from"lodash.sortby";function xe(t){let o=[];for(let[,r]of t.entries())r&&(w(r)?o.push(...r):o.push(r));let e={};return o.filter(r=>(r.enabled||typeof r.enabled>"u")&&r.url).forEach(r=>{let{pathname:n,query:s}=at(r.url,!0),i=e[n]??(e[n]=[]),c={...r,url:n};if(c.ws!==!0){let u=c.validator;le(s)||(P(u)?c.validator=function(d){return _(d.query,s)&&u(d)}:u?(c.validator={...u},c.validator.query=c.validator.query?{...s,...c.validator.query}:s):c.validator={query:s})}i.push(c)}),Object.keys(e).forEach(r=>{e[r]=pt(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return s?P(s)?0:1/Object.keys(s).reduce((c,u)=>c+lt(s[u]),0):2})}),e}function lt(t){return t?Object.keys(t).length:0}var yt=de(import.meta.url),$=mt(yt),K=class extends ut{constructor(e){super();this.options=e;this.moduleCache=new Map;this.moduleDeps=new Map;this.moduleType="cjs";this._mockData={};this.cwd=e.cwd||process.cwd();try{let r=A(this.cwd,["package.json"]);this.moduleType=r&&JSON.parse(r).type==="module"?"esm":"cjs"}catch{}}get mockData(){return this._mockData}load(){let{include:e,exclude:r}=this.options,n=gt(e,r,{resolve:!1});kt(e,{cwd:this.cwd}).then(i=>Promise.all(i.filter(n).map(c=>this.loadMock(c)))).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let s=null;this.on("mock:update",async i=>{n(i)&&(await this.loadMock(i),s&&clearImmediate(s),s=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),s=null}))}),this.on("mock:unlink",async i=>{n(i)&&(this.moduleCache.delete(i),this.updateMockList(),this.emit("mock:update-end",i))})}watchMockEntry(){let{include:e}=this.options,[r,...n]=e,s=Se.watch(r,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=q(i),this.emit("mock:update",i),j("watcher:add",i)}),s.on("change",async i=>{i=q(i),this.emit("mock:update",i),j("watcher:change",i)}),s.on("unlink",async i=>{i=q(i),this.emit("mock:unlink",i),j("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=Se.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=q(r);let n=this.moduleDeps.get(r);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",r=>{r=q(r),this.moduleDeps.delete(r)}),this.on("update:deps",()=>{let r=[];for(let[s]of this.moduleDeps.entries())r.push(s);let n=r.filter(s=>!e.includes(s));n.length>0&&this.depsWatcher.add(n)})}close(){var e,r;(e=this.mockWatcher)==null||e.close(),(r=this.depsWatcher)==null||r.close()}updateMockList(){this._mockData=xe(this.moduleCache)}updateModuleDeps(e,r){Object.keys(r).forEach(n=>{r[n].imports.map(i=>i.path).forEach(i=>{this.moduleDeps.has(i)||this.moduleDeps.set(i,new Set),this.moduleDeps.get(i).add(e)})}),this.emit("update:deps")}async loadMock(e){if(!e)return;let r=!1;/\.m[jt]s$/.test(e)?r=!0:/\.c[jt]s$/.test(e)?r=!1:r=this.moduleType==="esm";let{code:n,deps:s}=await this.transformWithEsbuild(e,r);try{let i=await this.loadFromCode(e,n,r)||{},c;i.default?c=i.default:(c=[],Object.keys(i).forEach(u=>{w(i[u])?c.push(...i[u]):c.push(i[u])})),w(c)?c.forEach(u=>u.__filepath__=e):c.__filepath__=e,this.moduleCache.set(e,c),this.updateModuleDeps(e,s)}catch(i){console.error(i)}}async loadFromCode(e,r,n){if(n){let s=`${e}.timestamp-${Date.now()}`,i=`${s}.mjs`,c=`${dt(s)}.mjs`;await oe.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{oe.unlinkSync(i)}catch{}}}else{e=we.resolve(this.cwd,e);let s=we.extname(e),i=oe.realpathSync(e),c=s in $.extensions?s:".js",u=$.extensions[c];$.extensions[c]=(v,h)=>{h===i?v._compile(r,h):u(v,h)},delete $.cache[$.resolve(e)];let d=$(e);return $.extensions[c]=u,d.__esModule?d:{default:d}}}async transformWithEsbuild(e,r){var n;try{let s=await ft({entryPoints:[e],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:r?"esm":"cjs",define:this.options.define,plugins:[G(this.options.alias),B,z,J]});return{code:s.outputFiles[0].text,deps:((n=s.metafile)==null?void 0:n.inputs)||{}}}catch(s){console.error(s)}return{code:"",deps:{}}}};import{parse as Oe}from"url";import ht from"cookies";import{pathToRegexp as Ce}from"path-to-regexp";import vt from"picocolors";import{WebSocketServer as Mt}from"ws";function je(t,o,e,r){var D;let n=new Map,s=new Map,i=new WeakMap,c=a=>{let l=s.get(a);return!l&&s.set(a,l=new Map),l},u=(a,l)=>{let p=a.get(l);return!p&&a.set(l,p=new Mt({noServer:!0})),p},d=(a,l)=>{let p=n.get(a);!p&&n.set(a,p=new Set),p.add(l)},v=(a,l,p,m,f,k)=>{var g;try{(g=p.setup)==null||g.call(p,l,m),l.on("close",()=>{a.delete(f)})}catch(S){R.error(`${vt.red("[websocket server error]")} ${k}
`,S)}},h=(a,l,p,m)=>{a.emit("connection",l,p),l.on("close",()=>{let f=m.findIndex(k=>k.ws===l);f!==-1&&m.splice(f,1)})},F=(a,l,p,m,f)=>{let{cleanupList:k,connectionList:g,context:S}=i.get(l);Pe(k),g.forEach(({ws:C})=>C.removeAllListeners()),l.removeAllListeners(),v(a,l,p,S,m,f),g.forEach(({ws:C,req:E})=>h(l,C,E,g))};(D=t.on)==null||D.call(t,"mock:update-end",a=>{if(!n.has(a))return;let l=n.get(a);if(l)for(let p of l.values())for(let m of t.mockData[p]){if(!m.ws||m.__filepath__!==a)return;let f=c(p);for(let[k,g]of f.entries())F(f,g,m,k,a)}}),o==null||o.on("upgrade",(a,l,p)=>{let{pathname:m,query:f}=Oe(a.url,!0);if(!m||e.length===0||!e.some(M=>X(M,a.url)))return;let k=t.mockData,g=Object.keys(k).find(M=>Ce(M).test(m));if(!g)return;let S=k[g].find(M=>M.url&&M.ws&&Ce(M.url).test(m));if(!S)return;let C=S.__filepath__;d(C,g);let E=c(g),I=u(E,m),L=i.get(I);if(!L){let M=[],ne={onCleanup:De=>M.push(De)};L={cleanupList:M,context:ne,connectionList:[]},i.set(I,L),v(E,I,S,ne,m,C)}let y=a,H=new ht(a,a,r),{query:We}=Oe(a.headers.referer||"",!0);y.query=f,y.refererQuery=We,y.params=N(g,m),y.getCookie=H.get.bind(H),I.handleUpgrade(y,l,p,M=>{j(`websocket-mock: ${a.url} connected`),L.connectionList.push({req:y,ws:M}),h(I,M,y,L.connectionList)})}),o==null||o.on("close",()=>{for(let a of s.values()){for(let l of a.values()){let p=i.get(l);Pe(p.cleanupList),l.close()}a.clear()}s.clear(),n.clear()})}function Pe(t){let o;for(;o=t.shift();)o==null||o()}async function re(t,o,e,r){let n=O(o.include),s=O(o.exclude),i={};if(t.define)for(let v in t.define){let h=t.define[v];i[v]=typeof h=="string"?h:JSON.stringify(h)}let c=new K({include:n,exclude:s,define:i,alias:t.resolve.alias});c.load(),c.on("mock:update-end",()=>{o.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>c.close());let{httpProxies:u}=Q(t.server.proxy||{}),d=O(o.prefix);return je(c,e,O(o.wsPrefix),o.cookiesOptions),be(c,{formidableOptions:o.formidableOptions,proxies:[...d,...u],cookiesOptions:o.cookiesOptions})}function Re({prefix:t=[],wsPrefix:o=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:n=!1,formidableOptions:s={},build:i=!1,cookiesOptions:c={}}={}){let u={prefix:t,wsPrefix:o,include:e,exclude:r,reload:n,cookiesOptions:c,formidableOptions:{multiples:!0,...s},build:i?Object.assign({serverPort:8080,dist:"mockServer"},typeof i=="object"?i:{}):!1},d=[xt(u)];return u.build&&d.push(bt(u)),d}function bt(t){let o={};return{name:"vite-plugin-mock-dev-server-generator",enforce:"post",apply:"build",configResolved(e){o=e,e.logger.warn("")},async buildEnd(e){e||o.command==="build"&&await fe(this,o,t)}}}function xt(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",configResolved(e){o=e,e.logger.warn("")},async configureServer({middlewares:e,config:r,httpServer:n,ws:s}){let i=await re(r,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let n=await re(o,t,r);e.use(n)}}}function Zo(t){return t}function er(t){return e=>(w(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var nr=Re;export{be as baseMiddleware,er as createDefineMock,nr as default,Zo as defineMock,Re as mockDevServerPlugin,je as mockWebSocket,xe as transformMockData};
export default transformMockData(mockList);`}async function Ye(t,o,e){var r;try{let n=await qe({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:o,plugins:[Q(e),J,z,G]});return{code:n.outputFiles[0].text,deps:((r=n.metafile)==null?void 0:r.inputs)||{}}}catch(n){console.error(n)}return{code:"",deps:{}}}import{Buffer as ve}from"buffer";import{parse as he}from"url";import tt from"cookies";import ot from"http-status";import rt from"lodash.sortby";import*as U from"mime-types";import{pathToRegexp as be}from"path-to-regexp";import W from"picocolors";import oe from"co-body";import Ze from"formidable";async function ke(t,o){var n;let e=t.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((n=t.headers["content-type"])==null?void 0:n.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await oe.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await oe.form(t);if(r.startsWith("text/plain"))return await oe.text(t);if(r.startsWith("multipart/form-data"))return await et(t,o)}catch(s){console.error(s)}}async function et(t,o){let e=Ze(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function ye(t,o){return L(t.headers,o.headers)&&L(t.body,o.body)&&L(t.params,o.params)&&L(t.query,o.query)&&L(t.refererQuery,o.refererQuery)}function L(t,o){if(!o)return!0;for(let e in o)if(o[e]!==t[e])return!1;return!0}var nt=/:/g;function xe(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:a,pathname:m}=he(n.url,!0);if(!m||e.length===0||!e.some(y=>K(y,n.url)))return i();let x=t.mockData,v=rt(Object.keys(x),y=>{var N;return((N=y.match(nt))==null?void 0:N.length)||0}).find(y=>be(y).test(m));if(!v)return i();let{query:F}=he(n.headers.referer||"",!0),D=await ke(n,o),p=new tt(n,s,r),l=p.get.bind(p),u=n.method.toUpperCase(),d=st(x[v],{pathname:m,method:u,request:{query:a,refererQuery:F,body:D,headers:n.headers,getCookie:l}});if(!d)return i();C("middleware: ",u,n.url);let f=n,g=s;f.body=D,f.query=a,f.refererQuery=F,f.params=A(d.url,m),f.getCookie=l,g.setCookie=p.set.bind(p);let{body:k,delay:O,type:P="json",response:_,status:E=200,statusText:I}=d;if(re(g,E,I),await it(f,g,d),await ct(f,g,d),k){try{let y=j(k)?await k(f):k;await Me(c,O),at(g,y,P)}catch(y){R.error(`${W.red("[body error]")} ${n.url}
`,`file: ${W.cyan(d.__filepath__)}`,y),re(g,500),s.end("")}return}if(_){try{await Me(c,O),await _(f,g,i)}catch(y){R.error(`${W.red("[response error]")} ${n.url}
`,`file: ${W.cyan(d.__filepath__)}`,y),re(g,500),s.end("")}return}s.end("")}}function st(t,{pathname:o,method:e,request:r}){return t.find(n=>{if(!o||!n||!n.url||n.ws===!0||!(n.method?S(n.method)?n.method:[n.method]:["GET","POST"]).includes(e))return!1;let i=be(n.url).test(o);if(i&&n.validator){let c=A(n.url,o);if(j(n.validator))return n.validator({params:c,...r});try{return ye({params:c,...r},n.validator)}catch(a){return R.error(`${W.red("[validator error]")} ${o}
`,`file: ${W.cyan(n.__filepath__)}`,a),!1}}return i})}function re(t,o=200,e){t.statusCode=o,t.statusMessage=e||pt(o)}async function it(t,o,e){let{headers:r,type:n="json"}=e,s=e.__filepath__,i=U.contentType(n)||U.contentType(U.lookup(n)||"");if(i&&o.setHeader("Content-Type",i),o.setHeader("Cache-Control","no-cache,max-age=0"),o.setHeader("X-Mock-Power-By","vite-plugin-mock-dev-server"),o.setHeader("X-File-Path",s),!!r)try{let c=j(r)?await r(t):r;Object.keys(c).forEach(a=>{o.setHeader(a,c[a])})}catch(c){R.error(`${W.red("[headers error]")} ${t.url}
`,c)}}async function ct(t,o,{cookies:e}){if(e)try{let r=j(e)?await e(t):e;Object.keys(r).forEach(n=>{let s=r[n];if(S(s)){let[i,c]=s;o.setCookie(n,i,c)}else o.setCookie(n,s)})}catch(r){R.error(`${W.red("[cookies error]")} ${t.url}
`,r)}}function at(t,o,e){if(me(o))o.pipe(t);else if(ve.isBuffer(o))t.end(e==="text"||e==="json"?o.toString("utf-8"):o);else{let r=typeof o=="string"?o:JSON.stringify(o);t.end(e==="buffer"?ve.from(r):r)}}async function Me(t,o){if(!o||o<=0)return;let e=Date.now()-t,r=o-e;r>0&&await de(r)}function pt(t){return ot[t]||"Unknown"}import dt from"events";import ne from"fs";import{createRequire as ft}from"module";import Se from"path";import{pathToFileURL as gt}from"url";import Oe from"chokidar";import{build as kt}from"esbuild";import yt from"fast-glob";import{createFilter as vt,normalizePath as q}from"vite";import{parse as lt}from"url";import ut from"lodash.sortby";function we(t){let o=[];for(let[,r]of t.entries())r&&(S(r)?o.push(...r):o.push(r));let e={};return o.filter(r=>(r.enabled||typeof r.enabled>"u")&&r.url).forEach(r=>{let{pathname:n,query:s}=lt(r.url,!0),i=e[n]??(e[n]=[]),c={...r,url:n};if(c.ws!==!0){let a=c.validator;te(s)||(j(a)?c.validator=function(m){return L(m.query,s)&&a(m)}:a?(c.validator={...a},c.validator.query=c.validator.query?{...s,...c.validator.query}:s):c.validator={query:s})}i.push(c)}),Object.keys(e).forEach(r=>{e[r]=ut(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return!s||te(s)?2:j(s)?0:1/Object.keys(s).reduce((c,a)=>c+mt(s[a]),0)})}),e}function mt(t){return t?Object.keys(t).length:0}var ht=fe(import.meta.url),$=ft(ht),Y=class extends dt{constructor(e){super();this.options=e;this.moduleCache=new Map;this.moduleDeps=new Map;this.moduleType="cjs";this._mockData={};this.cwd=e.cwd||process.cwd();try{let r=H(this.cwd,["package.json"]);this.moduleType=r&&JSON.parse(r).type==="module"?"esm":"cjs"}catch{}}get mockData(){return this._mockData}load(){let{include:e,exclude:r}=this.options,n=vt(e,r,{resolve:!1});yt(e,{cwd:this.cwd}).then(i=>Promise.all(i.filter(n).map(c=>this.loadMock(c)))).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let s=null;this.on("mock:update",async i=>{n(i)&&(await this.loadMock(i),s&&clearImmediate(s),s=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),s=null}))}),this.on("mock:unlink",async i=>{n(i)&&(this.moduleCache.delete(i),this.updateMockList(),this.emit("mock:update-end",i))})}watchMockEntry(){let{include:e}=this.options,[r,...n]=e,s=Oe.watch(r,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=q(i),this.emit("mock:update",i),C("watcher:add",i)}),s.on("change",async i=>{i=q(i),this.emit("mock:update",i),C("watcher:change",i)}),s.on("unlink",async i=>{i=q(i),this.emit("mock:unlink",i),C("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=Oe.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=q(r);let n=this.moduleDeps.get(r);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",r=>{r=q(r),this.moduleDeps.delete(r)}),this.on("update:deps",()=>{let r=[];for(let[s]of this.moduleDeps.entries())r.push(s);let n=r.filter(s=>!e.includes(s));n.length>0&&this.depsWatcher.add(n)})}close(){var e,r;(e=this.mockWatcher)==null||e.close(),(r=this.depsWatcher)==null||r.close()}updateMockList(){this._mockData=we(this.moduleCache)}updateModuleDeps(e,r){Object.keys(r).forEach(n=>{r[n].imports.map(i=>i.path).forEach(i=>{this.moduleDeps.has(i)||this.moduleDeps.set(i,new Set),this.moduleDeps.get(i).add(e)})}),this.emit("update:deps")}async loadMock(e){if(!e)return;let r=!1;/\.m[jt]s$/.test(e)?r=!0:/\.c[jt]s$/.test(e)?r=!1:r=this.moduleType==="esm";let{code:n,deps:s}=await this.transformWithEsbuild(e,r);try{let i=await this.loadFromCode(e,n,r)||{},c;i.default?c=i.default:(c=[],Object.keys(i).forEach(a=>{S(i[a])?c.push(...i[a]):c.push(i[a])})),S(c)?c.forEach(a=>a.__filepath__=e):c.__filepath__=e,this.moduleCache.set(e,c),this.updateModuleDeps(e,s)}catch(i){console.error(i)}}async loadFromCode(e,r,n){if(n){let s=`${e}.timestamp-${Date.now()}`,i=`${s}.mjs`,c=`${gt(s)}.mjs`;await ne.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{ne.unlinkSync(i)}catch{}}}else{e=Se.resolve(this.cwd,e);let s=Se.extname(e),i=ne.realpathSync(e),c=s in $.extensions?s:".js",a=$.extensions[c];$.extensions[c]=(x,v)=>{v===i?x._compile(r,v):a(x,v)},delete $.cache[$.resolve(e)];let m=$(e);return $.extensions[c]=a,m.__esModule?m:{default:m}}}async transformWithEsbuild(e,r){var n;try{let s=await kt({entryPoints:[e],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:r?"esm":"cjs",define:this.options.define,plugins:[Q(this.options.alias),J,G,z]});return{code:s.outputFiles[0].text,deps:((n=s.metafile)==null?void 0:n.inputs)||{}}}catch(s){console.error(s)}return{code:"",deps:{}}}};import{parse as Pe}from"url";import Mt from"cookies";import{pathToRegexp as je}from"path-to-regexp";import bt from"picocolors";import{WebSocketServer as xt}from"ws";function Re(t,o,e,r){var D;let n=new Map,s=new Map,i=new WeakMap,c=p=>{let l=s.get(p);return!l&&s.set(p,l=new Map),l},a=(p,l)=>{let u=p.get(l);return!u&&p.set(l,u=new xt({noServer:!0})),u},m=(p,l)=>{let u=n.get(p);!u&&n.set(p,u=new Set),u.add(l)},x=(p,l,u,d,f,g)=>{var k;try{(k=u.setup)==null||k.call(u,l,d),l.on("close",()=>p.delete(f))}catch(O){R.error(`${bt.red("[websocket server error]")} ${g}
`,O)}},v=(p,l,u,d)=>{p.emit("connection",l,u),l.on("close",()=>{let f=d.findIndex(g=>g.ws===l);f!==-1&&d.splice(f,1)})},F=(p,l,u,d,f)=>{let{cleanupList:g,connectionList:k,context:O}=i.get(l);Ce(g),k.forEach(({ws:P})=>P.removeAllListeners()),l.removeAllListeners(),x(p,l,u,O,d,f),k.forEach(({ws:P,req:_})=>v(l,P,_,k))};(D=t.on)==null||D.call(t,"mock:update-end",p=>{if(!n.has(p))return;let l=n.get(p);if(l)for(let u of l.values())for(let d of t.mockData[u]){if(!d.ws||d.__filepath__!==p)return;let f=c(u);for(let[g,k]of f.entries())F(f,k,d,g,p)}}),o==null||o.on("upgrade",(p,l,u)=>{let{pathname:d,query:f}=Pe(p.url,!0);if(!d||e.length===0||!e.some(h=>K(h,p.url)))return;let g=t.mockData,k=Object.keys(g).find(h=>je(h).test(d));if(!k)return;let O=g[k].find(h=>h.url&&h.ws&&je(h.url).test(d));if(!O)return;let P=O.__filepath__;m(P,k);let _=c(k),E=a(_,d),I=i.get(E);if(!I){let h=[],ie={onCleanup:_e=>h.push(_e)};I={cleanupList:h,context:ie,connectionList:[]},i.set(E,I),x(_,E,O,ie,d,P)}let y=p,N=new Mt(p,p,r),{query:De}=Pe(p.headers.referer||"",!0);y.query=f,y.refererQuery=De,y.params=A(k,d),y.getCookie=N.get.bind(N),E.handleUpgrade(y,l,u,h=>{C(`websocket-mock: ${p.url} connected`),I.connectionList.push({req:y,ws:h}),v(E,h,y,I.connectionList)})}),o==null||o.on("close",()=>{for(let p of s.values()){for(let l of p.values()){let u=i.get(l);Ce(u.cleanupList),l.close()}p.clear()}s.clear(),n.clear()})}function Ce(t){let o;for(;o=t.shift();)o==null||o()}async function se(t,o,e,r){let n=new Y({include:w(o.include),exclude:w(o.exclude),define:B(t),alias:t.resolve.alias});n.load(),n.on("mock:update-end",()=>{o.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>n.close());let{httpProxies:s}=V(t.server.proxy||{}),i=w(o.prefix);return Re(n,e,w(o.wsPrefix),o.cookiesOptions),xe(n,{formidableOptions:o.formidableOptions,proxies:[...i,...s],cookiesOptions:o.cookiesOptions})}function We({prefix:t=[],wsPrefix:o=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:n=!1,formidableOptions:s={},build:i=!1,cookiesOptions:c={}}={}){let a={prefix:t,wsPrefix:o,include:e,exclude:r,reload:n,cookiesOptions:c,formidableOptions:{multiples:!0,...s},build:i?Object.assign({serverPort:8080,dist:"mockServer"},typeof i=="object"?i:{}):!1},m=[St(a)];return a.build&&m.push(wt(a)),m}function wt(t){let o={};return{name:"vite-plugin-mock-dev-server-generator",enforce:"post",apply:"build",configResolved(e){o=e,e.logger.warn("")},async buildEnd(e){e||o.command==="build"&&await ge(this,o,t)}}}function St(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var s;let r=w(t.wsPrefix);if(r.length===0||!((s=e.server)!=null&&s.proxy)||Object.keys(e.server.proxy).length===0)return;let n={};Object.keys(e.server.proxy).forEach(i=>{r.includes(i)||(n[i]=e.server.proxy[i])}),e.server.proxy=n},configResolved(e){o=e,e.logger.warn("")},async configureServer({middlewares:e,config:r,httpServer:n,ws:s}){let i=await se(r,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let n=await se(o,t,r);e.use(n)}}}function ir(t){return t}function cr(t){return e=>(S(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var ur=We;export{xe as baseMiddleware,cr as createDefineMock,ur as default,ir as defineMock,We as mockDevServerPlugin,Re as mockWebSocket,we as transformMockData};
{
"name": "vite-plugin-mock-dev-server",
"version": "1.1.11",
"version": "1.1.12",
"keywords": [

@@ -5,0 +5,0 @@ "vite",

@@ -41,3 +41,3 @@ # vite-plugin-mock-dev-server

- ⚖️ Use `server.proxy`
- 🍕 Support `viteConfig.define` in the mock file.
- 🍕 Support `viteConfig.define` and `env` in the mock file.
- ⚓️ Support `viteConfig.resolve.alias` in the mock file.

@@ -61,3 +61,3 @@ - 🌈 Support `vite preview` mode.

```sh
``` sh
# npm

@@ -74,3 +74,3 @@ npm i -D vite-plugin-mock-dev-server

`vite.config.ts`
```ts
``` ts
import { defineConfig } from 'vite'

@@ -107,3 +107,3 @@ import mockDevServerPlugin from 'vite-plugin-mock-dev-server'

`mock/api.mock.ts` :
```ts
``` ts
import { defineMock } from 'vite-plugin-mock-dev-server'

@@ -128,3 +128,3 @@

`vite.config.ts`
```ts
``` ts
import { defineConfig } from 'vite'

@@ -197,3 +197,3 @@ import mockDevServerPlugin from 'vite-plugin-mock-dev-server'

example: Configure to file upload dir
```ts
``` ts
MockDevServerPlugin({

@@ -220,3 +220,3 @@ formidableOptions: {

```ts
``` ts
interface ServerBuildOptions {

@@ -240,3 +240,3 @@ /**

```ts
``` ts
import { defineMock } from 'vite-plugin-mock-dev-server'

@@ -254,3 +254,3 @@

```ts
``` ts
import path from 'node:path'

@@ -271,3 +271,3 @@ import { createDefineMock } from 'vite-plugin-mock-dev-server'

```ts
``` ts
// Configure the http mock

@@ -397,3 +397,3 @@ export default defineMock({

```
```ts
``` ts
// Configure the WebSocket mock

@@ -456,3 +456,3 @@ export default defineMock({

```ts
``` ts
type Response = http.ServerResponse<http.IncomingMessage> & {

@@ -481,3 +481,3 @@ setCookie: (

**exp:** Match `/api/test`, And returns a response body content with empty data
```ts
``` ts
export default defineMock({

@@ -489,3 +489,3 @@ url: '/api/test',

**exp:** Match `/api/test` , And returns a static content data
```ts
``` ts
export default defineMock({

@@ -499,3 +499,3 @@ url: '/api/test',

**exp:** Only Support `GET` Method
```ts
``` ts
export default defineMock({

@@ -508,3 +508,3 @@ url: '/api/test',

**exp:** In the response header, add a custom header and cookie
```ts
``` ts
export default defineMock({

@@ -516,3 +516,3 @@ url: '/api/test',

```
```ts
``` ts
export default defineMock({

@@ -531,3 +531,3 @@ url: '/api/test',

**exp:** Define multiple mock requests for the same URL and match valid rules with validators
```ts
``` ts
export default defineMock([

@@ -560,3 +560,3 @@ // Match /api/test?a=1

**exp:** Response Delay
```ts
``` ts
export default defineMock({

@@ -570,3 +570,3 @@ url: '/api/test',

**exp:** The interface request failed
```ts
``` ts
export default defineMock({

@@ -581,3 +581,3 @@ url: '/api/test',

**exp:** Dynamic route matching
```ts
``` ts
export default defineMock({

@@ -605,3 +605,3 @@ url: '/api/user/:userId',

```
```ts
``` ts
// When the type is buffer, the content-type is application/octet-stream.

@@ -620,3 +620,3 @@ // The data passed in through body will be converted to a buffer.

Simulate file download, and pass in the file reading stream.
```ts
``` ts
import { createReadStream } from 'node:fs'

@@ -636,3 +636,3 @@

**exp:** Use `mockjs`:
```ts
``` ts
import Mock from 'mockjs'

@@ -653,3 +653,3 @@

**exp:** Use `response` to customize the response
```ts
``` ts
export default defineMock({

@@ -674,3 +674,3 @@ url: '/api/test',

**exp:** Use json / json5
```json
``` json
{

@@ -721,3 +721,3 @@ "url": "/api/test",

**exp:** Graphql
```ts
``` ts
import { buildSchema, graphql } from 'graphql'

@@ -743,3 +743,3 @@

```ts
``` ts
fetch('/api/graphql', {

@@ -752,3 +752,3 @@ method: 'POST',

**exp:** WebSocket Mock
```ts
``` ts
// ws.mock.ts

@@ -780,3 +780,3 @@ export default defineMock({

```
```ts
``` ts
// app.ts

@@ -802,3 +802,3 @@ const ws = new WebSocket('ws://localhost:5173/socket.io')

The default output is built into the directory `dist/mockServer`, generating files as follows:
```sh
``` sh
./mockServer

@@ -805,0 +805,0 @@ ├── index.js

@@ -42,3 +42,3 @@ # vite-plugin-mock-dev-server

- ⚖️ 使用 `server.proxy` 配置
- 🍕 支持在 mock文件中使用 `viteConfig.define`配置字段
- 🍕 支持在 mock文件中使用 `viteConfig.define`配置字段 和 `env` 环境变量
- ⚓️ 支持在 mock文件中使用 `viteConfig.resolve.alias` 路径别名

@@ -45,0 +45,0 @@ - 🌈 支持 `vite preview` 模式

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc