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.16 to 1.2.0

6

dist/index.d.ts

@@ -6,2 +6,3 @@ import { Connect, Plugin, ResolvedConfig } from 'vite';

import Cookies from 'cookies';
import { CorsOptions } from 'cors';
import formidable from 'formidable';

@@ -68,2 +69,3 @@ import { WebSocketServer } from 'ws';

reload?: boolean;
cors?: boolean | CorsOptions;
/**

@@ -426,3 +428,3 @@ * formidable options

declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, formidableOptions, build, cookiesOptions, }?: MockServerPluginOptions): Plugin[];
declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, cors, formidableOptions, build, cookiesOptions, }?: MockServerPluginOptions): Plugin[];

@@ -459,4 +461,4 @@ /**

declare function defineMock(config: MockHttpItem): MockHttpItem;
declare function defineMock(config: MockWebsocketItem): MockWebsocketItem;
declare function defineMock(config: MockOptions): MockOptions;
declare function defineMock(config: MockWebsocketItem): MockWebsocketItem;
/**

@@ -463,0 +465,0 @@ * Return a custom defineMock function to support preprocessing of mock config.

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

import Be from"fs";import Z from"fs/promises";import N from"path";import{build as ze}from"esbuild";import Ge from"fast-glob";import Qe from"is-core-module";import{createFilter as Ve,normalizePath as Ke}from"vite";var ue="vite-plugin-mock-dev-server",me="1.1.16";import ne from"picocolors";import te from"fs";import oe from"path";import{parse as Le}from"querystring";import{URL as $e,fileURLToPath as Te}from"url";import Fe from"debug";import{match as Ne}from"path-to-regexp";import de from"picocolors";var v=t=>Array.isArray(t),C=t=>typeof t=="function",B=t=>Object.prototype.toString.call(t)==="[object Object]",re=t=>B(t)&&Object.keys(t).length===0,He=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",fe=t=>He(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function ke(t){return new Promise(o=>setTimeout(o,t))}function ge(t){return oe.dirname(Te(t))}var R=Fe("vite:plugin-mock-dev-server"),S=t=>v(t)?t:t==null?[]:[t],P={info(...t){console.info(de.cyan("mock-dev-server: "),...t)},error(...t){console.error(`
import qe from"node:fs";import Z from"node:fs/promises";import U from"node:path";import{build as ze}from"esbuild";import Ge from"fast-glob";import Qe from"is-core-module";import{createFilter as Ve,normalizePath as Ke}from"vite";var ue="vite-plugin-mock-dev-server",me="1.2.0";import ne from"picocolors";import te from"node:fs";import oe from"node:path";import{parse as Ie}from"node:querystring";import{URL as $e,fileURLToPath as Te}from"node:url";import Fe from"debug";import{match as Ne}from"path-to-regexp";import de from"picocolors";var v=t=>Array.isArray(t),W=t=>typeof t=="function",N=t=>Object.prototype.toString.call(t)==="[object Object]",re=t=>N(t)&&Object.keys(t).length===0,He=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",fe=t=>He(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function ke(t){return new Promise(o=>setTimeout(o,t))}function ge(t){return oe.dirname(Te(t))}var D=Fe("vite:plugin-mock-dev-server"),S=t=>v(t)?t:t==null?[]:[t],P={info(...t){console.info(de.cyan("mock-dev-server: "),...t)},error(...t){console.error(`
`,de.cyan("mock-dev-server: "),...t,`
`)}};function A(t,o,e){for(let n of o){let s=oe.join(t,n);if(te.existsSync(s)&&te.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:te.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=oe.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return A(r,o,e)}var z=(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 G(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function U(t,o){return(Ne(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}function W(t){let o=new $e(t,"http://example.com"),e=decodeURIComponent(o.pathname),r=Le(o.search.replace(/^\?/,""));return{pathname:e,query:r}}var Ae=/import\.meta\.env\.(.+)/;function Q(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={},s=[];for(let a in t.define){let u=t.define[a];if(typeof u=="string")try{JSON.parse(u),r[a]=u}catch{s.push(a)}else r[a]=JSON.stringify(u);let h=a.match(Ae);h&&r[a]&&(n[h[1]]=`__vite__define__${r[a]}`)}s.length&&P.error(`${ne.yellow("[warn]")} The following keys: ${ne.yellow(ne.underline(s.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let i={},c={};i["import.meta.hot"]="undefined";for(let a in t.env)i[`import.meta.env.${a}`]=JSON.stringify(t.env[a]);return Object.assign(c,{"import.meta.env":JSON.stringify({...t.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(a,u,h)=>`${u.replace(/(^\\")|(\\"$)/g,'"')}${h}`)}),{...i,...r,...c,...o}}import ye from"fs/promises";import Ue from"path";import Je from"json5";var V={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Ue.isAbsolute(o))return{external:!0}})}},K={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await ye.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Je.parse(e))}`,loader:"js"}})}},X={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await ye.readFile(o,"utf-8")}`,loader:"js"}))}},Y=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>qe(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 qe(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}async function he(t,o,e){let r=S(e.include),n=S(e.exclude),s=Q(o),{httpProxies:i}=z(o.server.proxy||{});i.push(...S(e.prefix));let c=S(e.wsPrefix),a={};try{let m=A(o.root,["package.json"]);m&&(a=JSON.parse(m))}catch{}let u=e.build.dist,h=await et(process.cwd(),r,n),M=N.join(o.root,`mock-data-${Date.now()}.js`);await Z.writeFile(M,h,"utf-8");let{code:F,deps:_}=await tt(M,s,o.resolve.alias),p=Xe(_);await Z.unlink(M);let l=[{filename:N.join(u,"mock-data.js"),source:F},{filename:N.join(u,"index.js"),source:Ze(i,c,e.cookiesOptions,e.build.serverPort)},{filename:N.join(u,"package.json"),source:Ye(a,p)}];try{if(N.isAbsolute(u)){await Z.rm(u,{recursive:!0}),Be.mkdirSync(u,{recursive:!0});for(let{filename:m,source:d}of l)await Z.writeFile(m,d,"utf-8")}else for(let{filename:m,source:d}of l)t.emitFile({type:"asset",fileName:m,source:d})}catch{}}function Xe(t){let o=new Set,e=[ue,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external&&!s.path.startsWith("<define:")).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Qe(s)&&o.add(s)})}),Array.from(o)}function Ye(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":`^${me}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Ze(t,o,e={},r=8080){return`import { createServer } from 'node:http';
`)}};function B(t,o,e){for(let n of o){let s=oe.join(t,n);if(te.existsSync(s)&&te.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:te.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=oe.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return B(r,o,e)}var G=(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 H(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function J(t,o){return(Ne(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}function j(t){let o=new $e(t,"http://example.com"),e=decodeURIComponent(o.pathname),r=Ie(o.search.replace(/^\?/,""));return{pathname:e,query:r}}var Ue=/import\.meta\.env\.(.+)/;function Q(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={},s=[];for(let a in t.define){let p=t.define[a];if(typeof p=="string")try{JSON.parse(p),r[a]=p}catch{s.push(a)}else r[a]=JSON.stringify(p);let f=a.match(Ue);f&&r[a]&&(n[f[1]]=`__vite__define__${r[a]}`)}s.length&&P.error(`${ne.yellow("[warn]")} The following keys: ${ne.yellow(ne.underline(s.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let i={},c={};i["import.meta.hot"]="undefined";for(let a in t.env)i[`import.meta.env.${a}`]=JSON.stringify(t.env[a]);return Object.assign(c,{"import.meta.env":JSON.stringify({...t.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(a,p,f)=>`${p.replace(/(^\\")|(\\"$)/g,'"')}${f}`)}),{...i,...r,...c,...o}}import ye from"node:fs/promises";import Ae from"node:path";import Be from"json5";var V={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Ae.isAbsolute(o))return{external:!0}})}},K={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await ye.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Be.parse(e))}`,loader:"js"}})}},X={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await ye.readFile(o,"utf-8")}`,loader:"js"}))}},Y=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>Je(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 Je(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}async function he(t,o,e){let r=S(e.include),n=S(e.exclude),s=Q(o),{httpProxies:i}=G(o.server.proxy||{});i.push(...S(e.prefix));let c=S(e.wsPrefix),a={};try{let m=B(o.root,["package.json"]);m&&(a=JSON.parse(m))}catch{}let p=e.build.dist,f=await et(process.cwd(),r,n),M=U.join(o.root,`mock-data-${Date.now()}.js`);await Z.writeFile(M,f,"utf-8");let{code:O,deps:L}=await tt(M,s,o.resolve.alias),l=Xe(L);await Z.unlink(M);let u=[{filename:U.join(p,"mock-data.js"),source:O},{filename:U.join(p,"index.js"),source:Ze(i,c,e.cookiesOptions,e.build.serverPort)},{filename:U.join(p,"package.json"),source:Ye(a,l)}];try{if(U.isAbsolute(p)){await Z.rm(p,{recursive:!0}),qe.mkdirSync(p,{recursive:!0});for(let{filename:m,source:d}of u)await Z.writeFile(m,d,"utf-8")}else for(let{filename:m,source:d}of u)t.emitFile({type:"asset",fileName:m,source:d})}catch{}}function Xe(t){let o=new Set,e=[ue,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external&&!s.path.startsWith("<define:")).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Qe(s)&&o.add(s)})}),Array.from(o)}function Ye(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":`^${me}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Ze(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 et(t,o,e){let r=await Ge(o,{cwd:t}),n=Ve(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((a,u)=>{let h=Ke(N.join(t,a));i+=`import * as m${u} from '${h}';
`,c+=`m${u}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server';
`}async function et(t,o,e){let r=await Ge(o,{cwd:t}),n=Ve(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((a,p)=>{let f=Ke(U.join(t,a));i+=`import * as m${p} from '${f}';
`,c+=`m${p}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server';
${i}

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

});
export default transformMockData(mockList);`}async function tt(t,o,e){var r;try{let n=await ze({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:o,plugins:[Y(e),V,K,X]});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 xe}from"buffer";import nt from"cookies";import st from"http-status";import it from"lodash.sortby";import*as J from"mime-types";import{pathToRegexp as Se}from"path-to-regexp";import E from"picocolors";import se from"co-body";import ot from"formidable";async function ve(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 se.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await se.form(t);if(r.startsWith("text/plain"))return await se.text(t);if(r.startsWith("multipart/form-data"))return await rt(t,o)}catch(s){console.error(s)}}async function rt(t,o){let e=ot(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function Me(t,o){return D(t.headers,o.headers)&&D(t.body,o.body)&&D(t.params,o.params)&&D(t.query,o.query)&&D(t.refererQuery,o.refererQuery)}function D(t,o){if(!o)return!0;for(let e in o)if(!be(t[e],o[e]))return!1;return!0}function be(t,o){if(v(t)&&v(o)){let e=new Set;return o.every(r=>t.some((n,s)=>{if(e.has(s))return!1;let i=be(n,r);return i&&e.add(s),i}))}return B(t)&&B(o)?D(t,o):t===o}var ct=/:/g;function Oe(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:a,pathname:u}=W(n.url);if(!u||e.length===0||!e.some(y=>G(y,n.url)))return i();let h=t.mockData,M=it(Object.keys(h),y=>{var H;return((H=y.match(ct))==null?void 0:H.length)||0}).find(y=>Se(y).test(u));if(!M)return i();let{query:F}=W(n.headers.referer||""),_=await ve(n,o),p=new nt(n,s,r),l=p.get.bind(p),m=n.method.toUpperCase(),d=at(h[M],{pathname:u,method:m,request:{query:a,refererQuery:F,body:_,headers:n.headers,getCookie:l}});if(!d)return i();R("middleware: ",m,n.url);let f=n,k=s;f.body=_,f.query=a,f.refererQuery=F,f.params=U(d.url,u),f.getCookie=l,k.setCookie=p.set.bind(p);let{body:g,delay:O,type:j="json",response:I,status:L=200,statusText:$}=d;if(ie(k,L,$),await pt(f,k,d),await lt(f,k,d),g){try{let y=C(g)?await g(f):g;await we(c,O),ut(k,y,j)}catch(y){P.error(`${E.red("[body error]")} ${n.url}
`,`file: ${E.cyan(d.__filepath__)}`,y),ie(k,500),s.end("")}return}if(I){try{await we(c,O),await I(f,k,i)}catch(y){P.error(`${E.red("[response error]")} ${n.url}
`,`file: ${E.cyan(d.__filepath__)}`,y),ie(k,500),s.end("")}return}s.end("")}}function at(t,{pathname:o,method:e,request:r}){return t.find(n=>{if(!o||!n||!n.url||n.ws===!0||!(n.method?v(n.method)?n.method:[n.method]:["GET","POST"]).includes(e))return!1;let i=Se(n.url).test(o);if(i&&n.validator){let c=U(n.url,o);if(C(n.validator))return n.validator({params:c,...r});try{return Me({params:c,...r},n.validator)}catch(a){return P.error(`${E.red("[validator error]")} ${o}
`,`file: ${E.cyan(n.__filepath__)}`,a),!1}}return i})}function ie(t,o=200,e){t.statusCode=o,t.statusMessage=e||mt(o)}async function pt(t,o,e){let{headers:r,type:n="json"}=e,s=e.__filepath__,i=J.contentType(n)||J.contentType(J.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=C(r)?await r(t):r;Object.keys(c).forEach(a=>{o.setHeader(a,c[a])})}catch(c){P.error(`${E.red("[headers error]")} ${t.url}
`,c)}}async function lt(t,o,{cookies:e}){if(e)try{let r=C(e)?await e(t):e;Object.keys(r).forEach(n=>{let s=r[n];if(v(s)){let[i,c]=s;o.setCookie(n,i,c)}else o.setCookie(n,s)})}catch(r){P.error(`${E.red("[cookies error]")} ${t.url}
`,r)}}function ut(t,o,e){if(fe(o))o.pipe(t);else if(xe.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"?xe.from(r):r)}}async function we(t,o){if(!o||typeof o=="number"&&o<=0||v(o)&&o.length!==2)return;let e=0;if(v(o)){let[r,n]=o;e=Math.floor(Math.random()*(n-r+1))+r}else e=o-(Date.now()-t);e>0&&await ke(e)}function mt(t){return st[t]||"Unknown"}import kt from"events";import ce from"fs";import{createRequire as gt}from"module";import je from"path";import{pathToFileURL as yt}from"url";import Ce from"chokidar";import{build as ht}from"esbuild";import vt from"fast-glob";import{createFilter as Mt,normalizePath as q}from"vite";import dt from"lodash.sortby";function Pe(t){let o=[];for(let[,r]of t.entries())r&&(v(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}=W(r.url),i=e[n]??(e[n]=[]),c={...r,url:n};if(c.ws!==!0){let a=c.validator;re(s)||(C(a)?c.validator=function(u){return D(u.query,s)&&a(u)}: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]=dt(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return!s||re(s)?2:C(s)?0:1/Object.keys(s).reduce((c,a)=>c+ft(s[a]),0)})}),e}function ft(t){return t?Object.keys(t).length:0}var bt=ge(import.meta.url),T=gt(bt),ee=class extends kt{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=Mt(e,r,{resolve:!1});vt(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=Ce.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),R("watcher:add",i)}),s.on("change",async i=>{i=q(i),this.emit("mock:update",i),R("watcher:change",i)}),s.on("unlink",async i=>{i=q(i),this.emit("mock:unlink",i),R("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=Ce.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=Pe(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=>{v(i[a])?c.push(...i[a]):c.push(i[a])})),v(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=`${yt(s)}.mjs`;await ce.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{ce.unlinkSync(i)}catch{}}}else{e=je.resolve(this.cwd,e);let s=je.extname(e),i=ce.realpathSync(e),c=s in T.extensions?s:".js",a=T.extensions[c];T.extensions[c]=(h,M)=>{M===i?h._compile(r,M):a(h,M)},delete T.cache[T.resolve(e)];let u=T(e);return T.extensions[c]=a,u.__esModule?u:{default:u}}}async transformWithEsbuild(e,r){var n;try{let s=await ht({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:[Y(this.options.alias),V,X,K]});return{code:s.outputFiles[0].text,deps:((n=s.metafile)==null?void 0:n.inputs)||{}}}catch(s){console.error(s)}return{code:"",deps:{}}}};import xt from"cookies";import{pathToRegexp as Re}from"path-to-regexp";import wt from"picocolors";import{WebSocketServer as St}from"ws";function De(t,o,e,r){var _;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 m=p.get(l);return!m&&p.set(l,m=new St({noServer:!0})),m},u=(p,l)=>{let m=n.get(p);!m&&n.set(p,m=new Set),m.add(l)},h=(p,l,m,d,f,k)=>{var g;try{(g=m.setup)==null||g.call(m,l,d),l.on("close",()=>p.delete(f))}catch(O){P.error(`${wt.red("[websocket server error]")} ${k}
`,O)}},M=(p,l,m,d)=>{p.emit("connection",l,m),l.on("close",()=>{let f=d.findIndex(k=>k.ws===l);f!==-1&&d.splice(f,1)})},F=(p,l,m,d,f)=>{let{cleanupList:k,connectionList:g,context:O}=i.get(l);We(k),g.forEach(({ws:j})=>j.removeAllListeners()),l.removeAllListeners(),h(p,l,m,O,d,f),g.forEach(({ws:j,req:I})=>M(l,j,I,g))};(_=t.on)==null||_.call(t,"mock:update-end",p=>{if(!n.has(p))return;let l=n.get(p);if(l)for(let m of l.values())for(let d of t.mockData[m]){if(!d.ws||d.__filepath__!==p)return;let f=c(m);for(let[k,g]of f.entries())F(f,g,d,k,p)}}),o==null||o.on("upgrade",(p,l,m)=>{let{pathname:d,query:f}=W(p.url);if(!d||e.length===0||!e.some(b=>G(b,p.url)))return;let k=t.mockData,g=Object.keys(k).find(b=>Re(b).test(d));if(!g)return;let O=k[g].find(b=>b.url&&b.ws&&Re(b.url).test(d));if(!O)return;let j=O.__filepath__;u(j,g);let I=c(g),L=a(I,d),$=i.get(L);if(!$){let b=[],pe={onCleanup:Ie=>b.push(Ie)};$={cleanupList:b,context:pe,connectionList:[]},i.set(L,$),h(I,L,O,pe,d,j)}let y=p,H=new xt(p,p,r),{query:_e}=W(p.headers.referer||"");y.query=f,y.refererQuery=_e,y.params=U(g,d),y.getCookie=H.get.bind(H),L.handleUpgrade(y,l,m,b=>{R(`websocket-mock: ${p.url} connected`),$.connectionList.push({req:y,ws:b}),M(L,b,y,$.connectionList)})}),o==null||o.on("close",()=>{for(let p of s.values()){for(let l of p.values()){let m=i.get(l);We(m.cleanupList),l.close()}p.clear()}s.clear(),n.clear()})}function We(t){let o;for(;o=t.shift();)o==null||o()}async function ae(t,o,e,r){let n=new ee({include:S(o.include),exclude:S(o.exclude),define:Q(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}=z(t.server.proxy||{}),i=S(o.prefix);return De(n,e,S(o.wsPrefix),o.cookiesOptions),Oe(n,{formidableOptions:o.formidableOptions,proxies:[...i,...s],cookiesOptions:o.cookiesOptions})}function Ee({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},u=[Pt(a)];return a.build&&u.push(Ot(a)),u}function Ot(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 he(this,o,t)}}}function Pt(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var s;let r=S(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 ae(r,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let n=await ae(o,t,r);e.use(n)}}}function pr(t){return t}function lr(t){return e=>(v(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var fr=Ee;export{Oe as baseMiddleware,lr as createDefineMock,fr as default,pr as defineMock,Ee as mockDevServerPlugin,De as mockWebSocket,Pe as transformMockData};
export default transformMockData(mockList);`}async function tt(t,o,e){var r;try{let n=await ze({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:o,plugins:[Y(e),V,K,X]});return{code:n.outputFiles[0].text,deps:((r=n.metafile)==null?void 0:r.inputs)||{}}}catch(n){console.error(n)}return{code:"",deps:{}}}import Ot from"cors";import{pathToRegexp as Ct}from"path-to-regexp";import{Buffer as xe}from"node:buffer";import nt from"cookies";import st from"http-status";import it from"lodash.sortby";import*as q from"mime-types";import{pathToRegexp as Se}from"path-to-regexp";import _ from"picocolors";import se from"co-body";import ot from"formidable";async function ve(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 se.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await se.form(t);if(r.startsWith("text/plain"))return await se.text(t);if(r.startsWith("multipart/form-data"))return await rt(t,o)}catch(s){console.error(s)}}async function rt(t,o){let e=ot(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function Me(t,o){return E(t.headers,o.headers)&&E(t.body,o.body)&&E(t.params,o.params)&&E(t.query,o.query)&&E(t.refererQuery,o.refererQuery)}function E(t,o){if(!o)return!0;for(let e in o)if(!be(t[e],o[e]))return!1;return!0}function be(t,o){if(v(t)&&v(o)){let e=new Set;return o.every(r=>t.some((n,s)=>{if(e.has(s))return!1;let i=be(n,r);return i&&e.add(s),i}))}return N(t)&&N(o)?E(t,o):Object.is(t,o)}var ct=/:/g;function Oe(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:a,pathname:p}=j(n.url);if(!p||e.length===0||!e.some(h=>H(h,n.url)))return i();let f=t.mockData,M=it(Object.keys(f),h=>{var A;return((A=h.match(ct))==null?void 0:A.length)||0}).find(h=>Se(h).test(p));if(!M)return i();let{query:O}=j(n.headers.referer||""),L=await ve(n,o),l=new nt(n,s,r),u=l.get.bind(l),m=n.method.toUpperCase(),d=at(f[M],{pathname:p,method:m,request:{query:a,refererQuery:O,body:L,headers:n.headers,getCookie:u}});if(!d)return i();D("middleware: ",m,n.url);let k=n,g=s;k.body=L,k.query=a,k.refererQuery=O,k.params=J(d.url,p),k.getCookie=u,g.setCookie=l.set.bind(l);let{body:y,delay:C,type:R="json",response:I,status:$=200,statusText:T}=d;if(ie(g,$,T),await pt(k,g,d),await lt(k,g,d),y){try{let h=W(y)?await y(k):y;await we(c,C),ut(g,h,R)}catch(h){P.error(`${_.red("[body error]")} ${n.url}
`,`file: ${_.cyan(d.__filepath__)}`,h),ie(g,500),s.end("")}return}if(I){try{await we(c,C),await I(k,g,i)}catch(h){P.error(`${_.red("[response error]")} ${n.url}
`,`file: ${_.cyan(d.__filepath__)}`,h),ie(g,500),s.end("")}return}s.end("")}}function at(t,{pathname:o,method:e,request:r}){return t.find(n=>{if(!o||!n||!n.url||n.ws===!0||!(n.method?v(n.method)?n.method:[n.method]:["GET","POST"]).includes(e))return!1;let i=Se(n.url).test(o);if(i&&n.validator){let c=J(n.url,o);if(W(n.validator))return n.validator({params:c,...r});try{return Me({params:c,...r},n.validator)}catch(a){return P.error(`${_.red("[validator error]")} ${o}
`,`file: ${_.cyan(n.__filepath__)}`,a),!1}}return i})}function ie(t,o=200,e){t.statusCode=o,t.statusMessage=e||mt(o)}async function pt(t,o,e){let{headers:r,type:n="json"}=e,s=e.__filepath__,i=q.contentType(n)||q.contentType(q.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=W(r)?await r(t):r;Object.keys(c).forEach(a=>{o.setHeader(a,c[a])})}catch(c){P.error(`${_.red("[headers error]")} ${t.url}
`,c)}}async function lt(t,o,{cookies:e}){if(e)try{let r=W(e)?await e(t):e;Object.keys(r).forEach(n=>{let s=r[n];if(v(s)){let[i,c]=s;o.setCookie(n,i,c)}else o.setCookie(n,s)})}catch(r){P.error(`${_.red("[cookies error]")} ${t.url}
`,r)}}function ut(t,o,e){if(fe(o))o.pipe(t);else if(xe.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"?xe.from(r):r)}}async function we(t,o){if(!o||typeof o=="number"&&o<=0||v(o)&&o.length!==2)return;let e=0;if(v(o)){let[r,n]=o;e=Math.floor(Math.random()*(n-r+1))+r}else e=o-(Date.now()-t);e>0&&await ke(e)}function mt(t){return st[t]||"Unknown"}import kt from"node:events";import ce from"node:fs";import{createRequire as gt}from"node:module";import Pe from"node:path";import{pathToFileURL as yt}from"node:url";import je from"chokidar";import{build as ht}from"esbuild";import vt from"fast-glob";import{createFilter as Mt,normalizePath as z}from"vite";import dt from"lodash.sortby";function Ce(t){let o=[];for(let[,r]of t.entries())r&&(v(r)?o.push(...r):o.push(r));let e={};return o.filter(r=>N(r)&&r.enabled!==!1&&r.url).forEach(r=>{let{pathname:n,query:s}=j(r.url),i=e[n]??=[],c={...r,url:n};if(c.ws!==!0){let a=c.validator;re(s)||(W(a)?c.validator=function(p){return E(p.query,s)&&a(p)}: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]=dt(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return!s||re(s)?2:W(s)?0:1/Object.keys(s).reduce((c,a)=>c+ft(s[a]),0)})}),e}function ft(t){return t?Object.keys(t).length:0}var bt=ge(import.meta.url),F=gt(bt),ee=class extends kt{constructor(e){super();this.options=e;this.cwd=e.cwd||process.cwd();try{let r=B(this.cwd,["package.json"]);this.moduleType=r&&JSON.parse(r).type==="module"?"esm":"cjs"}catch{}}moduleCache=new Map;moduleDeps=new Map;cwd;mockWatcher;depsWatcher;moduleType="cjs";_mockData={};get mockData(){return this._mockData}load(){let{include:e,exclude:r}=this.options,n=Mt(e,r,{resolve:!1});vt(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=je.watch(r,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=z(i),this.emit("mock:update",i),D("watcher:add",i)}),s.on("change",async i=>{i=z(i),this.emit("mock:update",i),D("watcher:change",i)}),s.on("unlink",async i=>{i=z(i),this.emit("mock:unlink",i),D("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=je.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=z(r);let n=this.moduleDeps.get(r);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",r=>{r=z(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=Ce(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=>{v(i[a])?c.push(...i[a]):c.push(i[a])})),v(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=`${yt(s)}.mjs`;await ce.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{ce.unlinkSync(i)}catch{}}}else{e=Pe.resolve(this.cwd,e);let s=Pe.extname(e),i=ce.realpathSync(e),c=s in F.extensions?s:".js",a=F.extensions[c];F.extensions[c]=(f,M)=>{M===i?f._compile(r,M):a(f,M)},delete F.cache[F.resolve(e)];let p=F(e);return F.extensions[c]=a,p.__esModule?p:{default:p}}}async transformWithEsbuild(e,r){var n;try{let s=await ht({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:[Y(this.options.alias),V,X,K]});return{code:s.outputFiles[0].text,deps:((n=s.metafile)==null?void 0:n.inputs)||{}}}catch(s){console.error(s)}return{code:"",deps:{}}}};import xt from"cookies";import{pathToRegexp as Re}from"path-to-regexp";import wt from"picocolors";import{WebSocketServer as St}from"ws";function De(t,o,e,r){var L;let n=new Map,s=new Map,i=new WeakMap,c=l=>{let u=s.get(l);return!u&&s.set(l,u=new Map),u},a=(l,u)=>{let m=l.get(u);return!m&&l.set(u,m=new St({noServer:!0})),m},p=(l,u)=>{let m=n.get(l);!m&&n.set(l,m=new Set),m.add(u)},f=(l,u,m,d,k,g)=>{var y;try{(y=m.setup)==null||y.call(m,u,d),u.on("close",()=>l.delete(k))}catch(C){P.error(`${wt.red("[websocket server error]")} ${g}
`,C)}},M=(l,u,m,d)=>{l.emit("connection",u,m),u.on("close",()=>{let k=d.findIndex(g=>g.ws===u);k!==-1&&d.splice(k,1)})},O=(l,u,m,d,k)=>{let{cleanupList:g,connectionList:y,context:C}=i.get(u);We(g),y.forEach(({ws:R})=>R.removeAllListeners()),u.removeAllListeners(),f(l,u,m,C,d,k),y.forEach(({ws:R,req:I})=>M(u,R,I,y))};(L=t.on)==null||L.call(t,"mock:update-end",l=>{if(!n.has(l))return;let u=n.get(l);if(u)for(let m of u.values())for(let d of t.mockData[m]){if(!d.ws||d.__filepath__!==l)return;let k=c(m);for(let[g,y]of k.entries())O(k,y,d,g,l)}}),o==null||o.on("upgrade",(l,u,m)=>{let{pathname:d,query:k}=j(l.url);if(!d||e.length===0||!e.some(b=>H(b,l.url)))return;let g=t.mockData,y=Object.keys(g).find(b=>Re(b).test(d));if(!y)return;let C=g[y].find(b=>b.url&&b.ws&&Re(b.url).test(d));if(!C)return;let R=C.__filepath__;p(R,y);let I=c(y),$=a(I,d),T=i.get($);if(!T){let b=[],pe={onCleanup:Le=>b.push(Le)};T={cleanupList:b,context:pe,connectionList:[]},i.set($,T),f(I,$,C,pe,d,R)}let h=l,A=new xt(l,l,r),{query:_e}=j(l.headers.referer||"");h.query=k,h.refererQuery=_e,h.params=J(y,d),h.getCookie=A.get.bind(A),$.handleUpgrade(h,u,m,b=>{D(`websocket-mock: ${l.url} connected`),T.connectionList.push({req:h,ws:b}),M($,b,h,T.connectionList)})}),o==null||o.on("close",()=>{for(let l of s.values()){for(let u of l.values()){let m=i.get(u);We(m.cleanupList),u.close()}l.clear()}s.clear(),n.clear()})}function We(t){let o;for(;o=t.shift();)o==null||o()}function ae(t,o,e,r){let n=new ee({include:S(o.include),exclude:S(o.exclude),define:Q(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}=G(t.server.proxy||{}),c=[...S(o.prefix),...s];De(n,e,S(o.wsPrefix),o.cookiesOptions);let a=[];return a.push(Pt(n,c,t,o),Oe(n,{formidableOptions:o.formidableOptions,proxies:c,cookiesOptions:o.cookiesOptions})),a.filter(Boolean)}function Pt(t,o,e,r){let n={},s=r.cors!==!1||e.server.cors!==!1;return e.server.cors!==!1&&(n={...n,...typeof e.server.cors=="boolean"?{}:e.server.cors}),r.cors!==!1&&(n={...n,...typeof r.cors=="boolean"?{}:r.cors}),s?function(i,c,a){let{pathname:p}=j(i.url);if(!p||o.length===0||!o.some(O=>H(O,i.url)))return a();let f=t.mockData;if(!Object.keys(f).find(O=>Ct(O).test(p)))return a();Ot(n)(i,c,a)}:void 0}function Ee({prefix:t=[],wsPrefix:o=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:n=!1,cors:s=!0,formidableOptions:i={},build:c=!1,cookiesOptions:a={}}={}){let p={prefix:t,wsPrefix:o,include:e,exclude:r,reload:n,cors:s,cookiesOptions:a,formidableOptions:{multiples:!0,...i},build:c?Object.assign({serverPort:8080,dist:"mockServer"},typeof c=="object"?c:{}):!1},f=[Rt(p)];return p.build&&f.push(jt(p)),f}function jt(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 he(this,o,t)}}}function Rt(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var s;let r=S(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("")},configureServer({middlewares:e,config:r,httpServer:n,ws:s}){ae(r,t,n,s).forEach(c=>e.use(c))},configurePreviewServer({middlewares:e,httpServer:r}){ae(o,t,r).forEach(s=>e.use(s))}}}function fr(t){return t}function kr(t){return e=>(v(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var vr=Ee;export{Oe as baseMiddleware,kr as createDefineMock,vr as default,fr as defineMock,Ee as mockDevServerPlugin,De as mockWebSocket,Ce as transformMockData};
{
"name": "vite-plugin-mock-dev-server",
"version": "1.1.16",
"version": "1.2.0",
"keywords": [

@@ -9,3 +9,4 @@ "vite",

"mock",
"mock-server"
"mock-server",
"development"
],

@@ -39,6 +40,7 @@ "homepage": "https://vite-plugin-mock-dev-server.netlify.app",

"cookies": "^0.8.0",
"cors": "^2.8.5",
"debug": "^4.3.4",
"esbuild": "^0.17.19",
"esbuild": "^0.18.4",
"fast-glob": "^3.2.12",
"formidable": "^2.1.1",
"formidable": "^3.4.0",
"http-status": "^1.6.2",

@@ -54,7 +56,8 @@ "is-core-module": "^2.12.1",

"devDependencies": {
"@pengzhanbo/eslint-config": "^0.3.12",
"@pengzhanbo/prettier-config": "^0.3.12",
"@pengzhanbo/eslint-config": "^0.3.14",
"@pengzhanbo/prettier-config": "^0.3.14",
"@types/co-body": "^6.1.0",
"@types/cookies": "^0.7.7",
"@types/debug": "^4.1.7",
"@types/cors": "^2.8.13",
"@types/debug": "^4.1.8",
"@types/formidable": "^2.0.6",

@@ -64,13 +67,13 @@ "@types/is-core-module": "^2.2.0",

"@types/mime-types": "^2.1.1",
"@types/node": "^18.16.13",
"@types/ws": "^8.5.4",
"bumpp": "^9.1.0",
"conventional-changelog-cli": "^2.2.2",
"eslint": "^8.41.0",
"@types/node": "^18.16.18",
"@types/ws": "^8.5.5",
"bumpp": "^9.1.1",
"conventional-changelog-cli": "^3.0.0",
"eslint": "^8.43.0",
"mockjs": "^1.1.0",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vite": "^4.3.8",
"vitepress": "1.0.0-alpha.76"
"tsup": "^7.0.0",
"typescript": "^5.1.3",
"vite": "^4.3.9",
"vitepress": "1.0.0-beta.2"
},

@@ -80,3 +83,3 @@ "peerDependencies": {

},
"packageManager": "pnpm@8.5.0",
"packageManager": "pnpm@8.6.2",
"engines": {

@@ -83,0 +86,0 @@ "node": "^14.18.0 || >=16"

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

`mock/api.mock.ts` :
`mock/**/*.mock.ts` :
``` ts

@@ -104,0 +104,0 @@ import { defineMock } from 'vite-plugin-mock-dev-server'

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

`mock/api.mock.ts` :
`mock/**/*.mock.ts` :
```ts

@@ -104,0 +104,0 @@ import { defineMock } from 'vite-plugin-mock-dev-server'

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