vite-plugin-mock-dev-server 1.5.1 → 1.6.0

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.
package/README.md CHANGED
@@ -152,6 +152,14 @@ export default defineConfig({
152
152
  > Different from using `viteConfig.server.proxy` by default for http mock, `websocket mock` does not use the ws-related configuration in `viteConfig.server.proxy`. Also, rules configured in `wsPrefix` cannot be configured simultaneously in `viteConfig.server.proxy`, as it will cause conflicts when starting the vite server because multiple instances of WebSocketServer cannot be implemented for the same request.
153
153
  > This conflict is neither a problem with Vite nor with the plugin; it belongs to a reasonable error type. When switching between WebSocket Mock and WebSocket Proxy, please pay attention to avoid duplicate configurations that may cause conflicts.
154
154
 
155
+ - `option.cwd`
156
+
157
+ **Type:** `string`
158
+
159
+ Configure the matching context for `include` and `exclude`.
160
+
161
+ **Default:** `process.cwd()`
162
+
155
163
  - `option.include`
156
164
 
157
165
  **Type:** `string | string[]`
@@ -939,7 +947,7 @@ You can access related `mock` interfaces through `localhost:8080/`.
939
947
  ## Contributors
940
948
 
941
949
  <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
942
- [![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors)
950
+ [![All Contributors](https://img.shields.io/badge/all_contributors-5-orange.svg?style=flat-square)](#contributors)
943
951
  <!-- ALL-CONTRIBUTORS-BADGE:END -->
944
952
 
945
953
  <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
@@ -952,6 +960,7 @@ You can access related `mock` interfaces through `localhost:8080/`.
952
960
  <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>
953
961
  <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>
954
962
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/pfdgithub"><img src="https://avatars.githubusercontent.com/u/3262762?v=4?s=100" width="100px;" alt="pfdgithub"/><br /><sub><b>pfdgithub</b></sub></a><br /><a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=pfdgithub" title="Code">💻</a> <a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues?q=author%3Apfdgithub" title="Bug reports">🐛</a></td>
963
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/chuyuandu"><img src="https://avatars.githubusercontent.com/u/6959138?v=4?s=100" width="100px;" alt="chuyuan du"/><br /><sub><b>chuyuan du</b></sub></a><br /><a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=chuyuandu" title="Code">💻</a></td>
955
964
  </tr>
956
965
  </tbody>
957
966
  </table>
package/README.zh-CN.md CHANGED
@@ -151,6 +151,14 @@ export default defineConfig({
151
151
  > 与 http mock 默认使用 `viteConfig.server.proxy` 不同的是,`websocket mock` 不会使用 `viteConfig.server.proxy` 中的 ws 相关的配置,且配置在 `wsPrefix` 中的规则,不能同时配置在 `viteConfig.server.proxy`中,因为会导致在 vite 在启动服务时产生冲突,因为不能对同一个请求实现多个的 `WebSocketServer`实例。
152
152
  > 该冲突既不是 `vite` 的问题,也不是插件的问题,这属于合理的错误类型。在进行 `WebSocket Mock`和 `WebSocket Proxy` 切换时,请注意配置不要出现重复导致冲突。
153
153
 
154
+ - `option.cwd`
155
+
156
+ **类型:** `string`
157
+
158
+ 配置 `include` 和 `exclude` 的匹配上下文
159
+
160
+ **默认值:** `process.cwd()`
161
+
154
162
  - `option.include`
155
163
 
156
164
  **类型:** `string | string[]`
package/dist/index.cjs CHANGED
@@ -44,11 +44,12 @@ __export(src_exports, {
44
44
  });
45
45
  module.exports = __toCommonJS(src_exports);
46
46
 
47
- // node_modules/.pnpm/tsup@8.1.0_postcss@8.4.38_typescript@5.5.2/node_modules/tsup/assets/cjs_shims.js
48
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
47
+ // node_modules/.pnpm/tsup@8.2.3_jiti@1.21.0_postcss@8.4.40_typescript@5.5.4/node_modules/tsup/assets/cjs_shims.js
48
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
49
49
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
50
50
 
51
51
  // src/plugin.ts
52
+ var import_node_process4 = __toESM(require("process"), 1);
52
53
  var import_utils16 = require("@pengzhanbo/utils");
53
54
 
54
55
  // src/build.ts
@@ -232,7 +233,12 @@ async function transformWithEsbuild(entryPoint, options) {
232
233
  }
233
234
  var _dirname = getDirname(importMetaUrl);
234
235
  var _require = (0, import_node_module.createRequire)(_dirname);
235
- async function loadFromCode(filepath, code, isESM, cwd) {
236
+ async function loadFromCode({
237
+ filepath,
238
+ code,
239
+ isESM,
240
+ cwd
241
+ }) {
236
242
  if (isESM) {
237
243
  const fileBase = `${filepath}.timestamp-${Date.now()}`;
238
244
  const fileNameTmp = `${fileBase}.mjs`;
@@ -285,11 +291,13 @@ function viteDefine(config) {
285
291
  if (typeof val === "string") {
286
292
  if (canJsonParse(val)) {
287
293
  userDefine[key] = val;
288
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
294
+ if (isMetaEnv)
295
+ userDefineEnv[key.slice(16)] = val;
289
296
  }
290
297
  } else {
291
298
  userDefine[key] = handleDefineValue(val);
292
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
299
+ if (isMetaEnv)
300
+ userDefineEnv[key.slice(16)] = val;
293
301
  }
294
302
  }
295
303
  const importMetaKeys = {};
@@ -346,11 +354,12 @@ function canJsonParse(value) {
346
354
 
347
355
  // src/build.ts
348
356
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
349
- var packageVersion = true ? "1.5.1" : "latest";
357
+ var packageVersion = true ? "1.6.0" : "latest";
350
358
  async function generateMockServer(ctx, config, options) {
351
359
  const include = (0, import_utils2.toArray)(options.include);
352
360
  const exclude = (0, import_utils2.toArray)(options.exclude);
353
361
  const define = viteDefine(config);
362
+ const cwd = options.cwd || import_node_process2.default.cwd();
354
363
  const { httpProxies } = ensureProxies(config.server.proxy || {});
355
364
  httpProxies.push(...(0, import_utils2.toArray)(options.prefix));
356
365
  const wsProxies = (0, import_utils2.toArray)(options.wsPrefix);
@@ -362,8 +371,8 @@ async function generateMockServer(ctx, config, options) {
362
371
  } catch {
363
372
  }
364
373
  const outputDir = options.build.dist;
365
- const content = await generateMockEntryCode(import_node_process2.default.cwd(), include, exclude);
366
- const mockEntry = import_node_path3.default.join(config.root, `mock-data-${Date.now()}.js`);
374
+ const content = await generateMockEntryCode(cwd, include, exclude);
375
+ const mockEntry = import_node_path3.default.join(cwd, `mock-data-${Date.now()}.js`);
367
376
  await import_promises.default.writeFile(mockEntry, content, "utf-8");
368
377
  const { code, deps } = await transformWithEsbuild(mockEntry, {
369
378
  define,
@@ -977,10 +986,12 @@ async function provideHeaders(req, res, mock, logger) {
977
986
  const { headers, type = "json" } = mock;
978
987
  const filepath = mock.__filepath__;
979
988
  const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
980
- contentType2 && res.setHeader("Content-Type", contentType2);
989
+ if (contentType2)
990
+ res.setHeader("Content-Type", contentType2);
981
991
  res.setHeader("Cache-Control", "no-cache,max-age=0");
982
992
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
983
- filepath && res.setHeader("X-File-Path", filepath);
993
+ if (filepath)
994
+ res.setHeader("X-File-Path", filepath);
984
995
  if (!headers)
985
996
  return;
986
997
  try {
@@ -1123,7 +1134,7 @@ function transformMockData(mockList) {
1123
1134
  const list = [];
1124
1135
  for (const [, handle] of mockList.entries()) {
1125
1136
  if (handle)
1126
- (0, import_utils9.isArray)(handle) ? list.push(...handle) : list.push(handle);
1137
+ list.push(...(0, import_utils9.toArray)(handle));
1127
1138
  }
1128
1139
  const mocks = {};
1129
1140
  list.filter((mock) => (0, import_utils9.isObject)(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
@@ -1183,7 +1194,7 @@ var MockLoader = class extends import_node_events.default {
1183
1194
  try {
1184
1195
  const pkg = lookupFile(this.cwd, ["package.json"]);
1185
1196
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
1186
- } catch (e) {
1197
+ } catch {
1187
1198
  }
1188
1199
  }
1189
1200
  moduleCache = /* @__PURE__ */ new Map();
@@ -1211,7 +1222,8 @@ var MockLoader = class extends import_node_events.default {
1211
1222
  if (!includeFilter(filepath))
1212
1223
  return;
1213
1224
  await this.loadMock(filepath);
1214
- timer && clearImmediate(timer);
1225
+ if (timer)
1226
+ clearImmediate(timer);
1215
1227
  timer = setImmediate(() => {
1216
1228
  this.updateMockList();
1217
1229
  this.emit("mock:update-end", filepath);
@@ -1233,7 +1245,8 @@ var MockLoader = class extends import_node_events.default {
1233
1245
  ignoreInitial: true,
1234
1246
  cwd: this.cwd
1235
1247
  });
1236
- otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1248
+ if (otherGlob.length > 0)
1249
+ otherGlob.forEach((glob) => watcher.add(glob));
1237
1250
  watcher.on("add", async (filepath) => {
1238
1251
  filepath = normalizePath(filepath);
1239
1252
  this.emit("mock:update", filepath);
@@ -1263,7 +1276,7 @@ var MockLoader = class extends import_node_events.default {
1263
1276
  this.depsWatcher.on("change", (filepath) => {
1264
1277
  filepath = normalizePath(filepath);
1265
1278
  const mockFiles = this.moduleDeps.get(filepath);
1266
- mockFiles && mockFiles.forEach((file) => {
1279
+ mockFiles == null ? void 0 : mockFiles.forEach((file) => {
1267
1280
  this.emit("mock:update", file);
1268
1281
  });
1269
1282
  });
@@ -1276,7 +1289,8 @@ var MockLoader = class extends import_node_events.default {
1276
1289
  for (const [dep] of this.moduleDeps.entries())
1277
1290
  deps.push(dep);
1278
1291
  const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
1279
- exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
1292
+ if (exactDeps.length > 0)
1293
+ this.depsWatcher.add(exactDeps);
1280
1294
  });
1281
1295
  }
1282
1296
  close() {
@@ -1315,12 +1329,12 @@ var MockLoader = class extends import_node_events.default {
1315
1329
  { isESM, define, alias }
1316
1330
  );
1317
1331
  try {
1318
- const raw = await loadFromCode(
1332
+ const raw = await loadFromCode({
1319
1333
  filepath,
1320
1334
  code,
1321
1335
  isESM,
1322
- this.cwd
1323
- ) || {};
1336
+ cwd: this.cwd
1337
+ }) || {};
1324
1338
  let mockConfig;
1325
1339
  if ((0, import_utils11.hasOwn)(raw, "default")) {
1326
1340
  mockConfig = raw.default;
@@ -1362,17 +1376,20 @@ function mockWebSocket({
1362
1376
  const wssContextMap = /* @__PURE__ */ new WeakMap();
1363
1377
  const getWssMap = (mockUrl) => {
1364
1378
  let wssMap = poolMap.get(mockUrl);
1365
- !wssMap && poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1379
+ if (!wssMap)
1380
+ poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1366
1381
  return wssMap;
1367
1382
  };
1368
1383
  const getWss = (wssMap, pathname) => {
1369
1384
  let wss = wssMap.get(pathname);
1370
- !wss && wssMap.set(pathname, wss = new import_ws.WebSocketServer({ noServer: true }));
1385
+ if (!wss)
1386
+ wssMap.set(pathname, wss = new import_ws.WebSocketServer({ noServer: true }));
1371
1387
  return wss;
1372
1388
  };
1373
1389
  const addHmr = (filepath, mockUrl) => {
1374
1390
  let urlList = hmrMap.get(filepath);
1375
- !urlList && hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1391
+ if (!urlList)
1392
+ hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1376
1393
  urlList.add(mockUrl);
1377
1394
  };
1378
1395
  const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
@@ -1509,6 +1526,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1509
1526
  (0, import_utils14.isBoolean)(options.log) ? options.log ? "info" : "error" : options.log
1510
1527
  );
1511
1528
  const loader = new MockLoader({
1529
+ cwd: options.cwd,
1512
1530
  include: (0, import_utils14.toArray)(options.include),
1513
1531
  exclude: (0, import_utils14.toArray)(options.exclude),
1514
1532
  define: viteDefine(config),
@@ -1593,6 +1611,7 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1593
1611
  function mockDevServerPlugin({
1594
1612
  prefix = [],
1595
1613
  wsPrefix = [],
1614
+ cwd = import_node_process4.default.cwd(),
1596
1615
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
1597
1616
  exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
1598
1617
  reload = false,
@@ -1607,6 +1626,7 @@ function mockDevServerPlugin({
1607
1626
  const pluginOptions = {
1608
1627
  prefix,
1609
1628
  wsPrefix,
1629
+ cwd,
1610
1630
  include,
1611
1631
  exclude,
1612
1632
  reload,
package/dist/index.d.cts CHANGED
@@ -41,6 +41,14 @@ interface MockServerPluginOptions {
41
41
  * @example ['/socket.io']
42
42
  */
43
43
  wsPrefix?: string | string[];
44
+ /**
45
+ * Configure the matching context for `include` and `exclude`.
46
+ *
47
+ * 配置 `include` 和 `exclude` 的匹配上下文
48
+ *
49
+ * @default process.cwd()
50
+ */
51
+ cwd?: string;
44
52
  /**
45
53
  * glob string matching mock includes files
46
54
  *
@@ -564,7 +572,7 @@ type LogType = 'info' | 'warn' | 'error' | 'debug';
564
572
  type LogLevel = LogType | 'silent';
565
573
 
566
574
  /** @deprecated The CJS build of vite-plugin-mock-dev-server's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details. */
567
- declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
575
+ declare function mockDevServerPlugin({ prefix, wsPrefix, cwd, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
568
576
 
569
577
  /**
570
578
  * mock config Type helper
package/dist/index.d.ts CHANGED
@@ -41,6 +41,14 @@ interface MockServerPluginOptions {
41
41
  * @example ['/socket.io']
42
42
  */
43
43
  wsPrefix?: string | string[];
44
+ /**
45
+ * Configure the matching context for `include` and `exclude`.
46
+ *
47
+ * 配置 `include` 和 `exclude` 的匹配上下文
48
+ *
49
+ * @default process.cwd()
50
+ */
51
+ cwd?: string;
44
52
  /**
45
53
  * glob string matching mock includes files
46
54
  *
@@ -563,7 +571,7 @@ type FormidableFile = formidable.File | formidable.File[];
563
571
  type LogType = 'info' | 'warn' | 'error' | 'debug';
564
572
  type LogLevel = LogType | 'silent';
565
573
 
566
- declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
574
+ declare function mockDevServerPlugin({ prefix, wsPrefix, cwd, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
567
575
 
568
576
  /**
569
577
  * mock config Type helper
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // src/plugin.ts
2
- import { toArray as toArray4 } from "@pengzhanbo/utils";
2
+ import process4 from "node:process";
3
+ import { toArray as toArray5 } from "@pengzhanbo/utils";
3
4
 
4
5
  // src/build.ts
5
6
  import fs3 from "node:fs";
@@ -182,7 +183,12 @@ async function transformWithEsbuild(entryPoint, options) {
182
183
  }
183
184
  var _dirname = getDirname(import.meta.url);
184
185
  var _require = createRequire(_dirname);
185
- async function loadFromCode(filepath, code, isESM, cwd) {
186
+ async function loadFromCode({
187
+ filepath,
188
+ code,
189
+ isESM,
190
+ cwd
191
+ }) {
186
192
  if (isESM) {
187
193
  const fileBase = `${filepath}.timestamp-${Date.now()}`;
188
194
  const fileNameTmp = `${fileBase}.mjs`;
@@ -235,11 +241,13 @@ function viteDefine(config) {
235
241
  if (typeof val === "string") {
236
242
  if (canJsonParse(val)) {
237
243
  userDefine[key] = val;
238
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
244
+ if (isMetaEnv)
245
+ userDefineEnv[key.slice(16)] = val;
239
246
  }
240
247
  } else {
241
248
  userDefine[key] = handleDefineValue(val);
242
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
249
+ if (isMetaEnv)
250
+ userDefineEnv[key.slice(16)] = val;
243
251
  }
244
252
  }
245
253
  const importMetaKeys = {};
@@ -296,11 +304,12 @@ function canJsonParse(value) {
296
304
 
297
305
  // src/build.ts
298
306
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
299
- var packageVersion = true ? "1.5.1" : "latest";
307
+ var packageVersion = true ? "1.6.0" : "latest";
300
308
  async function generateMockServer(ctx, config, options) {
301
309
  const include = toArray(options.include);
302
310
  const exclude = toArray(options.exclude);
303
311
  const define = viteDefine(config);
312
+ const cwd = options.cwd || process2.cwd();
304
313
  const { httpProxies } = ensureProxies(config.server.proxy || {});
305
314
  httpProxies.push(...toArray(options.prefix));
306
315
  const wsProxies = toArray(options.wsPrefix);
@@ -312,8 +321,8 @@ async function generateMockServer(ctx, config, options) {
312
321
  } catch {
313
322
  }
314
323
  const outputDir = options.build.dist;
315
- const content = await generateMockEntryCode(process2.cwd(), include, exclude);
316
- const mockEntry = path3.join(config.root, `mock-data-${Date.now()}.js`);
324
+ const content = await generateMockEntryCode(cwd, include, exclude);
325
+ const mockEntry = path3.join(cwd, `mock-data-${Date.now()}.js`);
317
326
  await fsp2.writeFile(mockEntry, content, "utf-8");
318
327
  const { code, deps } = await transformWithEsbuild(mockEntry, {
319
328
  define,
@@ -479,7 +488,7 @@ export default transformMockData(mockList);`;
479
488
  }
480
489
 
481
490
  // src/mockMiddleware.ts
482
- import { isBoolean as isBoolean2, toArray as toArray3, uniq as uniq2 } from "@pengzhanbo/utils";
491
+ import { isBoolean as isBoolean2, toArray as toArray4, uniq as uniq2 } from "@pengzhanbo/utils";
483
492
  import cors from "cors";
484
493
  import { pathToRegexp as pathToRegexp4 } from "path-to-regexp";
485
494
  import c2 from "picocolors";
@@ -940,10 +949,12 @@ async function provideHeaders(req, res, mock, logger) {
940
949
  const { headers, type = "json" } = mock;
941
950
  const filepath = mock.__filepath__;
942
951
  const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
943
- contentType2 && res.setHeader("Content-Type", contentType2);
952
+ if (contentType2)
953
+ res.setHeader("Content-Type", contentType2);
944
954
  res.setHeader("Cache-Control", "no-cache,max-age=0");
945
955
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
946
- filepath && res.setHeader("X-File-Path", filepath);
956
+ if (filepath)
957
+ res.setHeader("X-File-Path", filepath);
947
958
  if (!headers)
948
959
  return;
949
960
  try {
@@ -1075,24 +1086,24 @@ function createLogger(prefix, defaultLevel = "info") {
1075
1086
  // src/MockLoader.ts
1076
1087
  import EventEmitter from "node:events";
1077
1088
  import process3 from "node:process";
1078
- import { hasOwn, isArray as isArray5, promiseParallel, toArray as toArray2 } from "@pengzhanbo/utils";
1089
+ import { hasOwn, isArray as isArray4, promiseParallel, toArray as toArray3 } from "@pengzhanbo/utils";
1079
1090
  import chokidar from "chokidar";
1080
1091
  import fastGlob from "fast-glob";
1081
1092
  import { createFilter as createFilter2 } from "@rollup/pluginutils";
1082
1093
 
1083
1094
  // src/transform.ts
1084
1095
  import {
1085
- isArray as isArray4,
1086
1096
  isEmptyObject as isEmptyObject3,
1087
1097
  isFunction as isFunction2,
1088
1098
  isObject as isObject2,
1089
- sortBy as sortBy2
1099
+ sortBy as sortBy2,
1100
+ toArray as toArray2
1090
1101
  } from "@pengzhanbo/utils";
1091
1102
  function transformMockData(mockList) {
1092
1103
  const list = [];
1093
1104
  for (const [, handle] of mockList.entries()) {
1094
1105
  if (handle)
1095
- isArray4(handle) ? list.push(...handle) : list.push(handle);
1106
+ list.push(...toArray2(handle));
1096
1107
  }
1097
1108
  const mocks = {};
1098
1109
  list.filter((mock) => isObject2(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
@@ -1152,7 +1163,7 @@ var MockLoader = class extends EventEmitter {
1152
1163
  try {
1153
1164
  const pkg = lookupFile(this.cwd, ["package.json"]);
1154
1165
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
1155
- } catch (e) {
1166
+ } catch {
1156
1167
  }
1157
1168
  }
1158
1169
  moduleCache = /* @__PURE__ */ new Map();
@@ -1180,7 +1191,8 @@ var MockLoader = class extends EventEmitter {
1180
1191
  if (!includeFilter(filepath))
1181
1192
  return;
1182
1193
  await this.loadMock(filepath);
1183
- timer && clearImmediate(timer);
1194
+ if (timer)
1195
+ clearImmediate(timer);
1184
1196
  timer = setImmediate(() => {
1185
1197
  this.updateMockList();
1186
1198
  this.emit("mock:update-end", filepath);
@@ -1202,7 +1214,8 @@ var MockLoader = class extends EventEmitter {
1202
1214
  ignoreInitial: true,
1203
1215
  cwd: this.cwd
1204
1216
  });
1205
- otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1217
+ if (otherGlob.length > 0)
1218
+ otherGlob.forEach((glob) => watcher.add(glob));
1206
1219
  watcher.on("add", async (filepath) => {
1207
1220
  filepath = normalizePath(filepath);
1208
1221
  this.emit("mock:update", filepath);
@@ -1232,7 +1245,7 @@ var MockLoader = class extends EventEmitter {
1232
1245
  this.depsWatcher.on("change", (filepath) => {
1233
1246
  filepath = normalizePath(filepath);
1234
1247
  const mockFiles = this.moduleDeps.get(filepath);
1235
- mockFiles && mockFiles.forEach((file) => {
1248
+ mockFiles == null ? void 0 : mockFiles.forEach((file) => {
1236
1249
  this.emit("mock:update", file);
1237
1250
  });
1238
1251
  });
@@ -1245,7 +1258,8 @@ var MockLoader = class extends EventEmitter {
1245
1258
  for (const [dep] of this.moduleDeps.entries())
1246
1259
  deps.push(dep);
1247
1260
  const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
1248
- exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
1261
+ if (exactDeps.length > 0)
1262
+ this.depsWatcher.add(exactDeps);
1249
1263
  });
1250
1264
  }
1251
1265
  close() {
@@ -1284,22 +1298,22 @@ var MockLoader = class extends EventEmitter {
1284
1298
  { isESM, define, alias }
1285
1299
  );
1286
1300
  try {
1287
- const raw = await loadFromCode(
1301
+ const raw = await loadFromCode({
1288
1302
  filepath,
1289
1303
  code,
1290
1304
  isESM,
1291
- this.cwd
1292
- ) || {};
1305
+ cwd: this.cwd
1306
+ }) || {};
1293
1307
  let mockConfig;
1294
1308
  if (hasOwn(raw, "default")) {
1295
1309
  mockConfig = raw.default;
1296
1310
  } else {
1297
1311
  mockConfig = [];
1298
1312
  Object.keys(raw).forEach(
1299
- (key) => mockConfig.push(...toArray2(raw[key]))
1313
+ (key) => mockConfig.push(...toArray3(raw[key]))
1300
1314
  );
1301
1315
  }
1302
- if (isArray5(mockConfig)) {
1316
+ if (isArray4(mockConfig)) {
1303
1317
  mockConfig.forEach((mock) => mock.__filepath__ = filepath);
1304
1318
  } else {
1305
1319
  ;
@@ -1331,17 +1345,20 @@ function mockWebSocket({
1331
1345
  const wssContextMap = /* @__PURE__ */ new WeakMap();
1332
1346
  const getWssMap = (mockUrl) => {
1333
1347
  let wssMap = poolMap.get(mockUrl);
1334
- !wssMap && poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1348
+ if (!wssMap)
1349
+ poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1335
1350
  return wssMap;
1336
1351
  };
1337
1352
  const getWss = (wssMap, pathname) => {
1338
1353
  let wss = wssMap.get(pathname);
1339
- !wss && wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
1354
+ if (!wss)
1355
+ wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
1340
1356
  return wss;
1341
1357
  };
1342
1358
  const addHmr = (filepath, mockUrl) => {
1343
1359
  let urlList = hmrMap.get(filepath);
1344
- !urlList && hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1360
+ if (!urlList)
1361
+ hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1345
1362
  urlList.add(mockUrl);
1346
1363
  };
1347
1364
  const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
@@ -1478,8 +1495,9 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1478
1495
  isBoolean2(options.log) ? options.log ? "info" : "error" : options.log
1479
1496
  );
1480
1497
  const loader = new MockLoader({
1481
- include: toArray3(options.include),
1482
- exclude: toArray3(options.exclude),
1498
+ cwd: options.cwd,
1499
+ include: toArray4(options.include),
1500
+ exclude: toArray4(options.exclude),
1483
1501
  define: viteDefine(config),
1484
1502
  alias: config.resolve.alias
1485
1503
  });
@@ -1490,14 +1508,14 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1490
1508
  });
1491
1509
  httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
1492
1510
  const { httpProxies } = ensureProxies(config.server.proxy || {});
1493
- const prefix = toArray3(options.prefix);
1511
+ const prefix = toArray4(options.prefix);
1494
1512
  const proxies = uniq2([...prefix, ...httpProxies]);
1495
- if (!proxies.length && !toArray3(options.wsPrefix).length)
1513
+ if (!proxies.length && !toArray4(options.wsPrefix).length)
1496
1514
  logger.warn(`No proxy was configured, mock server will not work. See ${c2.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
1497
1515
  mockWebSocket({
1498
1516
  loader,
1499
1517
  httpServer,
1500
- proxies: toArray3(options.wsPrefix),
1518
+ proxies: toArray4(options.wsPrefix),
1501
1519
  cookiesOptions: options.cookiesOptions,
1502
1520
  logger
1503
1521
  });
@@ -1562,6 +1580,7 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1562
1580
  function mockDevServerPlugin({
1563
1581
  prefix = [],
1564
1582
  wsPrefix = [],
1583
+ cwd = process4.cwd(),
1565
1584
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
1566
1585
  exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
1567
1586
  reload = false,
@@ -1576,6 +1595,7 @@ function mockDevServerPlugin({
1576
1595
  const pluginOptions = {
1577
1596
  prefix,
1578
1597
  wsPrefix,
1598
+ cwd,
1579
1599
  include,
1580
1600
  exclude,
1581
1601
  reload,
@@ -1629,7 +1649,7 @@ function serverPlugin(pluginOptions) {
1629
1649
  apply: "serve",
1630
1650
  config(config) {
1631
1651
  var _a;
1632
- const wsPrefix = toArray4(pluginOptions.wsPrefix);
1652
+ const wsPrefix = toArray5(pluginOptions.wsPrefix);
1633
1653
  if (wsPrefix.length && ((_a = config.server) == null ? void 0 : _a.proxy)) {
1634
1654
  const proxy = {};
1635
1655
  Object.keys(config.server.proxy).forEach((key) => {
@@ -1665,13 +1685,13 @@ function serverPlugin(pluginOptions) {
1665
1685
  }
1666
1686
 
1667
1687
  // src/defineMock.ts
1668
- import { isArray as isArray6 } from "@pengzhanbo/utils";
1688
+ import { isArray as isArray5 } from "@pengzhanbo/utils";
1669
1689
  function defineMock(config) {
1670
1690
  return config;
1671
1691
  }
1672
1692
  function createDefineMock(transformer) {
1673
1693
  const define = (config) => {
1674
- if (isArray6(config))
1694
+ if (isArray5(config))
1675
1695
  config = config.map((item) => transformer(item) || item);
1676
1696
  else
1677
1697
  config = transformer(config) || config;
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.5.1",
4
+ "version": "1.6.0",
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",
@@ -49,19 +49,19 @@
49
49
  "cookies": "^0.9.1",
50
50
  "cors": "^2.8.5",
51
51
  "debug": "^4.3.5",
52
- "esbuild": "^0.21.5",
52
+ "esbuild": "^0.23.0",
53
53
  "fast-glob": "^3.3.2",
54
54
  "formidable": "2.1.2",
55
55
  "http-status": "^1.7.4",
56
- "is-core-module": "^2.14.0",
56
+ "is-core-module": "^2.15.0",
57
57
  "json5": "^2.2.3",
58
58
  "mime-types": "^2.1.35",
59
59
  "path-to-regexp": "6.2.2",
60
60
  "picocolors": "^1.0.1",
61
- "ws": "^8.17.1"
61
+ "ws": "^8.18.0"
62
62
  },
63
63
  "devDependencies": {
64
- "@pengzhanbo/eslint-config": "^1.11.2",
64
+ "@pengzhanbo/eslint-config": "^1.12.0",
65
65
  "@types/co-body": "^6.1.3",
66
66
  "@types/cookies": "^0.9.0",
67
67
  "@types/cors": "^2.8.17",
@@ -69,17 +69,17 @@
69
69
  "@types/formidable": "2.0.6",
70
70
  "@types/is-core-module": "^2.2.2",
71
71
  "@types/mime-types": "^2.1.4",
72
- "@types/node": "^20.14.9",
73
- "@types/ws": "^8.5.10",
72
+ "@types/node": "^20.14.12",
73
+ "@types/ws": "^8.5.11",
74
74
  "bumpp": "^9.4.1",
75
75
  "conventional-changelog-cli": "^5.0.0",
76
- "eslint": "^9.6.0",
76
+ "eslint": "^9.7.0",
77
77
  "mockjs": "^1.1.0",
78
- "tsup": "^8.1.0",
79
- "typescript": "^5.5.2",
80
- "vite": "^5.3.2",
81
- "vitepress": "^1.2.3",
82
- "vitest": "^1.6.0"
78
+ "tsup": "^8.2.3",
79
+ "typescript": "^5.5.4",
80
+ "vite": "^5.3.4",
81
+ "vitepress": "^1.3.1",
82
+ "vitest": "^2.0.4"
83
83
  },
84
84
  "scripts": {
85
85
  "build": "tsup && node ./deprecate.mjs",