vite-plugin-mock-dev-server 1.7.3 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -165,7 +165,7 @@ import bodyParser from "co-body";
165
165
  import formidable from "formidable";
166
166
  async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
167
167
  const method = req.method.toUpperCase();
168
- if (["GET", "DELETE", "HEAD"].includes(method))
168
+ if (["HEAD", "OPTIONS"].includes(method))
169
169
  return void 0;
170
170
  const type = req.headers["content-type"]?.toLocaleLowerCase() || "";
171
171
  const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
@@ -66,8 +66,65 @@ function defineMockData(key, initialData) {
66
66
  return res;
67
67
  }
68
68
 
69
+ // src/core/sse.ts
70
+ import { Transform } from "node:stream";
71
+ var SSEStream = class extends Transform {
72
+ constructor(req) {
73
+ super({ objectMode: true });
74
+ req.socket.setKeepAlive(true);
75
+ req.socket.setNoDelay(true);
76
+ req.socket.setTimeout(0);
77
+ }
78
+ pipe(destination, options) {
79
+ if (destination.writeHead) {
80
+ destination.writeHead(200, {
81
+ "Content-Type": "text/event-stream; charset=utf-8",
82
+ "Transfer-Encoding": "identity",
83
+ "Cache-Control": "no-cache",
84
+ "Connection": "keep-alive"
85
+ });
86
+ destination.flushHeaders?.();
87
+ }
88
+ destination.write(":ok\n\n");
89
+ return super.pipe(destination, options);
90
+ }
91
+ _transform(message, encoding, callback) {
92
+ if (message.comment)
93
+ this.push(`: ${message.comment}
94
+ `);
95
+ if (message.event)
96
+ this.push(`event: ${message.event}
97
+ `);
98
+ if (message.id)
99
+ this.push(`id: ${message.id}
100
+ `);
101
+ if (message.retry)
102
+ this.push(`retry: ${message.retry}
103
+ `);
104
+ if (message.data)
105
+ this.push(dataString(message.data));
106
+ this.push("\n");
107
+ callback();
108
+ }
109
+ write(message, ...args) {
110
+ return super.write(message, ...args);
111
+ }
112
+ };
113
+ function dataString(data) {
114
+ if (typeof data === "object")
115
+ return dataString(JSON.stringify(data));
116
+ return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}
117
+ `).join("");
118
+ }
119
+ function createSSEStream(req, res) {
120
+ const sse = new SSEStream(req);
121
+ sse.pipe(res);
122
+ return sse;
123
+ }
124
+
69
125
  export {
70
126
  defineMock,
71
127
  createDefineMock,
72
- defineMockData
128
+ defineMockData,
129
+ createSSEStream
73
130
  };
@@ -165,7 +165,7 @@ var _cobody = require('co-body'); var _cobody2 = _interopRequireDefault(_cobody)
165
165
  var _formidable = require('formidable'); var _formidable2 = _interopRequireDefault(_formidable);
166
166
  async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
167
167
  const method = req.method.toUpperCase();
168
- if (["GET", "DELETE", "HEAD"].includes(method))
168
+ if (["HEAD", "OPTIONS"].includes(method))
169
169
  return void 0;
170
170
  const type = _optionalChain([req, 'access', _ => _.headers, 'access', _2 => _2["content-type"], 'optionalAccess', _3 => _3.toLocaleLowerCase, 'call', _4 => _4()]) || "";
171
171
  const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
@@ -0,0 +1,130 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core/defineMock.ts
2
+ var _utils = require('@pengzhanbo/utils');
3
+ function defineMock(config) {
4
+ return config;
5
+ }
6
+ function createDefineMock(transformer) {
7
+ const define = (config) => {
8
+ if (_utils.isArray.call(void 0, config))
9
+ config = config.map((item) => transformer(item) || item);
10
+ else
11
+ config = transformer(config) || config;
12
+ return config;
13
+ };
14
+ return define;
15
+ }
16
+
17
+ // src/core/defineMockData.ts
18
+
19
+ var mockDataCache = /* @__PURE__ */ new Map();
20
+ var responseCache = /* @__PURE__ */ new WeakMap();
21
+ var staleInterval = 70;
22
+ var CacheImpl = class {
23
+
24
+ // 初始化数据的备份,用于 判断 传入的初始化数据是否发生变更
25
+ #initialValue;
26
+ #lastUpdate;
27
+ constructor(value) {
28
+ this.value = value;
29
+ this.#initialValue = _utils.deepClone.call(void 0, value);
30
+ this.#lastUpdate = Date.now();
31
+ }
32
+ hotUpdate(value) {
33
+ if (Date.now() - this.#lastUpdate < staleInterval)
34
+ return;
35
+ if (!_utils.deepEqual.call(void 0, value, this.#initialValue)) {
36
+ this.value = value;
37
+ this.#initialValue = _utils.deepClone.call(void 0, value);
38
+ this.#lastUpdate = Date.now();
39
+ }
40
+ }
41
+ };
42
+ function defineMockData(key, initialData) {
43
+ if (!mockDataCache.has(key))
44
+ mockDataCache.set(key, new CacheImpl(initialData));
45
+ const cache = mockDataCache.get(key);
46
+ cache.hotUpdate(initialData);
47
+ if (responseCache.has(cache))
48
+ return responseCache.get(cache);
49
+ const res = [
50
+ () => cache.value,
51
+ (val) => {
52
+ if (_utils.isFunction.call(void 0, val))
53
+ val = _nullishCoalesce(val(cache.value), () => ( cache.value));
54
+ cache.value = val;
55
+ }
56
+ ];
57
+ Object.defineProperty(res, "value", {
58
+ get() {
59
+ return cache.value;
60
+ },
61
+ set(val) {
62
+ cache.value = val;
63
+ }
64
+ });
65
+ responseCache.set(cache, res);
66
+ return res;
67
+ }
68
+
69
+ // src/core/sse.ts
70
+ var _stream = require('stream');
71
+ var SSEStream = class extends _stream.Transform {
72
+ constructor(req) {
73
+ super({ objectMode: true });
74
+ req.socket.setKeepAlive(true);
75
+ req.socket.setNoDelay(true);
76
+ req.socket.setTimeout(0);
77
+ }
78
+ pipe(destination, options) {
79
+ if (destination.writeHead) {
80
+ destination.writeHead(200, {
81
+ "Content-Type": "text/event-stream; charset=utf-8",
82
+ "Transfer-Encoding": "identity",
83
+ "Cache-Control": "no-cache",
84
+ "Connection": "keep-alive"
85
+ });
86
+ _optionalChain([destination, 'access', _ => _.flushHeaders, 'optionalCall', _2 => _2()]);
87
+ }
88
+ destination.write(":ok\n\n");
89
+ return super.pipe(destination, options);
90
+ }
91
+ _transform(message, encoding, callback) {
92
+ if (message.comment)
93
+ this.push(`: ${message.comment}
94
+ `);
95
+ if (message.event)
96
+ this.push(`event: ${message.event}
97
+ `);
98
+ if (message.id)
99
+ this.push(`id: ${message.id}
100
+ `);
101
+ if (message.retry)
102
+ this.push(`retry: ${message.retry}
103
+ `);
104
+ if (message.data)
105
+ this.push(dataString(message.data));
106
+ this.push("\n");
107
+ callback();
108
+ }
109
+ write(message, ...args) {
110
+ return super.write(message, ...args);
111
+ }
112
+ };
113
+ function dataString(data) {
114
+ if (typeof data === "object")
115
+ return dataString(JSON.stringify(data));
116
+ return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}
117
+ `).join("");
118
+ }
119
+ function createSSEStream(req, res) {
120
+ const sse = new SSEStream(req);
121
+ sse.pipe(res);
122
+ return sse;
123
+ }
124
+
125
+
126
+
127
+
128
+
129
+
130
+ exports.defineMock = defineMock; exports.createDefineMock = createDefineMock; exports.defineMockData = defineMockData; exports.createSSEStream = createSSEStream;
package/dist/helper.cjs CHANGED
@@ -2,9 +2,11 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkFND5XIG2cjs = require('./chunk-FND5XIG2.cjs');
6
5
 
