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.3.0 to 1.3.1

19

dist/index.d.ts

@@ -499,2 +499,19 @@ import { LogLevel, Connect, Plugin, ResolvedConfig } from 'vite';

type MockData<T = any> = readonly [
/**
* getter
*/
() => T,
/**
* setter
*/
(val: T | ((val: T) => T | void)) => void
] & {
/**
* @property getter/setter
*/
value: T;
};
declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
interface Logger {

@@ -571,2 +588,2 @@ info(msg: string, level?: boolean | LogLevel): void;

export { BaseMiddlewareOptions, FormidableFile, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockSocketOptions, MockWebsocketItem, baseMiddleware, createDefineMock, mockDevServerPlugin as default, defineMock, mockDevServerPlugin, mockWebSocket, transformMockData };
export { BaseMiddlewareOptions, FormidableFile, MockData, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockSocketOptions, MockWebsocketItem, baseMiddleware, createDefineMock, mockDevServerPlugin as default, defineMock, defineMockData, mockDevServerPlugin, mockWebSocket, transformMockData };

20

dist/index.js

@@ -1,2 +0,2 @@

import{toArray as Jt}from"@pengzhanbo/utils";import rt from"node:fs";import K from"node:fs/promises";import H from"node:path";import{toArray as X}from"@pengzhanbo/utils";import nt from"fast-glob";import st from"is-core-module";import{createFilter as it,normalizePath as ct}from"vite";var me="vite-plugin-mock-dev-server",ue="1.3.0";import ge,{promises as se}from"node:fs";import{createRequire as Ae}from"node:module";import ne from"node:path";import{pathToFileURL as ze}from"node:url";import{build as Ge}from"esbuild";import Qe from"json5";import oe from"node:fs";import re from"node:path";import{parse as He}from"node:querystring";import{URL as Fe,fileURLToPath as qe}from"node:url";import Ue from"debug";import{match as Be}from"path-to-regexp";var Je=o=>o!==null&&typeof o=="object"&&typeof o.pipe=="function",de=o=>Je(o)&&o.readable!==!1&&typeof o._read=="function"&&typeof o._readableState=="object";function fe(o){return re.dirname(qe(o))}var A=Ue("vite:mock-dev-server");function q(o,t,e){for(let s of t){let r=re.join(o,s);if(oe.existsSync(r)&&oe.statSync(r).isFile()){let i=e!=null&&e.pathOnly?r:oe.readFileSync(r,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let n=re.dirname(o);if(n!==o&&(!(e!=null&&e.rootDir)||n.startsWith(e==null?void 0:e.rootDir)))return q(n,t,e)}var z=(o={})=>{let t=[],e=[];return Object.keys(o).forEach(n=>{var r,i;let s=o[n];typeof s=="string"||!s.ws&&!((r=s.target)!=null&&r.toString().startsWith("ws:"))&&!((i=s.target)!=null&&i.toString().startsWith("wss:"))?t.push(n):e.push(n)}),{httpProxies:t,wsProxies:e}};function N(o,t){return o[0]==="^"&&new RegExp(o).test(t)||t.startsWith(o)}function U(o,t){return(Be(o,{decode:decodeURIComponent})(t)||{params:{}}).params||{}}function R(o){let t=new Fe(o,"http://example.com"),e=decodeURIComponent(t.pathname),n=He(t.search.replace(/^\?/,""));return{pathname:e,query:n}}var Ve={name:"externalize-deps",setup(o){o.onResolve({filter:/.*/},({path:t})=>{if(t[0]!=="."&&!ne.isAbsolute(t))return{external:!0}})}},Ke={name:"json5-loader",setup(o){o.onLoad({filter:/\.json5$/},async({path:t})=>{let e=await se.readFile(t,"utf-8");return{contents:`export default ${JSON.stringify(Qe.parse(e))}`,loader:"js"}})}},Xe={name:"json-loader",setup(o){o.onLoad({filter:/\.json$/},async({path:t})=>({contents:`export default ${await se.readFile(t,"utf-8")}`,loader:"js"}))}},Ye=o=>({name:"alias-plugin",setup(t){t.onResolve({filter:/.*/},async({path:e})=>{let n=o.find(({find:c})=>Ze(c,e));if(!n)return null;let{find:s,replacement:r}=n;return{path:(await t.resolve(e.replace(s,r),{kind:"import-statement",resolveDir:r,namespace:"file"})).path,external:!1}})}});function Ze(o,t){return o instanceof RegExp?o.test(t):t.length<o.length?!1:t===o?!0:t.startsWith(`${o}/`)}async function G(o,t){var r;let{isESM:e=!0,define:n,alias:s}=t;try{let i=await Ge({entryPoints:[o],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:e?"esm":"cjs",define:n,plugins:[Ye(s),Ve,Xe,Ke]});return{code:i.outputFiles[0].text,deps:((r=i.metafile)==null?void 0:r.inputs)||{}}}catch(i){console.error(i)}return{code:"",deps:{}}}var et=fe(import.meta.url),_=Ae(et);async function ke(o,t,e,n){if(e){let s=`${o}.timestamp-${Date.now()}`,r=`${s}.mjs`,i=`${ze(s)}.mjs`;await se.writeFile(r,t,"utf8");try{return await import(i)}finally{try{ge.unlinkSync(r)}catch{}}}else{o=ne.resolve(n,o);let s=ne.extname(o),r=ge.realpathSync(o),i=s in _.extensions?s:".js",c=_.extensions[i];_.extensions[i]=(p,m)=>{m===r?p._compile(t,m):c(p,m)},delete _.cache[_.resolve(o)];let a=_(o);return _.extensions[i]=c,a.__esModule?a:{default:a}}}import he from"picocolors";import{isBoolean as tt}from"@pengzhanbo/utils";import I from"picocolors";var ye={silent:0,error:1,warn:2,info:3};function Q(o,t="info"){o=`[${o}]`;function e(s,r,i){if(i=tt(i)?i?t:"error":i,ye[i]>=ye[s]){let a=s==="info"?"log":s,p=s==="info"?I.cyan(I.bold(o)):s==="warn"?I.yellow(I.bold(o)):I.red(I.bold(o)),m=`${I.dim(new Date().toLocaleTimeString())} ${p} ${r}`;console[a](m)}}return{info(s,r=t){e("info",s,r)},warn(s,r=t){e("warn",s,r)},error(s,r=t){e("error",s,r)}}}var ot=/import\.meta\.env\.(.+)/;function V(o){let t=Q("vite:mock-dev-server","warn"),e={},n=process.env.NODE_ENV||o.mode;Object.assign(e,{"process.env.NODE_ENV":JSON.stringify(n),"global.process.env.NODE_ENV":JSON.stringify(n),"globalThis.process.env.NODE_ENV":JSON.stringify(n),__vite_process_env_NODE_ENV:JSON.stringify(n)});let s={},r={},i=[];for(let p in o.define){let m=o.define[p];if(typeof m=="string")try{JSON.parse(m),s[p]=m}catch{i.push(p)}else s[p]=JSON.stringify(m);let k=p.match(ot);k&&s[p]&&(r[k[1]]=`__vite__define__${s[p]}`)}i.length&&t.warn(`The following keys: ${he.yellow(he.underline(i.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let c={},a={};c["import.meta.hot"]="undefined";for(let p in o.env)c[`import.meta.env.${p}`]=JSON.stringify(o.env[p]);return Object.assign(a,{"import.meta.env":JSON.stringify({...o.env,...r}).replace(/"__vite__define__(.+?)"([,}])/g,(p,m,k)=>`${m.replace(/(^\\")|(\\"$)/g,'"')}${k}`)}),{...c,...s,...a,...e}}async function ve(o,t,e){let n=X(e.include),s=X(e.exclude),r=V(t),{httpProxies:i}=z(t.server.proxy||{});i.push(...X(e.prefix));let c=X(e.wsPrefix),a={};try{let u=q(t.root,["package.json"]);u&&(a=JSON.parse(u))}catch{}let p=e.build.dist,m=await mt(process.cwd(),n,s),k=H.join(t.root,`mock-data-${Date.now()}.js`);await K.writeFile(k,m,"utf-8");let{code:w,deps:j}=await G(k,{define:r,alias:t.resolve.alias}),P=at(j);await K.unlink(k);let l=[{filename:H.join(p,"mock-data.js"),source:w},{filename:H.join(p,"index.js"),source:lt(i,c,e.cookiesOptions,e.build.serverPort)},{filename:H.join(p,"package.json"),source:pt(a,P)}];try{if(H.isAbsolute(p)){await K.rm(p,{recursive:!0}),rt.mkdirSync(p,{recursive:!0});for(let{filename:u,source:d}of l)await K.writeFile(u,d,"utf-8")}else for(let{filename:u,source:d}of l)o.emitFile({type:"asset",fileName:u,source:d})}catch{}}function at(o){let t=new Set,e=[me,"connect","cors"];return Object.keys(o).forEach(n=>{o[n].imports.filter(r=>r.external&&!r.path.startsWith("<define:")).map(r=>r.path).forEach(r=>{!e.includes(r)&&!st(r)&&t.add(r)})}),Array.from(t)}function pt(o,t){let{dependencies:e={},devDependencies:n={}}=o,s={...e,...n},r={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ue}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return t.forEach(i=>{r.dependencies[i]=s[i]||"latest"}),JSON.stringify(r,null,2)}function lt(o,t,e={},n=8080){return`import { createServer } from 'node:http';
import{toArray as Qt}from"@pengzhanbo/utils";import ct from"node:fs";import K from"node:fs/promises";import F from"node:path";import{toArray as X}from"@pengzhanbo/utils";import at from"fast-glob";import pt from"is-core-module";import{createFilter as lt,normalizePath as mt}from"vite";var fe="vite-plugin-mock-dev-server",ge="1.3.1";import he,{promises as se}from"node:fs";import{createRequire as Ve}from"node:module";import ne from"node:path";import{pathToFileURL as Ke}from"node:url";import{build as Xe}from"esbuild";import Ye from"json5";import oe from"node:fs";import re from"node:path";import{parse as Be}from"node:querystring";import{URL as Je,fileURLToPath as Ae}from"node:url";import ze from"debug";import{match as Ge}from"path-to-regexp";var Qe=o=>o!==null&&typeof o=="object"&&typeof o.pipe=="function",ke=o=>Qe(o)&&o.readable!==!1&&typeof o._read=="function"&&typeof o._readableState=="object";function ye(o){return re.dirname(Ae(o))}var A=ze("vite:mock-dev-server");function U(o,t,e){for(let s of t){let r=re.join(o,s);if(oe.existsSync(r)&&oe.statSync(r).isFile()){let i=e!=null&&e.pathOnly?r:oe.readFileSync(r,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let n=re.dirname(o);if(n!==o&&(!(e!=null&&e.rootDir)||n.startsWith(e==null?void 0:e.rootDir)))return U(n,t,e)}var z=(o={})=>{let t=[],e=[];return Object.keys(o).forEach(n=>{var r,i;let s=o[n];typeof s=="string"||!s.ws&&!((r=s.target)!=null&&r.toString().startsWith("ws:"))&&!((i=s.target)!=null&&i.toString().startsWith("wss:"))?t.push(n):e.push(n)}),{httpProxies:t,wsProxies:e}};function N(o,t){return o[0]==="^"&&new RegExp(o).test(t)||t.startsWith(o)}function q(o,t){return(Ge(o,{decode:decodeURIComponent})(t)||{params:{}}).params||{}}function R(o){let t=new Je(o,"http://example.com"),e=decodeURIComponent(t.pathname),n=Be(t.search.replace(/^\?/,""));return{pathname:e,query:n}}var Ze={name:"externalize-deps",setup(o){o.onResolve({filter:/.*/},({path:t})=>{if(t[0]!=="."&&!ne.isAbsolute(t))return{external:!0}})}},et={name:"json5-loader",setup(o){o.onLoad({filter:/\.json5$/},async({path:t})=>{let e=await se.readFile(t,"utf-8");return{contents:`export default ${JSON.stringify(Ye.parse(e))}`,loader:"js"}})}},tt={name:"json-loader",setup(o){o.onLoad({filter:/\.json$/},async({path:t})=>({contents:`export default ${await se.readFile(t,"utf-8")}`,loader:"js"}))}},ot=o=>({name:"alias-plugin",setup(t){t.onResolve({filter:/.*/},async({path:e})=>{let n=o.find(({find:c})=>rt(c,e));if(!n)return null;let{find:s,replacement:r}=n;return{path:(await t.resolve(e.replace(s,r),{kind:"import-statement",resolveDir:r,namespace:"file"})).path,external:!1}})}});function rt(o,t){return o instanceof RegExp?o.test(t):t.length<o.length?!1:t===o?!0:t.startsWith(`${o}/`)}async function G(o,t){var r;let{isESM:e=!0,define:n,alias:s}=t;try{let i=await Xe({entryPoints:[o],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:e?"esm":"cjs",define:n,plugins:[ot(s),Ze,tt,et]});return{code:i.outputFiles[0].text,deps:((r=i.metafile)==null?void 0:r.inputs)||{}}}catch(i){console.error(i)}return{code:"",deps:{}}}var nt=ye(import.meta.url),_=Ve(nt);async function ve(o,t,e,n){if(e){let s=`${o}.timestamp-${Date.now()}`,r=`${s}.mjs`,i=`${Ke(s)}.mjs`;await se.writeFile(r,t,"utf8");try{return await import(i)}finally{try{he.unlinkSync(r)}catch{}}}else{o=ne.resolve(n,o);let s=ne.extname(o),r=he.realpathSync(o),i=s in _.extensions?s:".js",c=_.extensions[i];_.extensions[i]=(p,m)=>{m===r?p._compile(t,m):c(p,m)},delete _.cache[_.resolve(o)];let a=_(o);return _.extensions[i]=c,a.__esModule?a:{default:a}}}import be from"picocolors";import{isBoolean as st}from"@pengzhanbo/utils";import I from"picocolors";var Me={silent:0,error:1,warn:2,info:3};function Q(o,t="info"){o=`[${o}]`;function e(s,r,i){if(i=st(i)?i?t:"error":i,Me[i]>=Me[s]){let a=s==="info"?"log":s,p=s==="info"?I.cyan(I.bold(o)):s==="warn"?I.yellow(I.bold(o)):I.red(I.bold(o)),m=`${I.dim(new Date().toLocaleTimeString())} ${p} ${r}`;console[a](m)}}return{info(s,r=t){e("info",s,r)},warn(s,r=t){e("warn",s,r)},error(s,r=t){e("error",s,r)}}}var it=/import\.meta\.env\.(.+)/;function V(o){let t=Q("vite:mock-dev-server","warn"),e={},n=process.env.NODE_ENV||o.mode;Object.assign(e,{"process.env.NODE_ENV":JSON.stringify(n),"global.process.env.NODE_ENV":JSON.stringify(n),"globalThis.process.env.NODE_ENV":JSON.stringify(n),__vite_process_env_NODE_ENV:JSON.stringify(n)});let s={},r={},i=[];for(let p in o.define){let m=o.define[p];if(typeof m=="string")try{JSON.parse(m),s[p]=m}catch{i.push(p)}else s[p]=JSON.stringify(m);let k=p.match(it);k&&s[p]&&(r[k[1]]=`__vite__define__${s[p]}`)}i.length&&t.warn(`The following keys: ${be.yellow(be.underline(i.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let c={},a={};c["import.meta.hot"]="undefined";for(let p in o.env)c[`import.meta.env.${p}`]=JSON.stringify(o.env[p]);return Object.assign(a,{"import.meta.env":JSON.stringify({...o.env,...r}).replace(/"__vite__define__(.+?)"([,}])/g,(p,m,k)=>`${m.replace(/(^\\")|(\\"$)/g,'"')}${k}`)}),{...c,...s,...a,...e}}async function xe(o,t,e){let n=X(e.include),s=X(e.exclude),r=V(t),{httpProxies:i}=z(t.server.proxy||{});i.push(...X(e.prefix));let c=X(e.wsPrefix),a={};try{let u=U(t.root,["package.json"]);u&&(a=JSON.parse(u))}catch{}let p=e.build.dist,m=await gt(process.cwd(),n,s),k=F.join(t.root,`mock-data-${Date.now()}.js`);await K.writeFile(k,m,"utf-8");let{code:w,deps:j}=await G(k,{define:r,alias:t.resolve.alias}),P=ut(j);await K.unlink(k);let l=[{filename:F.join(p,"mock-data.js"),source:w},{filename:F.join(p,"index.js"),source:ft(i,c,e.cookiesOptions,e.build.serverPort)},{filename:F.join(p,"package.json"),source:dt(a,P)}];try{if(F.isAbsolute(p)){await K.rm(p,{recursive:!0}),ct.mkdirSync(p,{recursive:!0});for(let{filename:u,source:d}of l)await K.writeFile(u,d,"utf-8")}else for(let{filename:u,source:d}of l)o.emitFile({type:"asset",fileName:u,source:d})}catch{}}function ut(o){let t=new Set,e=[fe,"connect","cors"];return Object.keys(o).forEach(n=>{o[n].imports.filter(r=>r.external&&!r.path.startsWith("<define:")).map(r=>r.path).forEach(r=>{!e.includes(r)&&!pt(r)&&t.add(r)})}),Array.from(t)}function dt(o,t){let{dependencies:e={},devDependencies:n={}}=o,s={...e,...n},r={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ge}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return t.forEach(i=>{r.dependencies[i]=s[i]||"latest"}),JSON.stringify(r,null,2)}function ft(o,t,e={},n=8080){return`import { createServer } from 'node:http';
import connect from 'connect';

@@ -25,3 +25,3 @@ import corsMiddleware from 'cors';

console.log('listen: http://localhost:${n}');
`}async function mt(o,t,e){let n=await nt(t,{cwd:o}),s=it(t,e,{resolve:!1}),r=n.filter(s),i="",c="";return r.forEach((a,p)=>{let m=ct(H.join(o,a));i+=`import * as m${p} from '${m}';
`}async function gt(o,t,e){let n=await at(t,{cwd:o}),s=lt(t,e,{resolve:!1}),r=n.filter(s),i="",c="";return r.forEach((a,p)=>{let m=mt(F.join(o,a));i+=`import * as m${p} from '${m}';
`,c+=`m${p}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server';

@@ -44,16 +44,16 @@ ${i}

});
export default transformMockData(mockList);`}import{isBoolean as Ft,toArray as te}from"@pengzhanbo/utils";import qt from"cors";import{pathToRegexp as Ut}from"path-to-regexp";import{Buffer as Oe}from"node:buffer";import{isArray as Y,isEmptyObject as ft,isFunction as Z,random as gt,sleep as kt,sortBy as yt,timestamp as Re}from"@pengzhanbo/utils";import ht from"cookies";import vt from"http-status";import*as B from"mime-types";import{pathToRegexp as Pe}from"path-to-regexp";import M from"picocolors";import ie from"co-body";import ut from"formidable";async function Me(o,t){var s;let e=o.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let n=((s=o.headers["content-type"])==null?void 0:s.toLocaleLowerCase())||"";try{if(n.startsWith("application/json"))return await ie.json(o);if(n.startsWith("application/x-www-form-urlencoded"))return await ie.form(o);if(n.startsWith("text/plain"))return await ie.text(o);if(n.startsWith("multipart/form-data"))return await dt(o,t)}catch(r){console.error(r)}}async function dt(o,t){let e=ut(t);return new Promise((n,s)=>{e.parse(o,(r,i,c)=>{if(r){s(r);return}n({...i,...c})})})}import{isArray as be,isObject as xe}from"@pengzhanbo/utils";function we(o,t){return L(o.headers,t.headers)&&L(o.body,t.body)&&L(o.params,t.params)&&L(o.query,t.query)&&L(o.refererQuery,t.refererQuery)}function L(o,t){if(!t)return!0;for(let e in t)if(!Se(o[e],t[e]))return!1;return!0}function Se(o,t){if(be(o)&&be(t)){let e=new Set;return t.every(n=>o.some((s,r)=>{if(e.has(r))return!1;let i=Se(s,n);return i&&e.add(r),i}))}return xe(o)&&xe(t)?L(o,t):Object.is(o,t)}var Mt=/:/g;function We(o,{formidableOptions:t={},proxies:e,cookiesOptions:n,logger:s}){return async function(r,i,c){let a=Re(),{query:p,pathname:m}=R(r.url);if(!m||e.length===0||!e.some(O=>N(O,r.url)))return c();let k=o.mockData,w=yt(Object.keys(k),O=>{var v;return((v=O.match(Mt))==null?void 0:v.length)||0}).find(O=>Pe(O).test(m));if(!w)return c();let{query:j}=R(r.headers.referer||""),P=await Me(r,t),l=new ht(r,i,n),u=l.get.bind(l),d=r.method.toUpperCase(),f=bt(k[w],s,{pathname:m,method:d,request:{query:p,refererQuery:j,body:P,headers:r.headers,getCookie:u}});if(!f)return c();let g=r,y=i;g.body=P,g.query=p,g.refererQuery=j,g.params=U(f.url,m),g.getCookie=u,y.setCookie=l.set.bind(l);let{body:h,delay:S,type:W="json",response:E,status:$=200,statusText:D,log:C,__filepath__:T}=f;if(ce(y,$,D),await xt(g,y,f,s),await wt(g,y,f,s),s.info(Ct(g,T),C),h){try{let O=Z(h)?await h(g):h;await Ce(a,S),St(y,O,W)}catch(O){s.error(`${M.red(`mock error at ${m}`)}
export default transformMockData(mockList);`}import{isBoolean as Jt,toArray as te}from"@pengzhanbo/utils";import At from"cors";import{pathToRegexp as zt}from"path-to-regexp";import{Buffer as Pe}from"node:buffer";import{isArray as Y,isEmptyObject as ht,isFunction as Z,random as vt,sleep as Mt,sortBy as bt,timestamp as je}from"@pengzhanbo/utils";import xt from"cookies";import wt from"http-status";import*as B from"mime-types";import{pathToRegexp as De}from"path-to-regexp";import M from"picocolors";import ie from"co-body";import kt from"formidable";async function we(o,t){var s;let e=o.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let n=((s=o.headers["content-type"])==null?void 0:s.toLocaleLowerCase())||"";try{if(n.startsWith("application/json"))return await ie.json(o);if(n.startsWith("application/x-www-form-urlencoded"))return await ie.form(o);if(n.startsWith("text/plain"))return await ie.text(o);if(n.startsWith("multipart/form-data"))return await yt(o,t)}catch(r){console.error(r)}}async function yt(o,t){let e=kt(t);return new Promise((n,s)=>{e.parse(o,(r,i,c)=>{if(r){s(r);return}n({...i,...c})})})}import{isArray as Se,isObject as Oe}from"@pengzhanbo/utils";function Ce(o,t){return D(o.headers,t.headers)&&D(o.body,t.body)&&D(o.params,t.params)&&D(o.query,t.query)&&D(o.refererQuery,t.refererQuery)}function D(o,t){if(!t)return!0;for(let e in t)if(!Re(o[e],t[e]))return!1;return!0}function Re(o,t){if(Se(o)&&Se(t)){let e=new Set;return t.every(n=>o.some((s,r)=>{if(e.has(r))return!1;let i=Re(s,n);return i&&e.add(r),i}))}return Oe(o)&&Oe(t)?D(o,t):Object.is(o,t)}var St=/:/g;function Le(o,{formidableOptions:t={},proxies:e,cookiesOptions:n,logger:s}){return async function(r,i,c){let a=je(),{query:p,pathname:m}=R(r.url);if(!m||e.length===0||!e.some(O=>N(O,r.url)))return c();let k=o.mockData,w=bt(Object.keys(k),O=>{var v;return((v=O.match(St))==null?void 0:v.length)||0}).find(O=>De(O).test(m));if(!w)return c();let{query:j}=R(r.headers.referer||""),P=await we(r,t),l=new xt(r,i,n),u=l.get.bind(l),d=r.method.toUpperCase(),f=Ot(k[w],s,{pathname:m,method:d,request:{query:p,refererQuery:j,body:P,headers:r.headers,getCookie:u}});if(!f)return c();let g=r,y=i;g.body=P,g.query=p,g.refererQuery=j,g.params=q(f.url,m),g.getCookie=u,y.setCookie=l.set.bind(l);let{body:h,delay:S,type:W="json",response:L,status:E=200,statusText:$,log:C,__filepath__:T}=f;if(ce(y,E,$),await Ct(g,y,f,s),await Rt(g,y,f,s),s.info(jt(g,T),C),h){try{let O=Z(h)?await h(g):h;await We(a,S),Pt(y,O,W)}catch(O){s.error(`${M.red(`mock error at ${m}`)}
${O}
at body (${M.underline(T)})`,C),ce(y,500),i.end("")}return}if(E){try{await Ce(a,S),await E(g,y,c)}catch(O){s.error(`${M.red(`mock error at ${m}`)}
at body (${M.underline(T)})`,C),ce(y,500),i.end("")}return}if(L){try{await We(a,S),await L(g,y,c)}catch(O){s.error(`${M.red(`mock error at ${m}`)}
${O}
at response (${M.underline(T)})`,C),ce(y,500),i.end("")}return}i.end("")}}function bt(o,t,{pathname:e,method:n,request:s}){return o.find(r=>{if(!e||!r||!r.url||r.ws===!0||!(r.method?Y(r.method)?r.method:[r.method]:["GET","POST"]).includes(n))return!1;let c=Pe(r.url).test(e);if(c&&r.validator){let a=U(r.url,e);if(Z(r.validator))return r.validator({params:a,...s});try{return we({params:a,...s},r.validator)}catch(p){let m=r.__filepath__;return t.error(`${M.red(`mock error at ${e}`)}
at response (${M.underline(T)})`,C),ce(y,500),i.end("")}return}i.end("")}}function Ot(o,t,{pathname:e,method:n,request:s}){return o.find(r=>{if(!e||!r||!r.url||r.ws===!0||!(r.method?Y(r.method)?r.method:[r.method]:["GET","POST"]).includes(n))return!1;let c=De(r.url).test(e);if(c&&r.validator){let a=q(r.url,e);if(Z(r.validator))return r.validator({params:a,...s});try{return Ce({params:a,...s},r.validator)}catch(p){let m=r.__filepath__;return t.error(`${M.red(`mock error at ${e}`)}
${p}
at validator (${M.underline(m)})`,r.log),!1}}return c})}function ce(o,t=200,e){o.statusCode=t,o.statusMessage=e||Ot(t)}async function xt(o,t,e,n){let{headers:s,type:r="json"}=e,i=e.__filepath__,c=B.contentType(r)||B.contentType(B.lookup(r)||"");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"),t.setHeader("X-File-Path",i),!!s)try{let a=Z(s)?await s(o):s;Object.keys(a).forEach(p=>{t.setHeader(p,a[p])})}catch(a){n.error(`${M.red(`mock error at ${o.url.split("?")[0]}`)}
at validator (${M.underline(m)})`,r.log),!1}}return c})}function ce(o,t=200,e){o.statusCode=t,o.statusMessage=e||Wt(t)}async function Ct(o,t,e,n){let{headers:s,type:r="json"}=e,i=e.__filepath__,c=B.contentType(r)||B.contentType(B.lookup(r)||"");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"),t.setHeader("X-File-Path",i),!!s)try{let a=Z(s)?await s(o):s;Object.keys(a).forEach(p=>{t.setHeader(p,a[p])})}catch(a){n.error(`${M.red(`mock error at ${o.url.split("?")[0]}`)}
${a}
at headers (${M.underline(i)})`,e.log)}}async function wt(o,t,e,n){let{cookies:s}=e,r=e.__filepath__;if(s)try{let i=Z(s)?await s(o):s;Object.keys(i).forEach(c=>{let a=i[c];if(Y(a)){let[p,m]=a;t.setCookie(c,p,m)}else t.setCookie(c,a)})}catch(i){n.error(`${M.red(`mock error at ${o.url.split("?")[0]}`)}
at headers (${M.underline(i)})`,e.log)}}async function Rt(o,t,e,n){let{cookies:s}=e,r=e.__filepath__;if(s)try{let i=Z(s)?await s(o):s;Object.keys(i).forEach(c=>{let a=i[c];if(Y(a)){let[p,m]=a;t.setCookie(c,p,m)}else t.setCookie(c,a)})}catch(i){n.error(`${M.red(`mock error at ${o.url.split("?")[0]}`)}
${i}
at cookies (${M.underline(r)})`,e.log)}}function St(o,t,e){if(de(t))t.pipe(o);else if(Oe.isBuffer(t))o.end(e==="text"||e==="json"?t.toString("utf-8"):t);else{let n=typeof t=="string"?t:JSON.stringify(t);o.end(e==="buffer"?Oe.from(n):n)}}async function Ce(o,t){if(!t||typeof t=="number"&&t<=0||Y(t)&&t.length!==2)return;let e=0;if(Y(t)){let[n,s]=t;e=gt(n,s)}else e=t-(Re()-o);e>0&&await kt(e)}function Ot(o){return vt[o]||"Unknown"}function Ct(o,t){let{url:e,method:n,query:s,params:r,body:i}=o,{pathname:c}=new URL(e,"http://example.com");c=M.green(decodeURIComponent(c));let a=(P,l)=>!l||ft(l)?"":` ${M.gray(`${P}:`)}${JSON.stringify(l)}`,p=M.magenta(M.bold(n)),m=a("query",s),k=a("params",r),w=a("body",i),j=` ${M.dim(M.underline(`(${t})`))}`;return`${p} ${c}${m}${k}${w}${j}`}import Lt from"node:events";import{hasOwn as Et,isArray as $t,promiseParallel as Dt,toArray as _t}from"@pengzhanbo/utils";import $e from"chokidar";import It from"fast-glob";import{createFilter as Tt,normalizePath as J}from"vite";import{isArray as Rt,isEmptyObject as je,isFunction as Le,isObject as Pt,sortBy as Wt}from"@pengzhanbo/utils";function Ee(o){let t=[];for(let[,n]of o.entries())n&&(Rt(n)?t.push(...n):t.push(n));let e={};return t.filter(n=>Pt(n)&&n.enabled!==!1&&n.url).forEach(n=>{let{pathname:s,query:r}=R(n.url),i=e[s]??=[],c={...n,url:s};if(c.ws!==!0){let a=c.validator;je(r)||(Le(a)?c.validator=function(p){return L(p.query,r)&&a(p)}:a?(c.validator={...a},c.validator.query=c.validator.query?{...r,...c.validator.query}:r):c.validator={query:r})}i.push(c)}),Object.keys(e).forEach(n=>{e[n]=Wt(e[n],s=>{if(s.ws===!0)return 0;let{validator:r}=s;return!r||je(r)?2:Le(r)?0:1/Object.keys(r).reduce((c,a)=>c+jt(r[a]),0)})}),e}function jt(o){return o?Object.keys(o).length:0}var ee=class extends Lt{constructor(e){super();this.options=e;this.cwd=e.cwd||process.cwd();try{let n=q(this.cwd,["package.json"]);this.moduleType=n&&JSON.parse(n).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:n}=this.options,s=Tt(e,n,{resolve:!1});It(e,{cwd:this.cwd}).then(i=>i.filter(s).map(c=>()=>this.loadMock(c))).then(i=>Dt(i,10)).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let r=null;this.on("mock:update",async i=>{s(i)&&(await this.loadMock(i),r&&clearImmediate(r),r=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),r=null}))}),this.on("mock:unlink",async i=>{s(i)&&(this.moduleCache.delete(i),this.updateMockList(),this.emit("mock:update-end",i))})}watchMockEntry(){let{include:e}=this.options,[n,...s]=e,r=$e.watch(n,{ignoreInitial:!0,cwd:this.cwd});s.length>0&&s.forEach(i=>r.add(i)),r.on("add",async i=>{i=J(i),this.emit("mock:update",i),A("watcher:add",i)}),r.on("change",async i=>{i=J(i),this.emit("mock:update",i),A("watcher:change",i)}),r.on("unlink",async i=>{i=J(i),this.emit("mock:unlink",i),A("watcher:unlink",i)}),this.mockWatcher=r}watchDeps(){let e=[];this.depsWatcher=$e.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",n=>{n=J(n);let s=this.moduleDeps.get(n);s&&s.forEach(r=>{this.emit("mock:update",r)})}),this.depsWatcher.on("unlink",n=>{n=J(n),this.moduleDeps.delete(n)}),this.on("update:deps",()=>{let n=[];for(let[r]of this.moduleDeps.entries())n.push(r);let s=n.filter(r=>!e.includes(r));s.length>0&&this.depsWatcher.add(s)})}close(){var e,n;(e=this.mockWatcher)==null||e.close(),(n=this.depsWatcher)==null||n.close()}updateMockList(){this._mockData=Ee(this.moduleCache)}updateModuleDeps(e,n){Object.keys(n).forEach(s=>{n[s].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 n=!1;/\.m[jt]s$/.test(e)?n=!0:/\.c[jt]s$/.test(e)?n=!1:n=this.moduleType==="esm";let{define:s,alias:r}=this.options,{code:i,deps:c}=await G(e,{isESM:n,define:s,alias:r});try{let a=await ke(e,i,n,this.cwd)||{},p;Et(a,"default")?p=a.default:(p=[],Object.keys(a).forEach(m=>p.push(..._t(a[m])))),$t(p)?p.forEach(m=>m.__filepath__=e):p.__filepath__=e,this.moduleCache.set(e,p),this.updateModuleDeps(e,c)}catch(a){console.error(a)}}};import Nt from"cookies";import{pathToRegexp as De}from"path-to-regexp";import F from"picocolors";import{WebSocketServer as Ht}from"ws";function Ie({loader:o,httpServer:t,proxies:e,cookiesOptions:n,logger:s}){var P;let r=new Map,i=new Map,c=new WeakMap,a=l=>{let u=i.get(l);return!u&&i.set(l,u=new Map),u},p=(l,u)=>{let d=l.get(u);return!d&&l.set(u,d=new Ht({noServer:!0})),d},m=(l,u)=>{let d=r.get(l);!d&&r.set(l,d=new Set),d.add(u)},k=(l,u,d,f,g,y)=>{var h;try{(h=d.setup)==null||h.call(d,u,f),u.on("close",()=>l.delete(g)),u.on("error",S=>{s.error(`${F.red(`WebSocket mock error at ${u.path}`)}
at cookies (${M.underline(r)})`,e.log)}}function Pt(o,t,e){if(ke(t))t.pipe(o);else if(Pe.isBuffer(t))o.end(e==="text"||e==="json"?t.toString("utf-8"):t);else{let n=typeof t=="string"?t:JSON.stringify(t);o.end(e==="buffer"?Pe.from(n):n)}}async function We(o,t){if(!t||typeof t=="number"&&t<=0||Y(t)&&t.length!==2)return;let e=0;if(Y(t)){let[n,s]=t;e=vt(n,s)}else e=t-(je()-o);e>0&&await Mt(e)}function Wt(o){return wt[o]||"Unknown"}function jt(o,t){let{url:e,method:n,query:s,params:r,body:i}=o,{pathname:c}=new URL(e,"http://example.com");c=M.green(decodeURIComponent(c));let a=(P,l)=>!l||ht(l)?"":` ${M.gray(`${P}:`)}${JSON.stringify(l)}`,p=M.magenta(M.bold(n)),m=a("query",s),k=a("params",r),w=a("body",i),j=` ${M.dim(M.underline(`(${t})`))}`;return`${p} ${c}${m}${k}${w}${j}`}import _t from"node:events";import{hasOwn as It,isArray as Tt,promiseParallel as Nt,toArray as Ft}from"@pengzhanbo/utils";import Ie from"chokidar";import Ht from"fast-glob";import{createFilter as Ut,normalizePath as J}from"vite";import{isArray as Dt,isEmptyObject as Ee,isFunction as $e,isObject as Lt,sortBy as Et}from"@pengzhanbo/utils";function _e(o){let t=[];for(let[,n]of o.entries())n&&(Dt(n)?t.push(...n):t.push(n));let e={};return t.filter(n=>Lt(n)&&n.enabled!==!1&&n.url).forEach(n=>{let{pathname:s,query:r}=R(n.url),i=e[s]??=[],c={...n,url:s};if(c.ws!==!0){let a=c.validator;Ee(r)||($e(a)?c.validator=function(p){return D(p.query,r)&&a(p)}:a?(c.validator={...a},c.validator.query=c.validator.query?{...r,...c.validator.query}:r):c.validator={query:r})}i.push(c)}),Object.keys(e).forEach(n=>{e[n]=Et(e[n],s=>{if(s.ws===!0)return 0;let{validator:r}=s;return!r||Ee(r)?2:$e(r)?0:1/Object.keys(r).reduce((c,a)=>c+$t(r[a]),0)})}),e}function $t(o){return o?Object.keys(o).length:0}var ee=class extends _t{constructor(e){super();this.options=e;this.cwd=e.cwd||process.cwd();try{let n=U(this.cwd,["package.json"]);this.moduleType=n&&JSON.parse(n).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:n}=this.options,s=Ut(e,n,{resolve:!1});Ht(e,{cwd:this.cwd}).then(i=>i.filter(s).map(c=>()=>this.loadMock(c))).then(i=>Nt(i,10)).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let r=null;this.on("mock:update",async i=>{s(i)&&(await this.loadMock(i),r&&clearImmediate(r),r=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),r=null}))}),this.on("mock:unlink",async i=>{s(i)&&(this.moduleCache.delete(i),this.updateMockList(),this.emit("mock:update-end",i))})}watchMockEntry(){let{include:e}=this.options,[n,...s]=e,r=this.mockWatcher=Ie.watch(n,{ignoreInitial:!0,cwd:this.cwd});s.length>0&&s.forEach(i=>r.add(i)),r.on("add",async i=>{i=J(i),this.emit("mock:update",i),A("watcher:add",i)}),r.on("change",async i=>{i=J(i),this.emit("mock:update",i),A("watcher:change",i)}),r.on("unlink",async i=>{i=J(i),this.emit("mock:unlink",i),A("watcher:unlink",i)})}watchDeps(){let e=[];this.depsWatcher=Ie.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",n=>{n=J(n);let s=this.moduleDeps.get(n);s&&s.forEach(r=>{this.emit("mock:update",r)})}),this.depsWatcher.on("unlink",n=>{n=J(n),this.moduleDeps.delete(n)}),this.on("update:deps",()=>{let n=[];for(let[r]of this.moduleDeps.entries())n.push(r);let s=n.filter(r=>!e.includes(r));s.length>0&&this.depsWatcher.add(s)})}close(){var e,n;(e=this.mockWatcher)==null||e.close(),(n=this.depsWatcher)==null||n.close()}updateMockList(){this._mockData=_e(this.moduleCache)}updateModuleDeps(e,n){Object.keys(n).forEach(s=>{n[s].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 n=!1;/\.m[jt]s$/.test(e)?n=!0:/\.c[jt]s$/.test(e)?n=!1:n=this.moduleType==="esm";let{define:s,alias:r}=this.options,{code:i,deps:c}=await G(e,{isESM:n,define:s,alias:r});try{let a=await ve(e,i,n,this.cwd)||{},p;It(a,"default")?p=a.default:(p=[],Object.keys(a).forEach(m=>p.push(...Ft(a[m])))),Tt(p)?p.forEach(m=>m.__filepath__=e):p.__filepath__=e,this.moduleCache.set(e,p),this.updateModuleDeps(e,c)}catch(a){console.error(a)}}};import qt from"cookies";import{pathToRegexp as Te}from"path-to-regexp";import H from"picocolors";import{WebSocketServer as Bt}from"ws";function Fe({loader:o,httpServer:t,proxies:e,cookiesOptions:n,logger:s}){var P;let r=new Map,i=new Map,c=new WeakMap,a=l=>{let u=i.get(l);return!u&&i.set(l,u=new Map),u},p=(l,u)=>{let d=l.get(u);return!d&&l.set(u,d=new Bt({noServer:!0})),d},m=(l,u)=>{let d=r.get(l);!d&&r.set(l,d=new Set),d.add(u)},k=(l,u,d,f,g,y)=>{var h;try{(h=d.setup)==null||h.call(d,u,f),u.on("close",()=>l.delete(g)),u.on("error",S=>{s.error(`${H.red(`WebSocket mock error at ${u.path}`)}
${S}
at setup (${y})`,d.log)})}catch(S){s.error(`${F.red(`WebSocket mock error at ${u.path}`)}
at setup (${y})`,d.log)})}catch(S){s.error(`${H.red(`WebSocket mock error at ${u.path}`)}
${S}
at setup (${y})`,d.log)}},w=(l,u,d,f)=>{l.emit("connection",u,d),u.on("close",()=>{let g=f.findIndex(y=>y.ws===u);g!==-1&&f.splice(g,1)})},j=(l,u,d,f,g)=>{let{cleanupList:y,connectionList:h,context:S}=c.get(u);_e(y),h.forEach(({ws:W})=>W.removeAllListeners()),u.removeAllListeners(),k(l,u,d,S,f,g),h.forEach(({ws:W,req:E})=>w(u,W,E,h))};(P=o.on)==null||P.call(o,"mock:update-end",l=>{if(!r.has(l))return;let u=r.get(l);if(u)for(let d of u.values())for(let f of o.mockData[d]){if(!f.ws||f.__filepath__!==l)return;let g=a(d);for(let[y,h]of g.entries())j(g,h,f,y,l)}}),t==null||t.on("upgrade",(l,u,d)=>{let{pathname:f,query:g}=R(l.url);if(!f||e.length===0||!e.some(v=>N(v,l.url)))return;let y=o.mockData,h=Object.keys(y).find(v=>De(v).test(f));if(!h)return;let S=y[h].find(v=>v.url&&v.ws&&De(v.url).test(f));if(!S)return;let W=S.__filepath__;m(W,h);let E=a(h),$=p(E,f),D=c.get($);if(!D){let v=[],pe={onCleanup:Ne=>v.push(Ne)};D={cleanupList:v,context:pe,connectionList:[]},c.set($,D),k(E,$,S,pe,f,W)}let C=l,T=new Nt(l,l,n),{query:O}=R(l.headers.referer||"");C.query=g,C.refererQuery=O,C.params=U(h,f),C.getCookie=T.get.bind(T),$.handleUpgrade(C,u,d,v=>{s.info(`${F.magenta(F.bold("WebSocket"))} ${F.green(l.url)} connected ${F.dim(`(${W})`)}`,S.log),D.connectionList.push({req:C,ws:v}),w($,v,C,D.connectionList)})}),t==null||t.on("close",()=>{for(let l of i.values()){for(let u of l.values()){let d=c.get(u);_e(d.cleanupList),u.close()}l.clear()}i.clear(),r.clear()})}function _e(o){let t;for(;t=o.shift();)t==null||t()}function ae(o,t,e,n){let s=Q("vite:mock",Ft(t.log)?t.log?"info":"error":t.log),r=new ee({include:te(t.include),exclude:te(t.exclude),define:V(o),alias:o.resolve.alias});r.load(),r.on("mock:update-end",()=>{t.reload&&(n==null||n.send({type:"full-reload"}))}),e==null||e.on("close",()=>r.close());let{httpProxies:i}=z(o.server.proxy||{}),a=[...te(t.prefix),...i];Ie({loader:r,httpServer:e,proxies:te(t.wsPrefix),cookiesOptions:t.cookiesOptions,logger:s});let p=[];return p.push(Bt(r,a,o,t),We(r,{formidableOptions:t.formidableOptions,proxies:a,cookiesOptions:t.cookiesOptions,logger:s})),p.filter(Boolean)}function Bt(o,t,e,n){let s={},r=n.cors===!1?!1:e.server.cors!==!1;return r&&e.server.cors!==!1&&(s={...s,...typeof e.server.cors=="boolean"?{}:e.server.cors}),r&&n.cors!==!1&&(s={...s,...typeof n.cors=="boolean"?{}:n.cors}),r?function(i,c,a){let{pathname:p}=R(i.url);if(!p||t.length===0||!t.some(w=>N(w,i.url)))return a();let m=o.mockData;if(!Object.keys(m).find(w=>Ut(w).test(p)))return a();qt(s)(i,c,a)}:void 0}function Te({prefix:o=[],wsPrefix:t=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:n=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:s=!1,log:r="info",cors:i=!0,formidableOptions:c={},build:a=!1,cookiesOptions:p={}}={}){let m={prefix:o,wsPrefix:t,include:e,exclude:n,reload:s,cors:i,cookiesOptions:p,log:r,formidableOptions:{multiples:!0,...c},build:a?Object.assign({serverPort:8080,dist:"mockServer"},typeof a=="object"?a:{}):!1},k=[zt(m)];return m.build&&k.push(At(m)),k}function At(o){let t={};return{name:"vite-plugin-mock-dev-server-generator",enforce:"post",apply:"build",configResolved(e){t=e,e.logger.warn("")},async buildEnd(e){e||t.command==="build"&&await ve(this,t,o)}}}function zt(o){let t={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var r;let n=Jt(o.wsPrefix);if(n.length===0||!((r=e.server)!=null&&r.proxy)||Object.keys(e.server.proxy).length===0)return;let s={};Object.keys(e.server.proxy).forEach(i=>{n.includes(i)||(s[i]=e.server.proxy[i])}),e.server.proxy=s},configResolved(e){t=e,e.logger.warn("")},configureServer({middlewares:e,config:n,httpServer:s,ws:r}){ae(n,o,s,r).forEach(c=>e.use(c))},configurePreviewServer({middlewares:e,httpServer:n}){ae(t,o,n).forEach(r=>e.use(r))}}}import{isArray as Gt}from"@pengzhanbo/utils";function Tr(o){return o}function Nr(o){return e=>(Gt(e)?e=e.map(n=>o(n)||n):e=o(e)||e,e)}var Ur=Te;export{We as baseMiddleware,Nr as createDefineMock,Ur as default,Tr as defineMock,Te as mockDevServerPlugin,Ie as mockWebSocket,Ee as transformMockData};
at setup (${y})`,d.log)}},w=(l,u,d,f)=>{l.emit("connection",u,d),u.on("close",()=>{let g=f.findIndex(y=>y.ws===u);g!==-1&&f.splice(g,1)})},j=(l,u,d,f,g)=>{let{cleanupList:y,connectionList:h,context:S}=c.get(u);Ne(y),h.forEach(({ws:W})=>W.removeAllListeners()),u.removeAllListeners(),k(l,u,d,S,f,g),h.forEach(({ws:W,req:L})=>w(u,W,L,h))};(P=o.on)==null||P.call(o,"mock:update-end",l=>{if(!r.has(l))return;let u=r.get(l);if(u)for(let d of u.values())for(let f of o.mockData[d]){if(!f.ws||f.__filepath__!==l)return;let g=a(d);for(let[y,h]of g.entries())j(g,h,f,y,l)}}),t==null||t.on("upgrade",(l,u,d)=>{let{pathname:f,query:g}=R(l.url);if(!f||e.length===0||!e.some(v=>N(v,l.url)))return;let y=o.mockData,h=Object.keys(y).find(v=>Te(v).test(f));if(!h)return;let S=y[h].find(v=>v.url&&v.ws&&Te(v.url).test(f));if(!S)return;let W=S.__filepath__;m(W,h);let L=a(h),E=p(L,f),$=c.get(E);if(!$){let v=[],ue={onCleanup:qe=>v.push(qe)};$={cleanupList:v,context:ue,connectionList:[]},c.set(E,$),k(L,E,S,ue,f,W)}let C=l,T=new qt(l,l,n),{query:O}=R(l.headers.referer||"");C.query=g,C.refererQuery=O,C.params=q(h,f),C.getCookie=T.get.bind(T),E.handleUpgrade(C,u,d,v=>{s.info(`${H.magenta(H.bold("WebSocket"))} ${H.green(l.url)} connected ${H.dim(`(${W})`)}`,S.log),$.connectionList.push({req:C,ws:v}),w(E,v,C,$.connectionList)})}),t==null||t.on("close",()=>{for(let l of i.values()){for(let u of l.values()){let d=c.get(u);Ne(d.cleanupList),u.close()}l.clear()}i.clear(),r.clear()})}function Ne(o){let t;for(;t=o.shift();)t==null||t()}function ae(o,t,e,n){let s=Q("vite:mock",Jt(t.log)?t.log?"info":"error":t.log),r=new ee({include:te(t.include),exclude:te(t.exclude),define:V(o),alias:o.resolve.alias});r.load(),r.on("mock:update-end",()=>{t.reload&&(n==null||n.send({type:"full-reload"}))}),e==null||e.on("close",()=>r.close());let{httpProxies:i}=z(o.server.proxy||{}),a=[...te(t.prefix),...i];Fe({loader:r,httpServer:e,proxies:te(t.wsPrefix),cookiesOptions:t.cookiesOptions,logger:s});let p=[];return p.push(Gt(r,a,o,t),Le(r,{formidableOptions:t.formidableOptions,proxies:a,cookiesOptions:t.cookiesOptions,logger:s})),p.filter(Boolean)}function Gt(o,t,e,n){let s={},r=n.cors===!1?!1:e.server.cors!==!1;return r&&e.server.cors!==!1&&(s={...s,...typeof e.server.cors=="boolean"?{}:e.server.cors}),r&&n.cors!==!1&&(s={...s,...typeof n.cors=="boolean"?{}:n.cors}),r?function(i,c,a){let{pathname:p}=R(i.url);if(!p||t.length===0||!t.some(w=>N(w,i.url)))return a();let m=o.mockData;if(!Object.keys(m).find(w=>zt(w).test(p)))return a();At(s)(i,c,a)}:void 0}function He({prefix:o=[],wsPrefix:t=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:n=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:s=!1,log:r="info",cors:i=!0,formidableOptions:c={},build:a=!1,cookiesOptions:p={}}={}){let m={prefix:o,wsPrefix:t,include:e,exclude:n,reload:s,cors:i,cookiesOptions:p,log:r,formidableOptions:{multiples:!0,...c},build:a?Object.assign({serverPort:8080,dist:"mockServer"},typeof a=="object"?a:{}):!1},k=[Kt(m)];return m.build&&k.push(Vt(m)),k}function Vt(o){let t={};return{name:"vite-plugin-mock-dev-server-generator",enforce:"post",apply:"build",configResolved(e){t=e,e.logger.warn("")},async buildEnd(e){e||t.command==="build"&&await xe(this,t,o)}}}function Kt(o){let t={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var r;let n=Qt(o.wsPrefix);if(n.length===0||!((r=e.server)!=null&&r.proxy)||Object.keys(e.server.proxy).length===0)return;let s={};Object.keys(e.server.proxy).forEach(i=>{n.includes(i)||(s[i]=e.server.proxy[i])}),e.server.proxy=s},configResolved(e){t=e,e.logger.warn("")},configureServer({middlewares:e,config:n,httpServer:s,ws:r}){ae(n,o,s,r).forEach(c=>e.use(c))},configurePreviewServer({middlewares:e,httpServer:n}){ae(t,o,n).forEach(r=>e.use(r))}}}import{isArray as Xt}from"@pengzhanbo/utils";function Jr(o){return o}function Ar(o){return e=>(Xt(e)?e=e.map(n=>o(n)||n):e=o(e)||e,e)}import{deepClone as Ue,deepEqual as Yt,isFunction as Zt}from"@pengzhanbo/utils";var pe=new Map,le=new WeakMap,eo=70,me=class{value;#e;#t;constructor(t){this.value=t,this.#e=Ue(t),this.#t=Date.now()}hotUpdate(t){Date.now()-this.#t<eo||Yt(t,this.#e)||(this.value=t,this.#e=Ue(t),this.#t=Date.now())}};function Vr(o,t){pe.has(o)||pe.set(o,new me(t));let e=pe.get(o);if(e.hotUpdate(t),le.has(e))return le.get(e);let n=[()=>e.value,s=>{Zt(s)&&(s=s(e.value)??e.value),e.value=s}];return Object.defineProperty(n,"value",{get(){return e.value},set(s){e.value=s}}),le.set(e,n),n}var Zr=He;export{Le as baseMiddleware,Ar as createDefineMock,Zr as default,Jr as defineMock,Vr as defineMockData,He as mockDevServerPlugin,Fe as mockWebSocket,_e as transformMockData};
{
"name": "vite-plugin-mock-dev-server",
"version": "1.3.0",
"version": "1.3.1",
"keywords": [

@@ -47,7 +47,7 @@ "vite",

"debug": "^4.3.4",
"esbuild": "^0.18.15",
"esbuild": "^0.19.2",
"fast-glob": "^3.3.1",
"formidable": "2.1.1",
"http-status": "^1.6.2",
"is-core-module": "^2.12.1",
"is-core-module": "^2.13.0",
"json5": "^2.2.3",

@@ -60,4 +60,4 @@ "mime-types": "^2.1.35",

"devDependencies": {
"@pengzhanbo/eslint-config": "^0.4.0",
"@pengzhanbo/prettier-config": "^0.4.0",
"@pengzhanbo/eslint-config": "^0.4.2",
"@pengzhanbo/prettier-config": "^0.4.2",
"@types/co-body": "^6.1.0",

@@ -72,11 +72,11 @@ "@types/cookies": "^0.7.7",

"@types/ws": "^8.5.5",
"bumpp": "^9.1.1",
"bumpp": "^9.2.0",
"conventional-changelog-cli": "^3.0.0",
"eslint": "^8.45.0",
"eslint": "^8.48.0",
"mockjs": "^1.1.0",
"prettier": "^3.0.0",
"tsup": "^7.1.0",
"typescript": "^5.1.6",
"vite": "^4.4.6",
"vitepress": "1.0.0-beta.6"
"prettier": "^3.0.2",
"tsup": "^7.2.0",
"typescript": "^5.2.2",
"vite": "^4.4.9",
"vitepress": "^1.0.0-rc.4"
},

@@ -83,0 +83,0 @@ "peerDependencies": {

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

**类型:** `string | string[]`
**Type:** `string | string[]`

@@ -191,3 +191,3 @@ Configure the matching rules for the WebSocket service. Any request path starting with the value of `wsPrefix` and using the `ws/wss` protocol will be proxied to the corresponding target.

**Type:** `true | 'info' | 'warn' | 'error' | 'silent'`
**Type:** `boolean | 'info' | 'warn' | 'error' | 'silent'`

@@ -474,2 +474,51 @@ Enable log and configure log level.

## Share Mock Data
Due to each `mock` file being compiled as a separate entry point, the local files they depend on are also compiled within. Additionally, each mock file has an independent scope. This means that even if multiple mock files collectively depend on a `data.ts` file, they cannot share data. If one mock file modifies the data in `data.ts`, other mock files will not receive the updated data.
To address this, the plugin offers a `defineMockData` function, which allows using `data.ts` as a shared data source within mock files.
```ts
type defineMockData<T> = (
key: string, // key
initialData: T, // initial data
) => [getter, setter] & { value: T }
```
#### Exp:
`data.ts`
```ts
import { defineMockData } from 'vite-plugin-mock-dev-server'
export default defineMockData('posts', [
{ id: '1', title: 'title1', content: 'content1' },
{ id: '2', title: 'title2', content: 'content2' },
])
```
`*.mock.ts`
```ts
import { defineMock } from 'vite-plugin-mock-dev-server'
import posts from './data'
export default defineMock([
{
url: '/api/posts',
body: () => posts.value
},
{
url: '/api/posts/delete/:id',
body: (params) => {
const id = params.id
posts.value = posts.value.filter((post) => post.id !== id)
return { success: true }
}
}
])
```
> **Tips:**
>
> The `defineMockData` function relies solely on the shared data support provided by `memory`.
> If persistent mock data is required, it is recommended to use a `nosql` database like `lowdb` or `level`.
## Example

@@ -809,2 +858,33 @@

## Contributors
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-3-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://pengzhanbo.cn"><img src="https://avatars.githubusercontent.com/u/16745751?v=4?s=100" width="100px;" alt="pengzhanbo"/><br /><sub><b>pengzhanbo</b></sub></a><br /><a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=pengzhanbo" title="Documentation">📖</a> <a href="#ideas-pengzhanbo" title="Ideas, Planning, & Feedback">🤔</a> <a href="#example-pengzhanbo" title="Examples">💡</a> <a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=pengzhanbo" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/jiadesen"><img src="https://avatars.githubusercontent.com/u/22772994?v=4?s=100" width="100px;" alt="jiadesen"/><br /><sub><b>jiadesen</b></sub></a><br /><a href="#ideas-jiadesen" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues?q=author%3Ajiadesen" title="Bug reports">🐛</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/yogibaba"><img src="https://avatars.githubusercontent.com/u/152670?v=4?s=100" width="100px;" alt="yogibaba"/><br /><sub><b>yogibaba</b></sub></a><br /><a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=yogibaba" title="Code">💻</a></td>
</tr>
</tbody>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
## LICENSE

@@ -811,0 +891,0 @@

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

**Type:** `true | 'info' | 'warn' | 'error' | 'silent'`
**Type:** `boolean | 'info' | 'warn' | 'error' | 'silent'`

@@ -461,2 +461,53 @@ 启动日志,以及配置日志打印级别

## 共享 Mock 数据
由于每个mock文件都是作为独立的入口进行编译,其依赖的本地文件也编译在内,
且每个mock文件拥有独立的作用域,这使得即使多个 mock文件共同依赖某一个`data.ts`文件,也无法共享数据。
某个 `mock` 文件对 `data.ts` 中的数据进行修改,其它`mock`文件不会获取到修改后的数据。
为此,插件提供了一个 `defineMockData` 函数,用于在 `mock` 文件中使用 `data.ts` 作为共享数据源。
```ts
type defineMockData<T> = (
key: string, // 数据唯一标识符
initialData: T, // 初始化数据
) => [getter, setter] & { value: T }
```
#### 用法:
`data.ts`
```ts
import { defineMockData } from 'vite-plugin-mock-dev-server'
export default defineMockData('posts', [
{ id: '1', title: 'title1', content: 'content1' },
{ id: '2', title: 'title2', content: 'content2' },
])
```
`*.mock.ts`
```ts
import { defineMock } from 'vite-plugin-mock-dev-server'
import posts from './data'
export default defineMock([
{
url: '/api/posts',
body: () => posts.value
},
{
url: '/api/posts/delete/:id',
body: (params) => {
const id = params.id
posts.value = posts.value.filter((post) => post.id !== id)
return { success: true }
}
}
])
```
> **注意:**
>
> `defineMockData` 仅是基于 `memory` 提供的共享数据支持,
> 如果需要做 mock 数据持久化,建议使用 `nosql`, 如 `lowdb` 或 `level` 等。
## Example

@@ -463,0 +514,0 @@

Sorry, the diff of this file is not supported yet

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