vite-plugin-mock-dev-server
Advanced tools
Comparing version 1.3.4-beta.0 to 1.3.4-beta.1
@@ -1,2 +0,2 @@ | ||
import{toArray as mo}from"@pengzhanbo/utils";import yt from"node:fs";import Z from"node:fs/promises";import H from"node:path";import{toArray as ee}from"@pengzhanbo/utils";import vt from"fast-glob";import Mt from"is-core-module";import{createFilter as bt,normalizePath as xt}from"vite";var ve="vite-plugin-mock-dev-server",Me="1.3.4-beta.0";import we,{promises as pe}from"node:fs";import{createRequire as it}from"node:module";import ae from"node:path";import{pathToFileURL as ct}from"node:url";import{build as at}from"esbuild";import pt from"json5";import ie from"node:fs";import ce from"node:path";import{parse as et}from"node:querystring";import{URL as tt,fileURLToPath as ot}from"node:url";import rt from"debug";import{match as nt}from"path-to-regexp";var st=o=>o!==null&&typeof o=="object"&&typeof o.pipe=="function",be=o=>st(o)&&o.readable!==!1&&typeof o._read=="function"&&typeof o._readableState=="object";function xe(o){return ce.dirname(ot(o))}var V=rt("vite:mock-dev-server");function q(o,t,e){for(let s of t){let n=ce.join(o,s);if(ie.existsSync(n)&&ie.statSync(n).isFile()){let i=e!=null&&e.pathOnly?n:ie.readFileSync(n,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=ce.dirname(o);if(r!==o&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return q(r,t,e)}var Q=(o={})=>{let t=[],e=[];return Object.keys(o).forEach(r=>{var n,i;let s=o[r];typeof s=="string"||!s.ws&&!((n=s.target)!=null&&n.toString().startsWith("ws:"))&&!((i=s.target)!=null&&i.toString().startsWith("wss:"))?t.push(r):e.push(r)}),{httpProxies:t,wsProxies:e}};function I(o,t){return o[0]==="^"&&new RegExp(o).test(t)||t.startsWith(o)}function B(o,t){return(nt(o,{decode:decodeURIComponent})(t)||{params:{}}).params||{}}function W(o){let t=new tt(o,"http://example.com"),e=decodeURIComponent(t.pathname),r=et(t.search.replace(/^\?/,""));return{pathname:e,query:r}}var lt={name:"externalize-deps",setup(o){o.onResolve({filter:/.*/},({path:t})=>{if(t[0]!=="."&&!ae.isAbsolute(t))return{external:!0}})}},ut={name:"json5-loader",setup(o){o.onLoad({filter:/\.json5$/},async({path:t})=>{let e=await pe.readFile(t,"utf-8");return{contents:`export default ${JSON.stringify(pt.parse(e))}`,loader:"js"}})}},mt={name:"json-loader",setup(o){o.onLoad({filter:/\.json$/},async({path:t})=>({contents:`export default ${await pe.readFile(t,"utf-8")}`,loader:"js"}))}},dt=o=>({name:"alias-plugin",setup(t){t.onResolve({filter:/.*/},async({path:e})=>{let r=o.find(({find:c})=>ft(c,e));if(!r)return null;let{find:s,replacement:n}=r;return{path:(await t.resolve(e.replace(s,n),{kind:"import-statement",resolveDir:n,namespace:"file"})).path,external:!1}})}});function ft(o,t){return o instanceof RegExp?o.test(t):t.length<o.length?!1:t===o?!0:t.startsWith(`${o}/`)}async function K(o,t){var n;let{isESM:e=!0,define:r,alias:s}=t;try{let i=await at({entryPoints:[o],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:e?"esm":"cjs",define:r,plugins:[dt(s),lt,mt,ut]});return{code:i.outputFiles[0].text,deps:((n=i.metafile)==null?void 0:n.inputs)||{}}}catch(i){console.error(i)}return{code:"",deps:{}}}var gt=xe(import.meta.url),T=it(gt);async function Se(o,t,e,r){if(e){let s=`${o}.timestamp-${Date.now()}`,n=`${s}.mjs`,i=`${ct(s)}.mjs`;await pe.writeFile(n,t,"utf8");try{return await import(i)}finally{try{we.unlinkSync(n)}catch{}}}else{o=ae.resolve(r,o);let s=ae.extname(o),n=we.realpathSync(o),i=s in T.extensions?s:".js",c=T.extensions[i];T.extensions[i]=(a,l)=>{l===n?a._compile(t,l):c(a,l)},delete T.cache[T.resolve(o)];let p=T(o);return T.extensions[i]=c,p.__esModule?p:{default:p}}}import Ce from"picocolors";import{isBoolean as kt}from"@pengzhanbo/utils";import $ from"picocolors";var Oe={silent:0,error:1,warn:2,info:3,debug:4};function X(o,t="info"){o=`[${o}]`;function e(s,n,i){if(i=kt(i)?i?t:"error":i,Oe[i]>=Oe[s]){let p=s==="info"||s==="debug"?"log":s,a=s==="debug"?$.magenta($.bold(o)):s==="info"?$.cyan($.bold(o)):s==="warn"?$.yellow($.bold(o)):$.red($.bold(o)),l=`${$.dim(new Date().toLocaleTimeString())} ${a} ${n}`;console[p](l)}}return{debug(s,n=t){e("debug",s,n)},info(s,n=t){e("info",s,n)},warn(s,n=t){e("warn",s,n)},error(s,n=t){e("error",s,n)}}}var ht=/import\.meta\.env\.(.+)/;function Y(o){let t=X("vite:mock-dev-server","warn"),e={},r=process.env.NODE_ENV||o.mode;Object.assign(e,{"process.env.NODE_ENV":JSON.stringify(r),"global.process.env.NODE_ENV":JSON.stringify(r),"globalThis.process.env.NODE_ENV":JSON.stringify(r),__vite_process_env_NODE_ENV:JSON.stringify(r)});let s={},n={},i=[];for(let a in o.define){let l=o.define[a];if(typeof l=="string")try{JSON.parse(l),s[a]=l}catch{i.push(a)}else s[a]=JSON.stringify(l);let d=a.match(ht);d&&s[a]&&(n[d[1]]=`__vite__define__${s[a]}`)}i.length&&t.warn(`The following keys: ${Ce.yellow(Ce.underline(i.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let c={},p={};c["import.meta.hot"]="undefined";for(let a in o.env)c[`import.meta.env.${a}`]=JSON.stringify(o.env[a]);return Object.assign(p,{"import.meta.env":JSON.stringify({...o.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(a,l,d)=>`${l.replace(/(^\\")|(\\"$)/g,'"')}${d}`)}),{...c,...s,...p,...e}}async function Pe(o,t,e){let r=ee(e.include),s=ee(e.exclude),n=Y(t),{httpProxies:i}=Q(t.server.proxy||{});i.push(...ee(e.prefix));let c=ee(e.wsPrefix),p={};try{let u=q(t.root,["package.json"]);u&&(p=JSON.parse(u))}catch{}let a=e.build.dist,l=await Ct(process.cwd(),r,s),d=H.join(t.root,`mock-data-${Date.now()}.js`);await Z.writeFile(d,l,"utf-8");let{code:h,deps:y}=await K(d,{define:n,alias:t.resolve.alias}),P=wt(y);await Z.unlink(d);let m=[{filename:H.join(a,"mock-data.js"),source:h},{filename:H.join(a,"index.js"),source:Ot(i,c,e.cookiesOptions,e.priority,e.build.serverPort)},{filename:H.join(a,"package.json"),source:St(p,P)}];try{if(H.isAbsolute(a)){await Z.rm(a,{recursive:!0}),yt.mkdirSync(a,{recursive:!0});for(let{filename:u,source:f}of m)await Z.writeFile(u,f,"utf-8")}else for(let{filename:u,source:f}of m)o.emitFile({type:"asset",fileName:u,source:f})}catch{}}function wt(o){let t=new Set,e=[ve,"connect","cors"];return Object.keys(o).forEach(r=>{o[r].imports.filter(n=>n.external&&!n.path.startsWith("<define:")).map(n=>n.path).forEach(n=>{!e.includes(n)&&!Mt(n)&&t.add(n)})}),Array.from(t)}function St(o,t){let{dependencies:e={},devDependencies:r={}}=o,s={...e,...r},n={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 t.forEach(i=>{n.dependencies[i]=s[i]||"latest"}),JSON.stringify(n,null,2)}function Ot(o,t,e={},r={},s=8080){return`import { createServer } from 'node:http'; | ||
import{toArray as mo}from"@pengzhanbo/utils";import yt from"node:fs";import Z from"node:fs/promises";import H from"node:path";import{toArray as ee}from"@pengzhanbo/utils";import vt from"fast-glob";import Mt from"is-core-module";import{createFilter as bt,normalizePath as xt}from"vite";var ve="vite-plugin-mock-dev-server",Me="1.3.4-beta.1";import we,{promises as pe}from"node:fs";import{createRequire as it}from"node:module";import ae from"node:path";import{pathToFileURL as ct}from"node:url";import{build as at}from"esbuild";import pt from"json5";import ie from"node:fs";import ce from"node:path";import{parse as et}from"node:querystring";import{URL as tt,fileURLToPath as ot}from"node:url";import rt from"debug";import{match as nt}from"path-to-regexp";var st=o=>o!==null&&typeof o=="object"&&typeof o.pipe=="function",be=o=>st(o)&&o.readable!==!1&&typeof o._read=="function"&&typeof o._readableState=="object";function xe(o){return ce.dirname(ot(o))}var V=rt("vite:mock-dev-server");function B(o,t,e){for(let s of t){let n=ce.join(o,s);if(ie.existsSync(n)&&ie.statSync(n).isFile()){let i=e!=null&&e.pathOnly?n:ie.readFileSync(n,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=ce.dirname(o);if(r!==o&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return B(r,t,e)}var Q=(o={})=>{let t=[],e=[];return Object.keys(o).forEach(r=>{var n,i;let s=o[r];typeof s=="string"||!s.ws&&!((n=s.target)!=null&&n.toString().startsWith("ws:"))&&!((i=s.target)!=null&&i.toString().startsWith("wss:"))?t.push(r):e.push(r)}),{httpProxies:t,wsProxies:e}};function I(o,t){return o[0]==="^"&&new RegExp(o).test(t)||t.startsWith(o)}function q(o,t){return(nt(o,{decode:decodeURIComponent})(t)||{params:{}}).params||{}}function W(o){let t=new tt(o,"http://example.com"),e=decodeURIComponent(t.pathname),r=et(t.search.replace(/^\?/,""));return{pathname:e,query:r}}var lt={name:"externalize-deps",setup(o){o.onResolve({filter:/.*/},({path:t})=>{if(t[0]!=="."&&!ae.isAbsolute(t))return{external:!0}})}},ut={name:"json5-loader",setup(o){o.onLoad({filter:/\.json5$/},async({path:t})=>{let e=await pe.readFile(t,"utf-8");return{contents:`export default ${JSON.stringify(pt.parse(e))}`,loader:"js"}})}},mt={name:"json-loader",setup(o){o.onLoad({filter:/\.json$/},async({path:t})=>({contents:`export default ${await pe.readFile(t,"utf-8")}`,loader:"js"}))}},dt=o=>({name:"alias-plugin",setup(t){t.onResolve({filter:/.*/},async({path:e})=>{let r=o.find(({find:c})=>ft(c,e));if(!r)return null;let{find:s,replacement:n}=r;return{path:(await t.resolve(e.replace(s,n),{kind:"import-statement",resolveDir:n,namespace:"file"})).path,external:!1}})}});function ft(o,t){return o instanceof RegExp?o.test(t):t.length<o.length?!1:t===o?!0:t.startsWith(`${o}/`)}async function K(o,t){var n;let{isESM:e=!0,define:r,alias:s}=t;try{let i=await at({entryPoints:[o],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:e?"esm":"cjs",define:r,plugins:[dt(s),lt,mt,ut]});return{code:i.outputFiles[0].text,deps:((n=i.metafile)==null?void 0:n.inputs)||{}}}catch(i){console.error(i)}return{code:"",deps:{}}}var gt=xe(import.meta.url),T=it(gt);async function Se(o,t,e,r){if(e){let s=`${o}.timestamp-${Date.now()}`,n=`${s}.mjs`,i=`${ct(s)}.mjs`;await pe.writeFile(n,t,"utf8");try{return await import(i)}finally{try{we.unlinkSync(n)}catch{}}}else{o=ae.resolve(r,o);let s=ae.extname(o),n=we.realpathSync(o),i=s in T.extensions?s:".js",c=T.extensions[i];T.extensions[i]=(a,l)=>{l===n?a._compile(t,l):c(a,l)},delete T.cache[T.resolve(o)];let p=T(o);return T.extensions[i]=c,p.__esModule?p:{default:p}}}import Ce from"picocolors";import{isBoolean as kt}from"@pengzhanbo/utils";import $ from"picocolors";var Oe={silent:0,error:1,warn:2,info:3,debug:4};function X(o,t="info"){o=`[${o}]`;function e(s,n,i){if(i=kt(i)?i?t:"error":i,Oe[i]>=Oe[s]){let p=s==="info"||s==="debug"?"log":s,a=s==="debug"?$.magenta($.bold(o)):s==="info"?$.cyan($.bold(o)):s==="warn"?$.yellow($.bold(o)):$.red($.bold(o)),l=`${$.dim(new Date().toLocaleTimeString())} ${a} ${n}`;console[p](l)}}return{debug(s,n=t){e("debug",s,n)},info(s,n=t){e("info",s,n)},warn(s,n=t){e("warn",s,n)},error(s,n=t){e("error",s,n)}}}var ht=/import\.meta\.env\.(.+)/;function Y(o){let t=X("vite:mock-dev-server","warn"),e={},r=process.env.NODE_ENV||o.mode;Object.assign(e,{"process.env.NODE_ENV":JSON.stringify(r),"global.process.env.NODE_ENV":JSON.stringify(r),"globalThis.process.env.NODE_ENV":JSON.stringify(r),__vite_process_env_NODE_ENV:JSON.stringify(r)});let s={},n={},i=[];for(let a in o.define){let l=o.define[a];if(typeof l=="string")try{JSON.parse(l),s[a]=l}catch{i.push(a)}else s[a]=JSON.stringify(l);let d=a.match(ht);d&&s[a]&&(n[d[1]]=`__vite__define__${s[a]}`)}i.length&&t.warn(`The following keys: ${Ce.yellow(Ce.underline(i.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let c={},p={};c["import.meta.hot"]="undefined";for(let a in o.env)c[`import.meta.env.${a}`]=JSON.stringify(o.env[a]);return Object.assign(p,{"import.meta.env":JSON.stringify({...o.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(a,l,d)=>`${l.replace(/(^\\")|(\\"$)/g,'"')}${d}`)}),{...c,...s,...p,...e}}async function Pe(o,t,e){let r=ee(e.include),s=ee(e.exclude),n=Y(t),{httpProxies:i}=Q(t.server.proxy||{});i.push(...ee(e.prefix));let c=ee(e.wsPrefix),p={};try{let u=B(t.root,["package.json"]);u&&(p=JSON.parse(u))}catch{}let a=e.build.dist,l=await Ct(process.cwd(),r,s),d=H.join(t.root,`mock-data-${Date.now()}.js`);await Z.writeFile(d,l,"utf-8");let{code:h,deps:y}=await K(d,{define:n,alias:t.resolve.alias}),P=wt(y);await Z.unlink(d);let m=[{filename:H.join(a,"mock-data.js"),source:h},{filename:H.join(a,"index.js"),source:Ot(i,c,e.cookiesOptions,e.priority,e.build.serverPort)},{filename:H.join(a,"package.json"),source:St(p,P)}];try{if(H.isAbsolute(a)){await Z.rm(a,{recursive:!0}),yt.mkdirSync(a,{recursive:!0});for(let{filename:u,source:f}of m)await Z.writeFile(u,f,"utf-8")}else for(let{filename:u,source:f}of m)o.emitFile({type:"asset",fileName:u,source:f})}catch{}}function wt(o){let t=new Set,e=[ve,"connect","cors"];return Object.keys(o).forEach(r=>{o[r].imports.filter(n=>n.external&&!n.path.startsWith("<define:")).map(n=>n.path).forEach(n=>{!e.includes(n)&&!Mt(n)&&t.add(n)})}),Array.from(t)}function St(o,t){let{dependencies:e={},devDependencies:r={}}=o,s={...e,...r},n={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 t.forEach(i=>{n.dependencies[i]=s[i]||"latest"}),JSON.stringify(n,null,2)}function Ot(o,t,e={},r={},s=8080){return`import { createServer } from 'node:http'; | ||
import connect from 'connect'; | ||
@@ -45,17 +45,17 @@ import corsMiddleware from 'cors'; | ||
}); | ||
export default transformMockData(mockList);`}import{isBoolean as ao,toArray as se}from"@pengzhanbo/utils";import po from"cors";import{pathToRegexp as lo}from"path-to-regexp";import{Buffer as Ue}from"node:buffer";import{isArray as oe,isEmptyObject as Tt,isFunction as re,random as It,sleep as Ht,timestamp as Be}from"@pengzhanbo/utils";import Nt from"cookies";import Ft from"http-status";import*as A from"mime-types";import{pathToRegexp as Ut}from"path-to-regexp";import k from"picocolors";import{isArray as Pt,isEmptyObject as Re,isString as te,sortBy as $e,uniq as We}from"@pengzhanbo/utils";import{parse as Rt,pathToRegexp as je}from"path-to-regexp";var le={};function J(o){if(le[o])return le[o];let t=Rt(o),e=[];for(let r of t)if(!te(r))e.push(r);else{let s=r[0]==="/",n=s?r.slice(1).split("/"):r.split("/");e.push(`${s?"/":""}${n[0]}`,...n.slice(1).map(i=>`/${i}`))}return le[o]=e,e}function Wt(o){let t=o.map(e=>J(e).length);return t=t.length===0?[1]:t,Math.max(...t)+2}function jt(o){let t=J(o),e=0;for(let r=0;r<t.length;r++){let s=t[r];te(s)||(e+=10**(r+1)),e+=10**(r+1)}return e}function $t(o){let t=[],e=[];for(let r of o){let n=J(r).filter(i=>typeof i!="string").length;e[n]||(e[n]=[]),e[n].push(r)}for(let r of e.filter(s=>s&&s.length>0))t=[...t,...$e(r,jt).reverse()];return t}function Lt(o){let t=Wt(o);return $e(o,e=>{let r=J(e),s=r.filter(c=>typeof c!="string");if(s.length===0)return 0;let n=s.length,i=0;for(let c=0;c<r.length;c++){let p=r[c],a=!te(p),{pattern:l="",modifier:d,prefix:h,name:y}=a?p:{},P=l&&l.includes(".*"),m=h==="/",u=te(y);i+=a&&m?1:0,c===r.length-1&&P?n+=5*10**(r.length===1?t+1:t):P?n+=3*10**(t-1):l&&(m?n+=(u?2:1)*10**(i+1):n-=1*10**i),d==="+"&&(n+=1*10**(t-1)),d==="*"&&(n+=1*10**(t-1)+1),d==="?"&&(n+=1*10**(i+(m?1:0)))}return n})}function Le(o,t,e){let r=Lt($t(o.filter(y=>je(y).test(t)))),{global:s=[],special:n={}}=e;if(s.length===0&&Re(n)||r.length===0)return r;let[i,c]=Dt(r),p=s.filter(y=>c.includes(y));if(p.length>0&&(r=We([...i,...p,...c])),Re(n))return r;let a=Object.keys(n).filter(y=>r.includes(y))[0];if(!a)return r;let l=n[a],{rules:d,when:h}=Pt(l)?{rules:l,when:[]}:l;return d.includes(r[0])&&(h.length===0||h.some(y=>je(y).test(t)))&&(r=We([a,...r])),r}function Dt(o){let t=[],e=[];for(let r of o)J(r).filter(i=>typeof i!="string").length>0?e.push(r):t.push(r);return[t,e]}import ue from"co-body";import Et from"formidable";async function De(o,t){var s;let e=o.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((s=o.headers["content-type"])==null?void 0:s.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await ue.json(o);if(r.startsWith("application/x-www-form-urlencoded"))return await ue.form(o);if(r.startsWith("text/plain"))return await ue.text(o);if(r.startsWith("multipart/form-data"))return await _t(o,t)}catch(n){console.error(n)}}async function _t(o,t){let e=Et(t);return new Promise((r,s)=>{e.parse(o,(n,i,c)=>{if(n){s(n);return}r({...i,...c})})})}import{Buffer as Ee}from"node:buffer";var me=new WeakMap,_e=o=>{let t=[];o.addListener("data",e=>{t.push(Ee.from(e))}),o.addListener("end",()=>{me.set(o,Ee.concat(t))})},Te=o=>{if(!o.server)return;let t=o.server.proxy||{};Object.keys(t).forEach(e=>{let r=t[e],s=typeof r=="string"?{target:r}:r;if(s.ws)return;let{configure:n,...i}=s;t[e]={...i,configure(c,p){c.on("proxyReq",(a,l)=>{let d=me.get(l);d&&(me.delete(l),a.setHeader("Content-Length",d.byteLength),a.write(d))}),n==null||n(c,p)}}})};import{isArray as Ie,isObject as He}from"@pengzhanbo/utils";function Ne(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(!Fe(o[e],t[e]))return!1;return!0}function Fe(o,t){if(Ie(o)&&Ie(t)){let e=new Set;return t.every(r=>o.some((s,n)=>{if(e.has(n))return!1;let i=Fe(s,r);return i&&e.add(n),i}))}return He(o)&&He(t)?D(o,t):Object.is(o,t)}function Je(o,{formidableOptions:t={},proxies:e,cookiesOptions:r,logger:s,priority:n={}}){return async function(i,c,p){let a=Be(),{query:l,pathname:d}=W(i.url);if(!d||e.length===0||!e.some(x=>I(x,i.url)))return p();let h=o.mockData,y=Le(Object.keys(h),d,n);if(y.length===0)return p();_e(i);let{query:P}=W(i.headers.referer||""),m=await De(i,t),u=new Nt(i,c,r),f=u.get.bind(u),v=i.method.toUpperCase(),M,C;for(let x of y)if(M=qt(h[x],s,{pathname:d,method:v,request:{query:l,refererQuery:P,body:m,headers:i.headers,getCookie:f}}),M){C=x;break}if(!M){let x=y.map(U=>U===C?k.underline(k.bold(U)):k.dim(U)).join(", ");return s.warn(`${k.green(d)} matches ${x} , but mock data is not found.`),p()}let g=i,b=c;g.body=m,g.query=l,g.refererQuery=P,g.params=B(M.url,d),g.getCookie=f,b.setCookie=u.set.bind(u);let{body:R,delay:E,type:_="json",response:L,status:j=200,statusText:G,log:F,__filepath__:w}=M;if(de(b,j,G),await Bt(g,b,M,s),await Jt(g,b,M,s),s.info(Gt(g,w),F),s.debug(`${k.magenta("DEBUG")} ${k.underline(d)} matches: [ ${y.map(x=>x===C?k.underline(k.bold(x)):k.dim(x)).join(", ")} ] | ||
`),R){try{let x=re(R)?await R(g):R;await qe(a,E),At(b,x,_)}catch(x){s.error(`${k.red(`mock error at ${d}`)} | ||
export default transformMockData(mockList);`}import{isBoolean as ao,toArray as se}from"@pengzhanbo/utils";import po from"cors";import{pathToRegexp as lo}from"path-to-regexp";import{Buffer as Ue}from"node:buffer";import{isArray as oe,isEmptyObject as Tt,isFunction as re,random as It,sleep as Ht,timestamp as qe}from"@pengzhanbo/utils";import Nt from"cookies";import Ft from"http-status";import*as A from"mime-types";import{pathToRegexp as Ut}from"path-to-regexp";import k from"picocolors";import{isArray as Pt,isEmptyObject as Re,isString as te,sortBy as $e,uniq as We}from"@pengzhanbo/utils";import{parse as Rt,pathToRegexp as je}from"path-to-regexp";var le={};function J(o){if(le[o])return le[o];let t=Rt(o),e=[];for(let r of t)if(!te(r))e.push(r);else{let s=r[0]==="/",n=s?r.slice(1).split("/"):r.split("/");e.push(`${s?"/":""}${n[0]}`,...n.slice(1).map(i=>`/${i}`))}return le[o]=e,e}function Wt(o){let t=o.map(e=>J(e).length);return t=t.length===0?[1]:t,Math.max(...t)+2}function jt(o){let t=J(o),e=0;for(let r=0;r<t.length;r++){let s=t[r];te(s)||(e+=10**(r+1)),e+=10**(r+1)}return e}function $t(o){let t=[],e=[];for(let r of o){let n=J(r).filter(i=>typeof i!="string").length;e[n]||(e[n]=[]),e[n].push(r)}for(let r of e.filter(s=>s&&s.length>0))t=[...t,...$e(r,jt).reverse()];return t}function Lt(o){let t=Wt(o);return $e(o,e=>{let r=J(e),s=r.filter(c=>typeof c!="string");if(s.length===0)return 0;let n=s.length,i=0;for(let c=0;c<r.length;c++){let p=r[c],a=!te(p),{pattern:l="",modifier:d,prefix:h,name:y}=a?p:{},P=l&&l.includes(".*"),m=h==="/",u=te(y);i+=a&&m?1:0,c===r.length-1&&P?n+=5*10**(r.length===1?t+1:t):P?n+=3*10**(t-1):l&&(m?n+=(u?2:1)*10**(i+1):n-=1*10**i),d==="+"&&(n+=1*10**(t-1)),d==="*"&&(n+=1*10**(t-1)+1),d==="?"&&(n+=1*10**(i+(m?1:0)))}return n})}function Le(o,t,e){let r=Lt($t(o.filter(y=>je(y).test(t)))),{global:s=[],special:n={}}=e;if(s.length===0&&Re(n)||r.length===0)return r;let[i,c]=Dt(r),p=s.filter(y=>c.includes(y));if(p.length>0&&(r=We([...i,...p,...c])),Re(n))return r;let a=Object.keys(n).filter(y=>r.includes(y))[0];if(!a)return r;let l=n[a],{rules:d,when:h}=Pt(l)?{rules:l,when:[]}:l;return d.includes(r[0])&&(h.length===0||h.some(y=>je(y).test(t)))&&(r=We([a,...r])),r}function Dt(o){let t=[],e=[];for(let r of o)J(r).filter(i=>typeof i!="string").length>0?e.push(r):t.push(r);return[t,e]}import ue from"co-body";import Et from"formidable";async function De(o,t){var s;let e=o.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((s=o.headers["content-type"])==null?void 0:s.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await ue.json(o);if(r.startsWith("application/x-www-form-urlencoded"))return await ue.form(o);if(r.startsWith("text/plain"))return await ue.text(o);if(r.startsWith("multipart/form-data"))return await _t(o,t)}catch(n){console.error(n)}}async function _t(o,t){let e=Et(t);return new Promise((r,s)=>{e.parse(o,(n,i,c)=>{if(n){s(n);return}r({...i,...c})})})}import{Buffer as Ee}from"node:buffer";var me=new WeakMap,_e=o=>{let t=[];o.addListener("data",e=>{t.push(Ee.from(e))}),o.addListener("end",()=>{t.length&&me.set(o,Ee.concat(t))})},Te=o=>{if(!o.server)return;let t=o.server.proxy||{};Object.keys(t).forEach(e=>{let r=t[e],s=typeof r=="string"?{target:r}:r;if(s.ws)return;let{configure:n,...i}=s;t[e]={...i,configure(c,p){n==null||n(c,p),c.on("proxyReq",(a,l)=>{let d=me.get(l);d&&(me.delete(l),a.headersSent||a.setHeader("Content-Length",d.byteLength),a.writableEnded||a.write(d))})}}})};import{isArray as Ie,isObject as He}from"@pengzhanbo/utils";function Ne(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(!Fe(o[e],t[e]))return!1;return!0}function Fe(o,t){if(Ie(o)&&Ie(t)){let e=new Set;return t.every(r=>o.some((s,n)=>{if(e.has(n))return!1;let i=Fe(s,r);return i&&e.add(n),i}))}return He(o)&&He(t)?D(o,t):Object.is(o,t)}function Je(o,{formidableOptions:t={},proxies:e,cookiesOptions:r,logger:s,priority:n={}}){return async function(i,c,p){let a=qe(),{query:l,pathname:d}=W(i.url);if(!d||e.length===0||!e.some(x=>I(x,i.url)))return p();let h=o.mockData,y=Le(Object.keys(h),d,n);if(y.length===0)return p();_e(i);let{query:P}=W(i.headers.referer||""),m=await De(i,t),u=new Nt(i,c,r),f=u.get.bind(u),v=i.method.toUpperCase(),M,C;for(let x of y)if(M=Bt(h[x],s,{pathname:d,method:v,request:{query:l,refererQuery:P,body:m,headers:i.headers,getCookie:f}}),M){C=x;break}if(!M){let x=y.map(U=>U===C?k.underline(k.bold(U)):k.dim(U)).join(", ");return s.warn(`${k.green(d)} matches ${x} , but mock data is not found.`),p()}let g=i,b=c;g.body=m,g.query=l,g.refererQuery=P,g.params=q(M.url,d),g.getCookie=f,b.setCookie=u.set.bind(u);let{body:R,delay:E,type:_="json",response:L,status:j=200,statusText:G,log:F,__filepath__:w}=M;if(de(b,j,G),await qt(g,b,M,s),await Jt(g,b,M,s),s.info(Gt(g,w),F),s.debug(`${k.magenta("DEBUG")} ${k.underline(d)} matches: [ ${y.map(x=>x===C?k.underline(k.bold(x)):k.dim(x)).join(", ")} ] | ||
`),R){try{let x=re(R)?await R(g):R;await Be(a,E),At(b,x,_)}catch(x){s.error(`${k.red(`mock error at ${d}`)} | ||
${x} | ||
at body (${k.underline(w)})`,F),de(b,500),c.end("")}return}if(L){try{await qe(a,E),await L(g,b,p)}catch(x){s.error(`${k.red(`mock error at ${d}`)} | ||
at body (${k.underline(w)})`,F),de(b,500),c.end("")}return}if(L){try{await Be(a,E),await L(g,b,p)}catch(x){s.error(`${k.red(`mock error at ${d}`)} | ||
${x} | ||
at response (${k.underline(w)})`,F),de(b,500),c.end("")}return}c.end("")}}function qt(o,t,{pathname:e,method:r,request:s}){return o.find(n=>{if(!e||!n||!n.url||n.ws===!0||!(n.method?oe(n.method)?n.method:[n.method]:["GET","POST"]).includes(r))return!1;let c=Ut(n.url).test(e);if(c&&n.validator){let p=B(n.url,e);if(re(n.validator))return n.validator({params:p,...s});try{return Ne({params:p,...s},n.validator)}catch(a){let l=n.__filepath__;return t.error(`${k.red(`mock error at ${e}`)} | ||
at response (${k.underline(w)})`,F),de(b,500),c.end("")}return}c.end("")}}function Bt(o,t,{pathname:e,method:r,request:s}){return o.find(n=>{if(!e||!n||!n.url||n.ws===!0||!(n.method?oe(n.method)?n.method:[n.method]:["GET","POST"]).includes(r))return!1;let c=Ut(n.url).test(e);if(c&&n.validator){let p=q(n.url,e);if(re(n.validator))return n.validator({params:p,...s});try{return Ne({params:p,...s},n.validator)}catch(a){let l=n.__filepath__;return t.error(`${k.red(`mock error at ${e}`)} | ||
${a} | ||
at validator (${k.underline(l)})`,n.log),!1}}return c})}function de(o,t=200,e){o.statusCode=t,o.statusMessage=e||zt(t)}async function Bt(o,t,e,r){let{headers:s,type:n="json"}=e,i=e.__filepath__,c=A.contentType(n)||A.contentType(A.lookup(n)||"");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 p=re(s)?await s(o):s;Object.keys(p).forEach(a=>{t.setHeader(a,p[a])})}catch(p){r.error(`${k.red(`mock error at ${o.url.split("?")[0]}`)} | ||
at validator (${k.underline(l)})`,n.log),!1}}return c})}function de(o,t=200,e){o.statusCode=t,o.statusMessage=e||zt(t)}async function qt(o,t,e,r){let{headers:s,type:n="json"}=e,i=e.__filepath__,c=A.contentType(n)||A.contentType(A.lookup(n)||"");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 p=re(s)?await s(o):s;Object.keys(p).forEach(a=>{t.setHeader(a,p[a])})}catch(p){r.error(`${k.red(`mock error at ${o.url.split("?")[0]}`)} | ||
${p} | ||
at headers (${k.underline(i)})`,e.log)}}async function Jt(o,t,e,r){let{cookies:s}=e,n=e.__filepath__;if(s)try{let i=re(s)?await s(o):s;Object.keys(i).forEach(c=>{let p=i[c];if(oe(p)){let[a,l]=p;t.setCookie(c,a,l)}else t.setCookie(c,p)})}catch(i){r.error(`${k.red(`mock error at ${o.url.split("?")[0]}`)} | ||
${i} | ||
at cookies (${k.underline(n)})`,e.log)}}function At(o,t,e){if(be(t))t.pipe(o);else if(Ue.isBuffer(t))o.end(e==="text"||e==="json"?t.toString("utf-8"):t);else{let r=typeof t=="string"?t:JSON.stringify(t);o.end(e==="buffer"?Ue.from(r):r)}}async function qe(o,t){if(!t||typeof t=="number"&&t<=0||oe(t)&&t.length!==2)return;let e=0;if(oe(t)){let[r,s]=t;e=It(r,s)}else e=t-(Be()-o);e>0&&await Ht(e)}function zt(o){return Ft[o]||"Unknown"}function Gt(o,t){let{url:e,method:r,query:s,params:n,body:i}=o,{pathname:c}=new URL(e,"http://example.com");c=k.green(decodeURIComponent(c));let p=(P,m)=>!m||Tt(m)?"":` ${k.gray(`${P}:`)}${JSON.stringify(m)}`,a=k.magenta(k.bold(r)),l=p("query",s),d=p("params",n),h=p("body",i),y=` ${k.dim(k.underline(`(${t})`))}`;return`${a} ${c}${l}${d}${h}${y}`}import Zt from"node:events";import{hasOwn as eo,isArray as to,promiseParallel as oo,toArray as ro}from"@pengzhanbo/utils";import Ve from"chokidar";import no from"fast-glob";import{createFilter as so,normalizePath as z}from"vite";import{isArray as Vt,isEmptyObject as Ae,isFunction as ze,isObject as Qt,sortBy as Kt}from"@pengzhanbo/utils";function Ge(o){let t=[];for(let[,r]of o.entries())r&&(Vt(r)?t.push(...r):t.push(r));let e={};return t.filter(r=>Qt(r)&&r.enabled!==!1&&r.url).forEach(r=>{let{pathname:s,query:n}=W(r.url),i=e[s]??=[],c={...r,url:s};if(c.ws!==!0){let p=c.validator;Ae(n)||(ze(p)?c.validator=function(a){return D(a.query,n)&&p(a)}:p?(c.validator={...p},c.validator.query=c.validator.query?{...n,...c.validator.query}:n):c.validator={query:n})}i.push(c)}),Object.keys(e).forEach(r=>{e[r]=Xt(e[r])}),e}function Xt(o){return Kt(o,t=>{if(t.ws===!0)return 0;let{validator:e}=t;return!e||Ae(e)?2:ze(e)?0:1/Object.keys(e).reduce((s,n)=>s+Yt(e[n]),0)})}function Yt(o){return o?Object.keys(o).length:0}var ne=class extends Zt{constructor(e){super();this.options=e;this.cwd=e.cwd||process.cwd();try{let r=q(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,s=so(e,r,{resolve:!1});no(e,{cwd:this.cwd}).then(i=>i.filter(s).map(c=>()=>this.loadMock(c))).then(i=>oo(i,10)).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let n=null;this.on("mock:update",async i=>{s(i)&&(await this.loadMock(i),n&&clearImmediate(n),n=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),n=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,[r,...s]=e,n=this.mockWatcher=Ve.watch(r,{ignoreInitial:!0,cwd:this.cwd});s.length>0&&s.forEach(i=>n.add(i)),n.on("add",async i=>{i=z(i),this.emit("mock:update",i),V("watcher:add",i)}),n.on("change",async i=>{i=z(i),this.emit("mock:update",i),V("watcher:change",i)}),n.on("unlink",async i=>{i=z(i),this.emit("mock:unlink",i),V("watcher:unlink",i)})}watchDeps(){let e=[];this.depsWatcher=Ve.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=z(r);let s=this.moduleDeps.get(r);s&&s.forEach(n=>{this.emit("mock:update",n)})}),this.depsWatcher.on("unlink",r=>{r=z(r),this.moduleDeps.delete(r)}),this.on("update:deps",()=>{let r=[];for(let[n]of this.moduleDeps.entries())r.push(n);let s=r.filter(n=>!e.includes(n));s.length>0&&this.depsWatcher.add(s)})}close(){var e,r;(e=this.mockWatcher)==null||e.close(),(r=this.depsWatcher)==null||r.close()}updateMockList(){this._mockData=Ge(this.moduleCache)}updateModuleDeps(e,r){Object.keys(r).forEach(s=>{r[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 r=!1;/\.m[jt]s$/.test(e)?r=!0:/\.c[jt]s$/.test(e)?r=!1:r=this.moduleType==="esm";let{define:s,alias:n}=this.options,{code:i,deps:c}=await K(e,{isESM:r,define:s,alias:n});try{let p=await Se(e,i,r,this.cwd)||{},a;eo(p,"default")?a=p.default:(a=[],Object.keys(p).forEach(l=>a.push(...ro(p[l])))),to(a)?a.forEach(l=>l.__filepath__=e):a.__filepath__=e,this.moduleCache.set(e,a),this.updateModuleDeps(e,c)}catch(p){console.error(p)}}};import io from"cookies";import{pathToRegexp as Qe}from"path-to-regexp";import N from"picocolors";import{WebSocketServer as co}from"ws";function Xe({loader:o,httpServer:t,proxies:e,cookiesOptions:r,logger:s}){var P;let n=new Map,i=new Map,c=new WeakMap,p=m=>{let u=i.get(m);return!u&&i.set(m,u=new Map),u},a=(m,u)=>{let f=m.get(u);return!f&&m.set(u,f=new co({noServer:!0})),f},l=(m,u)=>{let f=n.get(m);!f&&n.set(m,f=new Set),f.add(u)},d=(m,u,f,v,M,C)=>{var g;try{(g=f.setup)==null||g.call(f,u,v),u.on("close",()=>m.delete(M)),u.on("error",b=>{s.error(`${N.red(`WebSocket mock error at ${u.path}`)} | ||
at cookies (${k.underline(n)})`,e.log)}}function At(o,t,e){if(be(t))t.pipe(o);else if(Ue.isBuffer(t))o.end(e==="text"||e==="json"?t.toString("utf-8"):t);else{let r=typeof t=="string"?t:JSON.stringify(t);o.end(e==="buffer"?Ue.from(r):r)}}async function Be(o,t){if(!t||typeof t=="number"&&t<=0||oe(t)&&t.length!==2)return;let e=0;if(oe(t)){let[r,s]=t;e=It(r,s)}else e=t-(qe()-o);e>0&&await Ht(e)}function zt(o){return Ft[o]||"Unknown"}function Gt(o,t){let{url:e,method:r,query:s,params:n,body:i}=o,{pathname:c}=new URL(e,"http://example.com");c=k.green(decodeURIComponent(c));let p=(P,m)=>!m||Tt(m)?"":` ${k.gray(`${P}:`)}${JSON.stringify(m)}`,a=k.magenta(k.bold(r)),l=p("query",s),d=p("params",n),h=p("body",i),y=` ${k.dim(k.underline(`(${t})`))}`;return`${a} ${c}${l}${d}${h}${y}`}import Zt from"node:events";import{hasOwn as eo,isArray as to,promiseParallel as oo,toArray as ro}from"@pengzhanbo/utils";import Ve from"chokidar";import no from"fast-glob";import{createFilter as so,normalizePath as z}from"vite";import{isArray as Vt,isEmptyObject as Ae,isFunction as ze,isObject as Qt,sortBy as Kt}from"@pengzhanbo/utils";function Ge(o){let t=[];for(let[,r]of o.entries())r&&(Vt(r)?t.push(...r):t.push(r));let e={};return t.filter(r=>Qt(r)&&r.enabled!==!1&&r.url).forEach(r=>{let{pathname:s,query:n}=W(r.url),i=e[s]??=[],c={...r,url:s};if(c.ws!==!0){let p=c.validator;Ae(n)||(ze(p)?c.validator=function(a){return D(a.query,n)&&p(a)}:p?(c.validator={...p},c.validator.query=c.validator.query?{...n,...c.validator.query}:n):c.validator={query:n})}i.push(c)}),Object.keys(e).forEach(r=>{e[r]=Xt(e[r])}),e}function Xt(o){return Kt(o,t=>{if(t.ws===!0)return 0;let{validator:e}=t;return!e||Ae(e)?2:ze(e)?0:1/Object.keys(e).reduce((s,n)=>s+Yt(e[n]),0)})}function Yt(o){return o?Object.keys(o).length:0}var ne=class extends Zt{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,s=so(e,r,{resolve:!1});no(e,{cwd:this.cwd}).then(i=>i.filter(s).map(c=>()=>this.loadMock(c))).then(i=>oo(i,10)).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let n=null;this.on("mock:update",async i=>{s(i)&&(await this.loadMock(i),n&&clearImmediate(n),n=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),n=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,[r,...s]=e,n=this.mockWatcher=Ve.watch(r,{ignoreInitial:!0,cwd:this.cwd});s.length>0&&s.forEach(i=>n.add(i)),n.on("add",async i=>{i=z(i),this.emit("mock:update",i),V("watcher:add",i)}),n.on("change",async i=>{i=z(i),this.emit("mock:update",i),V("watcher:change",i)}),n.on("unlink",async i=>{i=z(i),this.emit("mock:unlink",i),V("watcher:unlink",i)})}watchDeps(){let e=[];this.depsWatcher=Ve.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=z(r);let s=this.moduleDeps.get(r);s&&s.forEach(n=>{this.emit("mock:update",n)})}),this.depsWatcher.on("unlink",r=>{r=z(r),this.moduleDeps.delete(r)}),this.on("update:deps",()=>{let r=[];for(let[n]of this.moduleDeps.entries())r.push(n);let s=r.filter(n=>!e.includes(n));s.length>0&&this.depsWatcher.add(s)})}close(){var e,r;(e=this.mockWatcher)==null||e.close(),(r=this.depsWatcher)==null||r.close()}updateMockList(){this._mockData=Ge(this.moduleCache)}updateModuleDeps(e,r){Object.keys(r).forEach(s=>{r[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 r=!1;/\.m[jt]s$/.test(e)?r=!0:/\.c[jt]s$/.test(e)?r=!1:r=this.moduleType==="esm";let{define:s,alias:n}=this.options,{code:i,deps:c}=await K(e,{isESM:r,define:s,alias:n});try{let p=await Se(e,i,r,this.cwd)||{},a;eo(p,"default")?a=p.default:(a=[],Object.keys(p).forEach(l=>a.push(...ro(p[l])))),to(a)?a.forEach(l=>l.__filepath__=e):a.__filepath__=e,this.moduleCache.set(e,a),this.updateModuleDeps(e,c)}catch(p){console.error(p)}}};import io from"cookies";import{pathToRegexp as Qe}from"path-to-regexp";import N from"picocolors";import{WebSocketServer as co}from"ws";function Xe({loader:o,httpServer:t,proxies:e,cookiesOptions:r,logger:s}){var P;let n=new Map,i=new Map,c=new WeakMap,p=m=>{let u=i.get(m);return!u&&i.set(m,u=new Map),u},a=(m,u)=>{let f=m.get(u);return!f&&m.set(u,f=new co({noServer:!0})),f},l=(m,u)=>{let f=n.get(m);!f&&n.set(m,f=new Set),f.add(u)},d=(m,u,f,v,M,C)=>{var g;try{(g=f.setup)==null||g.call(f,u,v),u.on("close",()=>m.delete(M)),u.on("error",b=>{s.error(`${N.red(`WebSocket mock error at ${u.path}`)} | ||
${b} | ||
at setup (${C})`,f.log)})}catch(b){s.error(`${N.red(`WebSocket mock error at ${u.path}`)} | ||
${b} | ||
at setup (${C})`,f.log)}},h=(m,u,f,v)=>{m.emit("connection",u,f),u.on("close",()=>{let M=v.findIndex(C=>C.ws===u);M!==-1&&v.splice(M,1)})},y=(m,u,f,v,M)=>{let{cleanupList:C,connectionList:g,context:b}=c.get(u);Ke(C),g.forEach(({ws:R})=>R.removeAllListeners()),u.removeAllListeners(),d(m,u,f,b,v,M),g.forEach(({ws:R,req:E})=>h(u,R,E,g))};(P=o.on)==null||P.call(o,"mock:update-end",m=>{if(!n.has(m))return;let u=n.get(m);if(u)for(let f of u.values())for(let v of o.mockData[f]){if(!v.ws||v.__filepath__!==m)return;let M=p(f);for(let[C,g]of M.entries())y(M,g,v,C,m)}}),t==null||t.on("upgrade",(m,u,f)=>{let{pathname:v,query:M}=W(m.url);if(!v||e.length===0||!e.some(w=>I(w,m.url)))return;let C=o.mockData,g=Object.keys(C).find(w=>Qe(w).test(v));if(!g)return;let b=C[g].find(w=>w.url&&w.ws&&Qe(w.url).test(v));if(!b)return;let R=b.__filepath__;l(R,g);let E=p(g),_=a(E,v),L=c.get(_);if(!L){let w=[],x={onCleanup:U=>w.push(U)};L={cleanupList:w,context:x,connectionList:[]},c.set(_,L),d(E,_,b,x,v,R)}let j=m,G=new io(m,m,r),{query:F}=W(m.headers.referer||"");j.query=M,j.refererQuery=F,j.params=B(g,v),j.getCookie=G.get.bind(G),_.handleUpgrade(j,u,f,w=>{s.info(`${N.magenta(N.bold("WebSocket"))} ${N.green(m.url)} connected ${N.dim(`(${R})`)}`,b.log),L.connectionList.push({req:j,ws:w}),h(_,w,j,L.connectionList)})}),t==null||t.on("close",()=>{for(let m of i.values()){for(let u of m.values()){let f=c.get(u);Ke(f.cleanupList),u.close()}m.clear()}i.clear(),n.clear()})}function Ke(o){let t;for(;t=o.shift();)t==null||t()}function fe(o,t,e,r){let s=X("vite:mock",ao(t.log)?t.log?"info":"error":t.log),n=new ne({include:se(t.include),exclude:se(t.exclude),define:Y(o),alias:o.resolve.alias});n.load(),n.on("mock:update-end",()=>{t.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>n.close());let{httpProxies:i}=Q(o.server.proxy||{}),p=[...se(t.prefix),...i];Xe({loader:n,httpServer:e,proxies:se(t.wsPrefix),cookiesOptions:t.cookiesOptions,logger:s});let a=[];return a.push(uo(n,p,o,t),Je(n,{formidableOptions:t.formidableOptions,proxies:p,cookiesOptions:t.cookiesOptions,priority:t.priority,logger:s})),a.filter(Boolean)}function uo(o,t,e,r){let s={},n=r.cors===!1?!1:e.server.cors!==!1;return n&&e.server.cors!==!1&&(s={...s,...typeof e.server.cors=="boolean"?{}:e.server.cors}),n&&r.cors!==!1&&(s={...s,...typeof r.cors=="boolean"?{}:r.cors}),n?function(i,c,p){let{pathname:a}=W(i.url);if(!a||t.length===0||!t.some(h=>I(h,i.url)))return p();let l=o.mockData;if(!Object.keys(l).find(h=>lo(h).test(a)))return p();po(s)(i,c,p)}:void 0}function Ye({prefix:o=[],wsPrefix:t=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:s=!1,log:n="info",cors:i=!0,formidableOptions:c={},build:p=!1,cookiesOptions:a={},priority:l={}}={}){let d={prefix:o,wsPrefix:t,include:e,exclude:r,reload:s,cors:i,cookiesOptions:a,log:n,formidableOptions:{multiples:!0,...c},priority:l,build:p?Object.assign({serverPort:8080,dist:"mockServer"},typeof p=="object"?p:{}):!1},h=[go(d)];return d.build&&h.push(fo(d)),h}function fo(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 Pe(this,t,o)}}}function go(o){let t={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var n;let r=mo(o.wsPrefix);if(r.length===0||!((n=e.server)!=null&&n.proxy)||Object.keys(e.server.proxy).length===0)return;let s={};Object.keys(e.server.proxy).forEach(i=>{r.includes(i)||(s[i]=e.server.proxy[i])}),e.server.proxy=s,Te(e)},configResolved(e){t=e,e.logger.warn("")},configureServer({middlewares:e,config:r,httpServer:s,ws:n}){fe(r,o,s,n).forEach(c=>e.use(c))},configurePreviewServer({middlewares:e,httpServer:r}){fe(t,o,r).forEach(n=>e.use(n))}}}import{isArray as ko}from"@pengzhanbo/utils";function vn(o){return o}function Mn(o){return e=>(ko(e)?e=e.map(r=>o(r)||r):e=o(e)||e,e)}import{deepClone as Ze,deepEqual as ho,isFunction as yo}from"@pengzhanbo/utils";var ge=new Map,ke=new WeakMap,vo=70,he=class{value;#e;#t;constructor(t){this.value=t,this.#e=Ze(t),this.#t=Date.now()}hotUpdate(t){Date.now()-this.#t<vo||ho(t,this.#e)||(this.value=t,this.#e=Ze(t),this.#t=Date.now())}};function Sn(o,t){ge.has(o)||ge.set(o,new he(t));let e=ge.get(o);if(e.hotUpdate(t),ke.has(e))return ke.get(e);let r=[()=>e.value,s=>{yo(s)&&(s=s(e.value)??e.value),e.value=s}];return Object.defineProperty(r,"value",{get(){return e.value},set(s){e.value=s}}),ke.set(e,r),r}var Rn=Ye;export{Je as baseMiddleware,Mn as createDefineMock,Rn as default,vn as defineMock,Sn as defineMockData,Ye as mockDevServerPlugin,Xe as mockWebSocket,Xt as sortByValidator,Ge as transformMockData}; | ||
at setup (${C})`,f.log)}},h=(m,u,f,v)=>{m.emit("connection",u,f),u.on("close",()=>{let M=v.findIndex(C=>C.ws===u);M!==-1&&v.splice(M,1)})},y=(m,u,f,v,M)=>{let{cleanupList:C,connectionList:g,context:b}=c.get(u);Ke(C),g.forEach(({ws:R})=>R.removeAllListeners()),u.removeAllListeners(),d(m,u,f,b,v,M),g.forEach(({ws:R,req:E})=>h(u,R,E,g))};(P=o.on)==null||P.call(o,"mock:update-end",m=>{if(!n.has(m))return;let u=n.get(m);if(u)for(let f of u.values())for(let v of o.mockData[f]){if(!v.ws||v.__filepath__!==m)return;let M=p(f);for(let[C,g]of M.entries())y(M,g,v,C,m)}}),t==null||t.on("upgrade",(m,u,f)=>{let{pathname:v,query:M}=W(m.url);if(!v||e.length===0||!e.some(w=>I(w,m.url)))return;let C=o.mockData,g=Object.keys(C).find(w=>Qe(w).test(v));if(!g)return;let b=C[g].find(w=>w.url&&w.ws&&Qe(w.url).test(v));if(!b)return;let R=b.__filepath__;l(R,g);let E=p(g),_=a(E,v),L=c.get(_);if(!L){let w=[],x={onCleanup:U=>w.push(U)};L={cleanupList:w,context:x,connectionList:[]},c.set(_,L),d(E,_,b,x,v,R)}let j=m,G=new io(m,m,r),{query:F}=W(m.headers.referer||"");j.query=M,j.refererQuery=F,j.params=q(g,v),j.getCookie=G.get.bind(G),_.handleUpgrade(j,u,f,w=>{s.info(`${N.magenta(N.bold("WebSocket"))} ${N.green(m.url)} connected ${N.dim(`(${R})`)}`,b.log),L.connectionList.push({req:j,ws:w}),h(_,w,j,L.connectionList)})}),t==null||t.on("close",()=>{for(let m of i.values()){for(let u of m.values()){let f=c.get(u);Ke(f.cleanupList),u.close()}m.clear()}i.clear(),n.clear()})}function Ke(o){let t;for(;t=o.shift();)t==null||t()}function fe(o,t,e,r){let s=X("vite:mock",ao(t.log)?t.log?"info":"error":t.log),n=new ne({include:se(t.include),exclude:se(t.exclude),define:Y(o),alias:o.resolve.alias});n.load(),n.on("mock:update-end",()=>{t.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>n.close());let{httpProxies:i}=Q(o.server.proxy||{}),p=[...se(t.prefix),...i];Xe({loader:n,httpServer:e,proxies:se(t.wsPrefix),cookiesOptions:t.cookiesOptions,logger:s});let a=[];return a.push(uo(n,p,o,t),Je(n,{formidableOptions:t.formidableOptions,proxies:p,cookiesOptions:t.cookiesOptions,priority:t.priority,logger:s})),a.filter(Boolean)}function uo(o,t,e,r){let s={},n=r.cors===!1?!1:e.server.cors!==!1;return n&&e.server.cors!==!1&&(s={...s,...typeof e.server.cors=="boolean"?{}:e.server.cors}),n&&r.cors!==!1&&(s={...s,...typeof r.cors=="boolean"?{}:r.cors}),n?function(i,c,p){let{pathname:a}=W(i.url);if(!a||t.length===0||!t.some(h=>I(h,i.url)))return p();let l=o.mockData;if(!Object.keys(l).find(h=>lo(h).test(a)))return p();po(s)(i,c,p)}:void 0}function Ye({prefix:o=[],wsPrefix:t=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:s=!1,log:n="info",cors:i=!0,formidableOptions:c={},build:p=!1,cookiesOptions:a={},priority:l={}}={}){let d={prefix:o,wsPrefix:t,include:e,exclude:r,reload:s,cors:i,cookiesOptions:a,log:n,formidableOptions:{multiples:!0,...c},priority:l,build:p?Object.assign({serverPort:8080,dist:"mockServer"},typeof p=="object"?p:{}):!1},h=[go(d)];return d.build&&h.push(fo(d)),h}function fo(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 Pe(this,t,o)}}}function go(o){let t={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var s;let r=mo(o.wsPrefix);if(r.length&&((s=e.server)!=null&&s.proxy)){let n={};Object.keys(e.server.proxy).forEach(i=>{r.includes(i)||(n[i]=e.server.proxy[i])}),e.server.proxy=n}Te(e)},configResolved(e){t=e,e.logger.warn("")},configureServer({middlewares:e,config:r,httpServer:s,ws:n}){fe(r,o,s,n).forEach(c=>e.use(c))},configurePreviewServer({middlewares:e,httpServer:r}){fe(t,o,r).forEach(n=>e.use(n))}}}import{isArray as ko}from"@pengzhanbo/utils";function vn(o){return o}function Mn(o){return e=>(ko(e)?e=e.map(r=>o(r)||r):e=o(e)||e,e)}import{deepClone as Ze,deepEqual as ho,isFunction as yo}from"@pengzhanbo/utils";var ge=new Map,ke=new WeakMap,vo=70,he=class{value;#e;#t;constructor(t){this.value=t,this.#e=Ze(t),this.#t=Date.now()}hotUpdate(t){Date.now()-this.#t<vo||ho(t,this.#e)||(this.value=t,this.#e=Ze(t),this.#t=Date.now())}};function Sn(o,t){ge.has(o)||ge.set(o,new he(t));let e=ge.get(o);if(e.hotUpdate(t),ke.has(e))return ke.get(e);let r=[()=>e.value,s=>{yo(s)&&(s=s(e.value)??e.value),e.value=s}];return Object.defineProperty(r,"value",{get(){return e.value},set(s){e.value=s}}),ke.set(e,r),r}var Rn=Ye;export{Je as baseMiddleware,Mn as createDefineMock,Rn as default,vn as defineMock,Sn as defineMockData,Ye as mockDevServerPlugin,Xe as mockWebSocket,Xt as sortByValidator,Ge as transformMockData}; |
{ | ||
"name": "vite-plugin-mock-dev-server", | ||
"version": "1.3.4-beta.0", | ||
"version": "1.3.4-beta.1", | ||
"keywords": [ | ||
@@ -5,0 +5,0 @@ "vite", |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
943
155475