6
+ var _chunkJNSDHVCKcjs = require('./chunk-JNSDHVCK.cjs');
7
7
 
8
8
 
9
9
 
10
- exports.createDefineMock = _chunkFND5XIG2cjs.createDefineMock; exports.defineMock = _chunkFND5XIG2cjs.defineMock; exports.defineMockData = _chunkFND5XIG2cjs.defineMockData;
10
+
11
+
12
+ exports.createDefineMock = _chunkJNSDHVCKcjs.createDefineMock; exports.createSSEStream = _chunkJNSDHVCKcjs.createSSEStream; exports.defineMock = _chunkJNSDHVCKcjs.defineMock; exports.defineMockData = _chunkJNSDHVCKcjs.defineMockData;
package/dist/helper.d.cts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { a as MockHttpItem, d as MockWebsocketItem, b as MockOptions } from './types-BYspd62h.cjs';
2
2
  export { c as MockRequest } from './types-BYspd62h.cjs';
3
+ import { IncomingMessage, ServerResponse, OutgoingHttpHeaders } from 'node:http';
4
+ import { Transform } from 'node:stream';
3
5
  import 'co-body';
4
6
  import 'cookies';
5
7
  import 'cors';
6
8
  import 'formidable';
7
9
  import 'node:buffer';
8
- import 'node:http';
9
- import 'node:stream';
10
10
  import 'vite';
11
11
  import 'ws';
12
12
 
@@ -84,4 +84,40 @@ type MockData<T = any> = readonly [
84
84
  };
85
85
  declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
86
86
 
87
- export { type MockData, MockHttpItem, MockOptions, MockWebsocketItem, createDefineMock, defineMock, defineMockData };
87
+ interface SSEMessage {
88
+ data?: string | object;
89
+ comment?: string;
90
+ event?: string;
91
+ id?: string;
92
+ retry?: number;
93
+ }
94
+ interface WriteHeaders {
95
+ writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
96
+ flushHeaders?: () => void;
97
+ }
98
+ type HeaderStream = NodeJS.WritableStream & WriteHeaders;
99
+ /**
100
+ * Transforms "messages" to W3C event stream content.
101
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
102
+ * A message is an object with one or more of the following properties:
103
+ * - data (String or object, which gets turned into JSON)
104
+ * - event
105
+ * - id
106
+ * - retry
107
+ * - comment
108
+ *
109
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
110
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
111
+ */
112
+ declare class SSEStream extends Transform {
113
+ constructor(req: IncomingMessage);
114
+ pipe<T extends HeaderStream>(destination: T, options?: {
115
+ end?: boolean;
116
+ }): T;
117
+ _transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
118
+ write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
119
+ write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
120
+ }
121
+ declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
122
+
123
+ export { type HeaderStream, type MockData, MockHttpItem, MockOptions, MockWebsocketItem, type SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
package/dist/helper.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { a as MockHttpItem, d as MockWebsocketItem, b as MockOptions } from './types-BYspd62h.js';
2
2
  export { c as MockRequest } from './types-BYspd62h.js';
3
+ import { IncomingMessage, ServerResponse, OutgoingHttpHeaders } from 'node:http';
4
+ import { Transform } from 'node:stream';
3
5
  import 'co-body';
4
6
  import 'cookies';
5
7
  import 'cors';
6
8
  import 'formidable';
7
9
  import 'node:buffer';
8
- import 'node:http';
9
- import 'node:stream';
10
10
  import 'vite';
11
11
  import 'ws';
12
12
 
@@ -84,4 +84,40 @@ type MockData<T = any> = readonly [
84
84
  };
85
85
  declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
86
86
 
87
- export { type MockData, MockHttpItem, MockOptions, MockWebsocketItem, createDefineMock, defineMock, defineMockData };
87
+ interface SSEMessage {
88
+ data?: string | object;
89
+ comment?: string;
90
+ event?: string;
91
+ id?: string;
92
+ retry?: number;
93
+ }
94
+ interface WriteHeaders {
95
+ writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
96
+ flushHeaders?: () => void;
97
+ }
98
+ type HeaderStream = NodeJS.WritableStream & WriteHeaders;
99
+ /**
100
+ * Transforms "messages" to W3C event stream content.
101
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
102
+ * A message is an object with one or more of the following properties:
103
+ * - data (String or object, which gets turned into JSON)
104
+ * - event
105
+ * - id
106
+ * - retry
107
+ * - comment
108
+ *
109
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
110
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
111
+ */
112
+ declare class SSEStream extends Transform {
113
+ constructor(req: IncomingMessage);
114
+ pipe<T extends HeaderStream>(destination: T, options?: {
115
+ end?: boolean;
116
+ }): T;
117
+ _transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
118
+ write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
119
+ write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
120
+ }
121
+ declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
122
+
123
+ export { type HeaderStream, type MockData, MockHttpItem, MockOptions, MockWebsocketItem, type SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
package/dist/helper.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  createDefineMock,
3
+ createSSEStream,
3
4
  defineMock,
4
5
  defineMockData
5
- } from "./chunk-VMBOC7DG.js";
6
+ } from "./chunk-4RQVTS77.js";
6
7
  export {
7
8
  createDefineMock,
9
+ createSSEStream,
8
10
  defineMock,
9
11
  defineMockData
10
12
  };
package/dist/index.cjs CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkFND5XIG2cjs = require('./chunk-FND5XIG2.cjs');
6
5
 
6
+ var _chunkJNSDHVCKcjs = require('./chunk-JNSDHVCK.cjs');
7
7
 
8
8
 
9
9
 
@@ -18,7 +18,8 @@ var _chunkFND5XIG2cjs = require('./chunk-FND5XIG2.cjs');
18
18
 
19
19
 
20
20
 
21
- var _chunkJP6LPDGGcjs = require('./chunk-JP6LPDGG.cjs');
21
+
22
+ var _chunkGWNR3FAVcjs = require('./chunk-GWNR3FAV.cjs');
22
23
 
23
24
  // src/plugin.ts
24
25
  var _utils = require('@pengzhanbo/utils');
@@ -181,7 +182,7 @@ async function generateMockServer(ctx, options) {
181
182
  const cwd = options.cwd || _process2.default.cwd();
182
183
  let pkg = {};
183
184
  try {
184
- const pkgStr = _chunkJP6LPDGGcjs.lookupFile.call(void 0, options.context, ["package.json"]);
185
+ const pkgStr = _chunkGWNR3FAVcjs.lookupFile.call(void 0, options.context, ["package.json"]);
185
186
  if (pkgStr)
186
187
  pkg = JSON.parse(pkgStr);
187
188
  } catch (e3) {
@@ -267,7 +268,7 @@ function generatePackageJson(pkg, mockDeps) {
267
268
  },
268
269
  dependencies: {
269
270
  connect: "^3.7.0",
270
- ["vite-plugin-mock-dev-server"]: `^${"1.7.2"}`,
271
+ ["vite-plugin-mock-dev-server"]: `^${"1.8.0"}`,
271
272
  cors: "^2.8.5"
272
273
  },
273
274
  pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
@@ -328,7 +329,7 @@ async function generateMockEntryCode(cwd, include, exclude) {
328
329
  let importers = "";
329
330
  const exporters = [];
330
331
  mockFiles.forEach((filepath, index) => {
331
- const file = _chunkJP6LPDGGcjs.normalizePath.call(void 0, _path2.default.join(cwd, filepath));
332
+ const file = _chunkGWNR3FAVcjs.normalizePath.call(void 0, _path2.default.join(cwd, filepath));
332
333
  importers += `import * as m${index} from '${file}';
333
334
  `;
334
335
  exporters.push(`[m${index}, '${filepath}']`);
@@ -365,7 +366,7 @@ var MockCompiler = (_class = class extends _events2.default {
365
366
  this.options = options;
366
367
  this.cwd = options.cwd || _process2.default.cwd();
367
368
  try {
368
- const pkg = _chunkJP6LPDGGcjs.lookupFile.call(void 0, this.cwd, ["package.json"]);
369
+ const pkg = _chunkGWNR3FAVcjs.lookupFile.call(void 0, this.cwd, ["package.json"]);
369
370
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
370
371
  } catch (e4) {
371
372
  }
@@ -419,19 +420,19 @@ var MockCompiler = (_class = class extends _events2.default {
419
420
  if (otherGlob.length > 0)
420
421
  otherGlob.forEach((glob) => watcher.add(glob));
421
422
  watcher.on("add", async (filepath) => {
422
- filepath = _chunkJP6LPDGGcjs.normalizePath.call(void 0, filepath);
423
+ filepath = _chunkGWNR3FAVcjs.normalizePath.call(void 0, filepath);
423
424
  this.emit("mock:update", filepath);
424
- _chunkJP6LPDGGcjs.debug.call(void 0, "watcher:add", filepath);
425
+ _chunkGWNR3FAVcjs.debug.call(void 0, "watcher:add", filepath);
425
426
  });
426
427
  watcher.on("change", async (filepath) => {
427
- filepath = _chunkJP6LPDGGcjs.normalizePath.call(void 0, filepath);
428
+ filepath = _chunkGWNR3FAVcjs.normalizePath.call(void 0, filepath);
428
429
  this.emit("mock:update", filepath);
429
- _chunkJP6LPDGGcjs.debug.call(void 0, "watcher:change", filepath);
430
+ _chunkGWNR3FAVcjs.debug.call(void 0, "watcher:change", filepath);
430
431
  });
431
432
  watcher.on("unlink", async (filepath) => {
432
- filepath = _chunkJP6LPDGGcjs.normalizePath.call(void 0, filepath);
433
+ filepath = _chunkGWNR3FAVcjs.normalizePath.call(void 0, filepath);
433
434
  this.emit("mock:unlink", filepath);
434
- _chunkJP6LPDGGcjs.debug.call(void 0, "watcher:unlink", filepath);
435
+ _chunkGWNR3FAVcjs.debug.call(void 0, "watcher:unlink", filepath);
435
436
  });
436
437
  }
437
438
  /**
@@ -445,14 +446,14 @@ var MockCompiler = (_class = class extends _events2.default {
445
446
  cwd: this.cwd
446
447
  });
447
448
  this.depsWatcher.on("change", (filepath) => {
448
- filepath = _chunkJP6LPDGGcjs.normalizePath.call(void 0, filepath);
449
+ filepath = _chunkGWNR3FAVcjs.normalizePath.call(void 0, filepath);
449
450
  const mockFiles = this.moduleDeps.get(filepath);
450
451
  _optionalChain([mockFiles, 'optionalAccess', _4 => _4.forEach, 'call', _5 => _5((file) => {
451
452
  this.emit("mock:update", file);
452
453
  })]);
453
454
  });
454
455
  this.depsWatcher.on("unlink", (filepath) => {
455
- filepath = _chunkJP6LPDGGcjs.normalizePath.call(void 0, filepath);
456
+ filepath = _chunkGWNR3FAVcjs.normalizePath.call(void 0, filepath);
456
457
  this.moduleDeps.delete(filepath);
457
458
  });
458
459
  this.on("update:deps", () => {
@@ -469,7 +470,7 @@ var MockCompiler = (_class = class extends _events2.default {
469
470
  _optionalChain([this, 'access', _9 => _9.depsWatcher, 'optionalAccess', _10 => _10.close, 'call', _11 => _11()]);
470
471
  }
471
472
  updateMockList() {
472
- this._mockData = _chunkJP6LPDGGcjs.transformMockData.call(void 0, this.moduleCache);
473
+ this._mockData = _chunkGWNR3FAVcjs.transformMockData.call(void 0, this.moduleCache);
473
474
  }
474
475
  updateModuleDeps(filepath, deps) {
475
476
  Object.keys(deps).forEach((mPath) => {
@@ -500,7 +501,7 @@ var MockCompiler = (_class = class extends _events2.default {
500
501
  );
501
502
  try {
502
503
  const raw = await loadFromCode({ filepath, code, isESM, cwd: this.cwd }) || {};
503
- this.moduleCache.set(filepath, _chunkJP6LPDGGcjs.transformRawData.call(void 0, raw, filepath));
504
+ this.moduleCache.set(filepath, _chunkGWNR3FAVcjs.transformRawData.call(void 0, raw, filepath));
504
505
  this.updateModuleDeps(filepath, deps);
505
506
  } catch (e) {
506
507
  console.error(e);
@@ -517,7 +518,7 @@ function mockServerMiddleware(options, server, ws) {
517
518
  _optionalChain([ws, 'optionalAccess', _12 => _12.send, 'call', _13 => _13({ type: "full-reload" })]);
518
519
  });
519
520
  _optionalChain([server, 'optionalAccess', _14 => _14.on, 'call', _15 => _15("close", () => compiler.close())]);
520
- _chunkJP6LPDGGcjs.mockWebSocket.call(void 0, compiler, server, options);
521
+ _chunkGWNR3FAVcjs.mockWebSocket.call(void 0, compiler, server, options);
521
522
  const middlewares = [];
522
523
  middlewares.push(
523
524
  /**
@@ -532,14 +533,14 @@ function mockServerMiddleware(options, server, ws) {
532
533
  * 而用户的配置也仅对 mock 的接口生效。
533
534
  */
534
535
  corsMiddleware(compiler, options),
535
- _chunkJP6LPDGGcjs.baseMiddleware.call(void 0, compiler, options)
536
+ _chunkGWNR3FAVcjs.baseMiddleware.call(void 0, compiler, options)
536
537
  );
537
538
  return middlewares.filter(Boolean);
538
539
  }
539
540
  function corsMiddleware(compiler, { proxies, cors: corsOptions }) {
540
541
  return !corsOptions ? void 0 : function(req, res, next) {
541
- const { pathname } = _chunkJP6LPDGGcjs.urlParse.call(void 0, req.url);
542
- if (!pathname || proxies.length === 0 || !proxies.some((context) => _chunkJP6LPDGGcjs.doesProxyContextMatchUrl.call(void 0, context, req.url))) {
542
+ const { pathname } = _chunkGWNR3FAVcjs.urlParse.call(void 0, req.url);
543
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => _chunkGWNR3FAVcjs.doesProxyContextMatchUrl.call(void 0, context, req.url))) {
543
544
  return next();
544
545
  }
545
546
  const mockData = compiler.mockData;
@@ -652,8 +653,8 @@ function resolvePluginOptions({
652
653
  bodyParserOptions = {},
653
654
  priority = {}
654
655
  }, config) {
655
- const logger = _chunkJP6LPDGGcjs.createLogger.call(void 0, "vite:mock", _utils.isBoolean.call(void 0, log) ? log ? "info" : "error" : log);
656
- const { httpProxies } = _chunkJP6LPDGGcjs.ensureProxies.call(void 0, config.server.proxy || {});
656
+ const logger = _chunkGWNR3FAVcjs.createLogger.call(void 0, "vite:mock", _utils.isBoolean.call(void 0, log) ? log ? "info" : "error" : log);
657
+ const { httpProxies } = _chunkGWNR3FAVcjs.ensureProxies.call(void 0, config.server.proxy || {});
657
658
  const proxies = _utils.uniq.call(void 0, [..._utils.toArray.call(void 0, prefix), ...httpProxies]);
658
659
  const wsProxies = _utils.toArray.call(void 0, wsPrefix);
659
660
  if (!proxies.length && !wsProxies.length)
@@ -754,7 +755,7 @@ function serverPlugin(options) {
754
755
  });
755
756
  config.server.proxy = proxy;
756
757
  }
757
- _chunkJP6LPDGGcjs.recoverRequest.call(void 0, config);
758
+ _chunkGWNR3FAVcjs.recoverRequest.call(void 0, config);
758
759
  },
759
760
  configResolved(config) {
760
761
  resolvedOptions = resolvePluginOptions(options, config);
@@ -786,4 +787,5 @@ var src_default = mockDevServerPlugin;
786
787
 
787
788
 
788
789
 
789
- exports.baseMiddleware = _chunkJP6LPDGGcjs.baseMiddleware; exports.createDefineMock = _chunkFND5XIG2cjs.createDefineMock; exports.createLogger = _chunkJP6LPDGGcjs.createLogger; exports.default = src_default; exports.defineMock = _chunkFND5XIG2cjs.defineMock; exports.defineMockData = _chunkFND5XIG2cjs.defineMockData; exports.logLevels = _chunkJP6LPDGGcjs.logLevels; exports.mockDevServerPlugin = mockDevServerPlugin; exports.mockWebSocket = _chunkJP6LPDGGcjs.mockWebSocket; exports.sortByValidator = _chunkJP6LPDGGcjs.sortByValidator; exports.transformMockData = _chunkJP6LPDGGcjs.transformMockData; exports.transformRawData = _chunkJP6LPDGGcjs.transformRawData;
790
+
791
+ exports.baseMiddleware = _chunkGWNR3FAVcjs.baseMiddleware; exports.createDefineMock = _chunkJNSDHVCKcjs.createDefineMock; exports.createLogger = _chunkGWNR3FAVcjs.createLogger; exports.createSSEStream = _chunkJNSDHVCKcjs.createSSEStream; exports.default = src_default; exports.defineMock = _chunkJNSDHVCKcjs.defineMock; exports.defineMockData = _chunkJNSDHVCKcjs.defineMockData; exports.logLevels = _chunkGWNR3FAVcjs.logLevels; exports.mockDevServerPlugin = mockDevServerPlugin; exports.mockWebSocket = _chunkGWNR3FAVcjs.mockWebSocket; exports.sortByValidator = _chunkGWNR3FAVcjs.sortByValidator; exports.transformMockData = _chunkGWNR3FAVcjs.transformMockData; exports.transformRawData = _chunkGWNR3FAVcjs.transformRawData;
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Plugin } from 'vite';
2
2
  import { M as MockServerPluginOptions } from './types-BYspd62h.cjs';
3
3
  export { F as FormidableFile, a as MockHttpItem, b as MockOptions, c as MockRequest, d as MockWebsocketItem } from './types-BYspd62h.cjs';
4
- export { MockData, createDefineMock, defineMock, defineMockData } from './helper.cjs';
4
+ export { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from './helper.cjs';
5
5
  export { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from './server.cjs';
6
6
  import 'co-body';
7
7
  import 'cookies';
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Plugin } from 'vite';
2
2
  import { M as MockServerPluginOptions } from './types-BYspd62h.js';
3
3
  export { F as FormidableFile, a as MockHttpItem, b as MockOptions, c as MockRequest, d as MockWebsocketItem } from './types-BYspd62h.js';
4
- export { MockData, createDefineMock, defineMock, defineMockData } from './helper.js';
4
+ export { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from './helper.js';
5
5
  export { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from './server.js';
6
6
  import 'co-body';
7
7
  import 'cookies';
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import {
2
2
  createDefineMock,
3
+ createSSEStream,
3
4
  defineMock,
4
5
  defineMockData
5
- } from "./chunk-VMBOC7DG.js";
6
+ } from "./chunk-4RQVTS77.js";
6
7
  import {
7
8
  baseMiddleware,
8
9
  createLogger,
@@ -18,7 +19,7 @@ import {
18
19
  transformMockData,
19
20
  transformRawData,
20
21
  urlParse
21
- } from "./chunk-FUNGHLD3.js";
22
+ } from "./chunk-2IAQM65M.js";
22
23
 
23
24
  // src/plugin.ts
24
25
  import { toArray as toArray4 } from "@pengzhanbo/utils";
@@ -267,7 +268,7 @@ function generatePackageJson(pkg, mockDeps) {
267
268
  },
268
269
  dependencies: {
269
270
  connect: "^3.7.0",
270
- ["vite-plugin-mock-dev-server"]: `^${"1.7.2"}`,
271
+ ["vite-plugin-mock-dev-server"]: `^${"1.8.0"}`,
271
272
  cors: "^2.8.5"
272
273
  },
273
274
  pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
@@ -777,6 +778,7 @@ export {
777
778
  baseMiddleware,
778
779
  createDefineMock,
779
780
  createLogger,
781
+ createSSEStream,
780
782
  src_default as default,
781
783
  defineMock,
782
784
  defineMockData,
package/dist/server.cjs CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkJP6LPDGGcjs = require('./chunk-JP6LPDGG.cjs');
9
+ var _chunkGWNR3FAVcjs = require('./chunk-GWNR3FAV.cjs');
10
10
 
11
11
 
12
12
 
@@ -15,4 +15,4 @@ var _chunkJP6LPDGGcjs = require('./chunk-JP6LPDGG.cjs');
15
15
 
16
16
 
17
17
 
18
- exports.baseMiddleware = _chunkJP6LPDGGcjs.baseMiddleware; exports.createLogger = _chunkJP6LPDGGcjs.createLogger; exports.logLevels = _chunkJP6LPDGGcjs.logLevels; exports.mockWebSocket = _chunkJP6LPDGGcjs.mockWebSocket; exports.sortByValidator = _chunkJP6LPDGGcjs.sortByValidator; exports.transformMockData = _chunkJP6LPDGGcjs.transformMockData; exports.transformRawData = _chunkJP6LPDGGcjs.transformRawData;
18
+ exports.baseMiddleware = _chunkGWNR3FAVcjs.baseMiddleware; exports.createLogger = _chunkGWNR3FAVcjs.createLogger; exports.logLevels = _chunkGWNR3FAVcjs.logLevels; exports.mockWebSocket = _chunkGWNR3FAVcjs.mockWebSocket; exports.sortByValidator = _chunkGWNR3FAVcjs.sortByValidator; exports.transformMockData = _chunkGWNR3FAVcjs.transformMockData; exports.transformRawData = _chunkGWNR3FAVcjs.transformRawData;
package/dist/server.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  sortByValidator,
7
7
  transformMockData,
8
8
  transformRawData
9
- } from "./chunk-FUNGHLD3.js";
9
+ } from "./chunk-2IAQM65M.js";
10
10
  export {
11
11
  baseMiddleware,
12
12
  createLogger,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "vite-plugin-mock-dev-server",
3
3
  "type": "module",
4
- "version": "1.7.3",
4
+ "version": "1.8.1",
5
5
  "author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
6
6
  "license": "MIT",
7
7
  "homepage": "https://vite-plugin-mock-dev-server.netlify.app",
@@ -56,7 +56,7 @@
56
56
  "dist"
57
57
  ],
58
58
  "engines": {
59
- "node": "^18 || >= 20"
59
+ "node": "^18 || ^20 || >=22"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "esbuild": ">=0.21.0",
@@ -69,7 +69,7 @@
69
69
  },
70
70
  "dependencies": {
71
71
  "@pengzhanbo/utils": "^1.1.2",
72
- "@rollup/pluginutils": "^5.1.2",
72
+ "@rollup/pluginutils": "^5.1.3",
73
73
  "chokidar": "3.6.0",
74
74
  "co-body": "^6.2.0",
75
75
  "cookies": "^0.9.1",
@@ -77,17 +77,17 @@
77
77
  "debug": "^4.3.7",
78
78
  "fast-glob": "^3.3.2",
79
79
  "formidable": "2.1.2",
80
- "http-status": "^1.7.4",
80
+ "http-status": "^2.0.0",
81
81
  "is-core-module": "^2.15.1",
82
82
  "json5": "^2.2.3",
83
83
  "mime-types": "^2.1.35",
84
84
  "path-to-regexp": "6.2.2",
85
- "picocolors": "^1.1.0",
85
+ "picocolors": "^1.1.1",
86
86
  "ws": "^8.18.0"
87
87
  },
88
88
  "devDependencies": {
89
89
  "esbuild": "^0.24.0",
90
- "vite": "^5.4.7"
90
+ "vite": "^6.0.3"
91
91
  },
92
92
  "publishConfig": {
93
93
  "access": "public"
@@ -1,73 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/core/defineMock.ts
2
- var _utils = require('@pengzhanbo/utils');
3
- function defineMock(config) {
4
- return config;
5
- }
6
- function createDefineMock(transformer) {
7
- const define = (config) => {
8
- if (_utils.isArray.call(void 0, config))
9
- config = config.map((item) => transformer(item) || item);
10
- else
11
- config = transformer(config) || config;
12
- return config;
13
- };
14
- return define;
15
- }
16
-
17
- // src/core/defineMockData.ts
18
-
19
- var mockDataCache = /* @__PURE__ */ new Map();
20
- var responseCache = /* @__PURE__ */ new WeakMap();
21
- var staleInterval = 70;
22
- var CacheImpl = class {
23
-
24
- // 初始化数据的备份,用于 判断 传入的初始化数据是否发生变更
25
- #initialValue;
26
- #lastUpdate;
27
- constructor(value) {
28
- this.value = value;
29
- this.#initialValue = _utils.deepClone.call(void 0, value);
30
- this.#lastUpdate = Date.now();
31
- }
32
- hotUpdate(value) {
33
- if (Date.now() - this.#lastUpdate < staleInterval)
34
- return;
35
- if (!_utils.deepEqual.call(void 0, value, this.#initialValue)) {
36
- this.value = value;
37
- this.#initialValue = _utils.deepClone.call(void 0, value);
38
- this.#lastUpdate = Date.now();
39
- }
40
- }
41
- };
42
- function defineMockData(key, initialData) {
43
- if (!mockDataCache.has(key))
44
- mockDataCache.set(key, new CacheImpl(initialData));
45
- const cache = mockDataCache.get(key);
46
- cache.hotUpdate(initialData);
47
- if (responseCache.has(cache))
48
- return responseCache.get(cache);
49
- const res = [
50
- () => cache.value,
51
- (val) => {
52
- if (_utils.isFunction.call(void 0, val))
53
- val = _nullishCoalesce(val(cache.value), () => ( cache.value));
54
- cache.value = val;
55
- }
56
- ];
57
- Object.defineProperty(res, "value", {
58
- get() {
59
- return cache.value;
60
- },
61
- set(val) {
62
- cache.value = val;
63
- }
64
- });
65
- responseCache.set(cache, res);
66
- return res;
67
- }
68
-
69
-
70
-
71
-
72
-
73
- exports.defineMock = defineMock; exports.createDefineMock = createDefineMock; exports.defineMockData = defineMockData;