vite-plugin-mock-dev-server 1.5.1 → 1.6.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.
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,18 +44,19 @@ __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_process5 = __toESM(require("process"), 1);
52
53
  var import_utils16 = require("@pengzhanbo/utils");
53
54
 
54
55
  // src/build.ts
55
56
  var import_node_fs3 = __toESM(require("fs"), 1);
56
57
  var import_promises = __toESM(require("fs/promises"), 1);
57
58
  var import_node_path3 = __toESM(require("path"), 1);
58
- var import_node_process2 = __toESM(require("process"), 1);
59
+ var import_node_process3 = __toESM(require("process"), 1);
59
60
  var import_utils2 = require("@pengzhanbo/utils");
60
61
  var import_fast_glob = __toESM(require("fast-glob"), 1);
61
62
  var import_is_core_module = __toESM(require("is-core-module"), 1);
@@ -67,6 +68,7 @@ var import_node_fs2 = __toESM(require("fs"), 1);
67
68
  var import_node_module = require("module");
68
69
  var import_node_path2 = __toESM(require("path"), 1);
69
70
  var import_node_url2 = require("url");
71
+ var import_node_process = __toESM(require("process"), 1);
70
72
  var import_esbuild = require("esbuild");
71
73
  var import_json5 = __toESM(require("json5"), 1);
72
74
 
@@ -207,7 +209,7 @@ function aliasMatches(pattern, importee) {
207
209
  }
208
210
  async function transformWithEsbuild(entryPoint, options) {
209
211
  var _a;
210
- const { isESM = true, define, alias } = options;
212
+ const { isESM = true, define, alias, cwd = import_node_process.default.cwd() } = options;
211
213
  try {
212
214
  const result = await (0, import_esbuild.build)({
213
215
  entryPoints: [entryPoint],
@@ -219,7 +221,8 @@ async function transformWithEsbuild(entryPoint, options) {
219
221
  metafile: true,
220
222
  format: isESM ? "esm" : "cjs",
221
223
  define,
222
- plugins: [aliasPlugin(alias), externalizeDeps, jsonLoader, json5Loader]
224
+ plugins: [aliasPlugin(alias), externalizeDeps, jsonLoader, json5Loader],
225
+ absWorkingDir: cwd
223
226
  });
224
227
  return {
225
228
  code: result.outputFiles[0].text,
@@ -232,7 +235,13 @@ async function transformWithEsbuild(entryPoint, options) {
232
235
  }
233
236
  var _dirname = getDirname(importMetaUrl);
234
237
  var _require = (0, import_node_module.createRequire)(_dirname);
235
- async function loadFromCode(filepath, code, isESM, cwd) {
238
+ async function loadFromCode({
239
+ filepath,
240
+ code,
241
+ isESM,
242
+ cwd
243
+ }) {
244
+ filepath = import_node_path2.default.resolve(cwd, filepath);
236
245
  if (isESM) {
237
246
  const fileBase = `${filepath}.timestamp-${Date.now()}`;
238
247
  const fileNameTmp = `${fileBase}.mjs`;
@@ -247,7 +256,6 @@ async function loadFromCode(filepath, code, isESM, cwd) {
247
256
  }
248
257
  }
249
258
  } else {
250
- filepath = import_node_path2.default.resolve(cwd, filepath);
251
259
  const extension = import_node_path2.default.extname(filepath);
252
260
  const realFileName = import_node_fs2.default.realpathSync(filepath);
253
261
  const loaderExt = extension in _require.extensions ? extension : ".js";
@@ -268,10 +276,10 @@ async function loadFromCode(filepath, code, isESM, cwd) {
268
276
  }
269
277
 
270
278
  // src/define.ts
271
- var import_node_process = __toESM(require("process"), 1);
279
+ var import_node_process2 = __toESM(require("process"), 1);
272
280
  function viteDefine(config) {
273
281
  const processNodeEnv = {};
274
- const nodeEnv = import_node_process.default.env.NODE_ENV || config.mode;
282
+ const nodeEnv = import_node_process2.default.env.NODE_ENV || config.mode;
275
283
  Object.assign(processNodeEnv, {
276
284
  "process.env.NODE_ENV": JSON.stringify(nodeEnv),
277
285
  "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
@@ -285,11 +293,13 @@ function viteDefine(config) {
285
293
  if (typeof val === "string") {
286
294
  if (canJsonParse(val)) {
287
295
  userDefine[key] = val;
288
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
296
+ if (isMetaEnv)
297
+ userDefineEnv[key.slice(16)] = val;
289
298
  }
290
299
  } else {
291
300
  userDefine[key] = handleDefineValue(val);
292
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
301
+ if (isMetaEnv)
302
+ userDefineEnv[key.slice(16)] = val;
293
303
  }
294
304
  }
295
305
  const importMetaKeys = {};
@@ -346,11 +356,12 @@ function canJsonParse(value) {
346
356
 
347
357
  // src/build.ts
348
358
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
349
- var packageVersion = true ? "1.5.1" : "latest";
359
+ var packageVersion = true ? "1.6.1" : "latest";
350
360
  async function generateMockServer(ctx, config, options) {
351
361
  const include = (0, import_utils2.toArray)(options.include);
352
362
  const exclude = (0, import_utils2.toArray)(options.exclude);
353
363
  const define = viteDefine(config);
364
+ const cwd = options.cwd || import_node_process3.default.cwd();
354
365
  const { httpProxies } = ensureProxies(config.server.proxy || {});
355
366
  httpProxies.push(...(0, import_utils2.toArray)(options.prefix));
356
367
  const wsProxies = (0, import_utils2.toArray)(options.wsPrefix);
@@ -362,8 +373,8 @@ async function generateMockServer(ctx, config, options) {
362
373
  } catch {
363
374
  }
364
375
  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`);
376
+ const content = await generateMockEntryCode(cwd, include, exclude);
377
+ const mockEntry = import_node_path3.default.join(cwd, `mock-data-${Date.now()}.js`);
367
378
  await import_promises.default.writeFile(mockEntry, content, "utf-8");
368
379
  const { code, deps } = await transformWithEsbuild(mockEntry, {
369
380
  define,
@@ -977,10 +988,12 @@ async function provideHeaders(req, res, mock, logger) {
977
988
  const { headers, type = "json" } = mock;
978
989
  const filepath = mock.__filepath__;
979
990
  const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
980
- contentType2 && res.setHeader("Content-Type", contentType2);
991
+ if (contentType2)
992
+ res.setHeader("Content-Type", contentType2);
981
993
  res.setHeader("Cache-Control", "no-cache,max-age=0");
982
994
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
983
- filepath && res.setHeader("X-File-Path", filepath);
995
+ if (filepath)
996
+ res.setHeader("X-File-Path", filepath);
984
997
  if (!headers)
985
998
  return;
986
999
  try {
@@ -1111,7 +1124,7 @@ function createLogger(prefix, defaultLevel = "info") {
1111
1124
 
1112
1125
  // src/MockLoader.ts
1113
1126
  var import_node_events = __toESM(require("events"), 1);
1114
- var import_node_process3 = __toESM(require("process"), 1);
1127
+ var import_node_process4 = __toESM(require("process"), 1);
1115
1128
  var import_utils11 = require("@pengzhanbo/utils");
1116
1129
  var import_chokidar = __toESM(require("chokidar"), 1);
1117
1130
  var import_fast_glob2 = __toESM(require("fast-glob"), 1);
@@ -1123,7 +1136,7 @@ function transformMockData(mockList) {
1123
1136
  const list = [];
1124
1137
  for (const [, handle] of mockList.entries()) {
1125
1138
  if (handle)
1126
- (0, import_utils9.isArray)(handle) ? list.push(...handle) : list.push(handle);
1139
+ list.push(...(0, import_utils9.toArray)(handle));
1127
1140
  }
1128
1141
  const mocks = {};
1129
1142
  list.filter((mock) => (0, import_utils9.isObject)(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
@@ -1179,11 +1192,11 @@ var MockLoader = class extends import_node_events.default {
1179
1192
  constructor(options) {
1180
1193
  super();
1181
1194
  this.options = options;
1182
- this.cwd = options.cwd || import_node_process3.default.cwd();
1195
+ this.cwd = options.cwd || import_node_process4.default.cwd();
1183
1196
  try {
1184
1197
  const pkg = lookupFile(this.cwd, ["package.json"]);
1185
1198
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
1186
- } catch (e) {
1199
+ } catch {
1187
1200
  }
1188
1201
  }
1189
1202
  moduleCache = /* @__PURE__ */ new Map();
@@ -1211,7 +1224,8 @@ var MockLoader = class extends import_node_events.default {
1211
1224
  if (!includeFilter(filepath))
1212
1225
  return;
1213
1226
  await this.loadMock(filepath);
1214
- timer && clearImmediate(timer);
1227
+ if (timer)
1228
+ clearImmediate(timer);
1215
1229
  timer = setImmediate(() => {
1216
1230
  this.updateMockList();
1217
1231
  this.emit("mock:update-end", filepath);
@@ -1233,7 +1247,8 @@ var MockLoader = class extends import_node_events.default {
1233
1247
  ignoreInitial: true,
1234
1248
  cwd: this.cwd
1235
1249
  });
1236
- otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1250
+ if (otherGlob.length > 0)
1251
+ otherGlob.forEach((glob) => watcher.add(glob));
1237
1252
  watcher.on("add", async (filepath) => {
1238
1253
  filepath = normalizePath(filepath);
1239
1254
  this.emit("mock:update", filepath);
@@ -1263,7 +1278,7 @@ var MockLoader = class extends import_node_events.default {
1263
1278
  this.depsWatcher.on("change", (filepath) => {
1264
1279
  filepath = normalizePath(filepath);
1265
1280
  const mockFiles = this.moduleDeps.get(filepath);
1266
- mockFiles && mockFiles.forEach((file) => {
1281
+ mockFiles == null ? void 0 : mockFiles.forEach((file) => {
1267
1282
  this.emit("mock:update", file);
1268
1283
  });
1269
1284
  });
@@ -1276,7 +1291,8 @@ var MockLoader = class extends import_node_events.default {
1276
1291
  for (const [dep] of this.moduleDeps.entries())
1277
1292
  deps.push(dep);
1278
1293
  const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
1279
- exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
1294
+ if (exactDeps.length > 0)
1295
+ this.depsWatcher.add(exactDeps);
1280
1296
  });
1281
1297
  }
1282
1298
  close() {
@@ -1312,15 +1328,15 @@ var MockLoader = class extends import_node_events.default {
1312
1328
  const { define, alias } = this.options;
1313
1329
  const { code, deps } = await transformWithEsbuild(
1314
1330
  filepath,
1315
- { isESM, define, alias }
1331
+ { isESM, define, alias, cwd: this.cwd }
1316
1332
  );
1317
1333
  try {
1318
- const raw = await loadFromCode(
1334
+ const raw = await loadFromCode({
1319
1335
  filepath,
1320
1336
  code,
1321
1337
  isESM,
1322
- this.cwd
1323
- ) || {};
1338
+ cwd: this.cwd
1339
+ }) || {};
1324
1340
  let mockConfig;
1325
1341
  if ((0, import_utils11.hasOwn)(raw, "default")) {
1326
1342
  mockConfig = raw.default;
@@ -1362,17 +1378,20 @@ function mockWebSocket({
1362
1378
  const wssContextMap = /* @__PURE__ */ new WeakMap();
1363
1379
  const getWssMap = (mockUrl) => {
1364
1380
  let wssMap = poolMap.get(mockUrl);
1365
- !wssMap && poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1381
+ if (!wssMap)
1382
+ poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1366
1383
  return wssMap;
1367
1384
  };
1368
1385
  const getWss = (wssMap, pathname) => {
1369
1386
  let wss = wssMap.get(pathname);
1370
- !wss && wssMap.set(pathname, wss = new import_ws.WebSocketServer({ noServer: true }));
1387
+ if (!wss)
1388
+ wssMap.set(pathname, wss = new import_ws.WebSocketServer({ noServer: true }));
1371
1389
  return wss;
1372
1390
  };
1373
1391
  const addHmr = (filepath, mockUrl) => {
1374
1392
  let urlList = hmrMap.get(filepath);
1375
- !urlList && hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1393
+ if (!urlList)
1394
+ hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1376
1395
  urlList.add(mockUrl);
1377
1396
  };
1378
1397
  const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
@@ -1509,6 +1528,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1509
1528
  (0, import_utils14.isBoolean)(options.log) ? options.log ? "info" : "error" : options.log
1510
1529
  );
1511
1530
  const loader = new MockLoader({
1531
+ cwd: options.cwd,
1512
1532
  include: (0, import_utils14.toArray)(options.include),
1513
1533
  exclude: (0, import_utils14.toArray)(options.exclude),
1514
1534
  define: viteDefine(config),
@@ -1593,6 +1613,7 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1593
1613
  function mockDevServerPlugin({
1594
1614
  prefix = [],
1595
1615
  wsPrefix = [],
1616
+ cwd = import_node_process5.default.cwd(),
1596
1617
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
1597
1618
  exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
1598
1619
  reload = false,
@@ -1607,6 +1628,7 @@ function mockDevServerPlugin({
1607
1628
  const pluginOptions = {
1608
1629
  prefix,
1609
1630
  wsPrefix,
1631
+ cwd,
1610
1632
  include,
1611
1633
  exclude,
1612
1634
  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,11 +1,12 @@
1
1
  // src/plugin.ts
2
- import { toArray as toArray4 } from "@pengzhanbo/utils";
2
+ import process5 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";
6
7
  import fsp2 from "node:fs/promises";
7
8
  import path3 from "node:path";
8
- import process2 from "node:process";
9
+ import process3 from "node:process";
9
10
  import { toArray } from "@pengzhanbo/utils";
10
11
  import fg from "fast-glob";
11
12
  import isCore from "is-core-module";
@@ -17,6 +18,7 @@ import fs2, { promises as fsp } from "node:fs";
17
18
  import { createRequire } from "node:module";
18
19
  import path2 from "node:path";
19
20
  import { pathToFileURL } from "node:url";
21
+ import process from "node:process";
20
22
  import { build } from "esbuild";
21
23
  import JSON5 from "json5";
22
24
 
@@ -157,7 +159,7 @@ function aliasMatches(pattern, importee) {
157
159
  }
158
160
  async function transformWithEsbuild(entryPoint, options) {
159
161
  var _a;
160
- const { isESM = true, define, alias } = options;
162
+ const { isESM = true, define, alias, cwd = process.cwd() } = options;
161
163
  try {
162
164
  const result = await build({
163
165
  entryPoints: [entryPoint],
@@ -169,7 +171,8 @@ async function transformWithEsbuild(entryPoint, options) {
169
171
  metafile: true,
170
172
  format: isESM ? "esm" : "cjs",
171
173
  define,
172
- plugins: [aliasPlugin(alias), externalizeDeps, jsonLoader, json5Loader]
174
+ plugins: [aliasPlugin(alias), externalizeDeps, jsonLoader, json5Loader],
175
+ absWorkingDir: cwd
173
176
  });
174
177
  return {
175
178
  code: result.outputFiles[0].text,
@@ -182,7 +185,13 @@ async function transformWithEsbuild(entryPoint, options) {
182
185
  }
183
186
  var _dirname = getDirname(import.meta.url);
184
187
  var _require = createRequire(_dirname);
185
- async function loadFromCode(filepath, code, isESM, cwd) {
188
+ async function loadFromCode({
189
+ filepath,
190
+ code,
191
+ isESM,
192
+ cwd
193
+ }) {
194
+ filepath = path2.resolve(cwd, filepath);
186
195
  if (isESM) {
187
196
  const fileBase = `${filepath}.timestamp-${Date.now()}`;
188
197
  const fileNameTmp = `${fileBase}.mjs`;
@@ -197,7 +206,6 @@ async function loadFromCode(filepath, code, isESM, cwd) {
197
206
  }
198
207
  }
199
208
  } else {
200
- filepath = path2.resolve(cwd, filepath);
201
209
  const extension = path2.extname(filepath);
202
210
  const realFileName = fs2.realpathSync(filepath);
203
211
  const loaderExt = extension in _require.extensions ? extension : ".js";
@@ -218,10 +226,10 @@ async function loadFromCode(filepath, code, isESM, cwd) {
218
226
  }
219
227
 
220
228
  // src/define.ts
221
- import process from "node:process";
229
+ import process2 from "node:process";
222
230
  function viteDefine(config) {
223
231
  const processNodeEnv = {};
224
- const nodeEnv = process.env.NODE_ENV || config.mode;
232
+ const nodeEnv = process2.env.NODE_ENV || config.mode;
225
233
  Object.assign(processNodeEnv, {
226
234
  "process.env.NODE_ENV": JSON.stringify(nodeEnv),
227
235
  "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
@@ -235,11 +243,13 @@ function viteDefine(config) {
235
243
  if (typeof val === "string") {
236
244
  if (canJsonParse(val)) {
237
245
  userDefine[key] = val;
238
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
246
+ if (isMetaEnv)
247
+ userDefineEnv[key.slice(16)] = val;
239
248
  }
240
249
  } else {
241
250
  userDefine[key] = handleDefineValue(val);
242
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
251
+ if (isMetaEnv)
252
+ userDefineEnv[key.slice(16)] = val;
243
253
  }
244
254
  }
245
255
  const importMetaKeys = {};
@@ -296,11 +306,12 @@ function canJsonParse(value) {
296
306
 
297
307
  // src/build.ts
298
308
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
299
- var packageVersion = true ? "1.5.1" : "latest";
309
+ var packageVersion = true ? "1.6.1" : "latest";
300
310
  async function generateMockServer(ctx, config, options) {
301
311
  const include = toArray(options.include);
302
312
  const exclude = toArray(options.exclude);
303
313
  const define = viteDefine(config);
314
+ const cwd = options.cwd || process3.cwd();
304
315
  const { httpProxies } = ensureProxies(config.server.proxy || {});
305
316
  httpProxies.push(...toArray(options.prefix));
306
317
  const wsProxies = toArray(options.wsPrefix);
@@ -312,8 +323,8 @@ async function generateMockServer(ctx, config, options) {
312
323
  } catch {
313
324
  }
314
325
  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`);
326
+ const content = await generateMockEntryCode(cwd, include, exclude);
327
+ const mockEntry = path3.join(cwd, `mock-data-${Date.now()}.js`);
317
328
  await fsp2.writeFile(mockEntry, content, "utf-8");
318
329
  const { code, deps } = await transformWithEsbuild(mockEntry, {
319
330
  define,
@@ -479,7 +490,7 @@ export default transformMockData(mockList);`;
479
490
  }
480
491
 
481
492
  // src/mockMiddleware.ts
482
- import { isBoolean as isBoolean2, toArray as toArray3, uniq as uniq2 } from "@pengzhanbo/utils";
493
+ import { isBoolean as isBoolean2, toArray as toArray4, uniq as uniq2 } from "@pengzhanbo/utils";
483
494
  import cors from "cors";
484
495
  import { pathToRegexp as pathToRegexp4 } from "path-to-regexp";
485
496
  import c2 from "picocolors";
@@ -940,10 +951,12 @@ async function provideHeaders(req, res, mock, logger) {
940
951
  const { headers, type = "json" } = mock;
941
952
  const filepath = mock.__filepath__;
942
953
  const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
943
- contentType2 && res.setHeader("Content-Type", contentType2);
954
+ if (contentType2)
955
+ res.setHeader("Content-Type", contentType2);
944
956
  res.setHeader("Cache-Control", "no-cache,max-age=0");
945
957
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
946
- filepath && res.setHeader("X-File-Path", filepath);
958
+ if (filepath)
959
+ res.setHeader("X-File-Path", filepath);
947
960
  if (!headers)
948
961
  return;
949
962
  try {
@@ -1074,25 +1087,25 @@ function createLogger(prefix, defaultLevel = "info") {
1074
1087
 
1075
1088
  // src/MockLoader.ts
1076
1089
  import EventEmitter from "node:events";
1077
- import process3 from "node:process";
1078
- import { hasOwn, isArray as isArray5, promiseParallel, toArray as toArray2 } from "@pengzhanbo/utils";
1090
+ import process4 from "node:process";
1091
+ import { hasOwn, isArray as isArray4, promiseParallel, toArray as toArray3 } from "@pengzhanbo/utils";
1079
1092
  import chokidar from "chokidar";
1080
1093
  import fastGlob from "fast-glob";
1081
1094
  import { createFilter as createFilter2 } from "@rollup/pluginutils";
1082
1095
 
1083
1096
  // src/transform.ts
1084
1097
  import {
1085
- isArray as isArray4,
1086
1098
  isEmptyObject as isEmptyObject3,
1087
1099
  isFunction as isFunction2,
1088
1100
  isObject as isObject2,
1089
- sortBy as sortBy2
1101
+ sortBy as sortBy2,
1102
+ toArray as toArray2
1090
1103
  } from "@pengzhanbo/utils";
1091
1104
  function transformMockData(mockList) {
1092
1105
  const list = [];
1093
1106
  for (const [, handle] of mockList.entries()) {
1094
1107
  if (handle)
1095
- isArray4(handle) ? list.push(...handle) : list.push(handle);
1108
+ list.push(...toArray2(handle));
1096
1109
  }
1097
1110
  const mocks = {};
1098
1111
  list.filter((mock) => isObject2(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
@@ -1148,11 +1161,11 @@ var MockLoader = class extends EventEmitter {
1148
1161
  constructor(options) {
1149
1162
  super();
1150
1163
  this.options = options;
1151
- this.cwd = options.cwd || process3.cwd();
1164
+ this.cwd = options.cwd || process4.cwd();
1152
1165
  try {
1153
1166
  const pkg = lookupFile(this.cwd, ["package.json"]);
1154
1167
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
1155
- } catch (e) {
1168
+ } catch {
1156
1169
  }
1157
1170
  }
1158
1171
  moduleCache = /* @__PURE__ */ new Map();
@@ -1180,7 +1193,8 @@ var MockLoader = class extends EventEmitter {
1180
1193
  if (!includeFilter(filepath))
1181
1194
  return;
1182
1195
  await this.loadMock(filepath);
1183
- timer && clearImmediate(timer);
1196
+ if (timer)
1197
+ clearImmediate(timer);
1184
1198
  timer = setImmediate(() => {
1185
1199
  this.updateMockList();
1186
1200
  this.emit("mock:update-end", filepath);
@@ -1202,7 +1216,8 @@ var MockLoader = class extends EventEmitter {
1202
1216
  ignoreInitial: true,
1203
1217
  cwd: this.cwd
1204
1218
  });
1205
- otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1219
+ if (otherGlob.length > 0)
1220
+ otherGlob.forEach((glob) => watcher.add(glob));
1206
1221
  watcher.on("add", async (filepath) => {
1207
1222
  filepath = normalizePath(filepath);
1208
1223
  this.emit("mock:update", filepath);
@@ -1232,7 +1247,7 @@ var MockLoader = class extends EventEmitter {
1232
1247
  this.depsWatcher.on("change", (filepath) => {
1233
1248
  filepath = normalizePath(filepath);
1234
1249
  const mockFiles = this.moduleDeps.get(filepath);
1235
- mockFiles && mockFiles.forEach((file) => {
1250
+ mockFiles == null ? void 0 : mockFiles.forEach((file) => {
1236
1251
  this.emit("mock:update", file);
1237
1252
  });
1238
1253
  });
@@ -1245,7 +1260,8 @@ var MockLoader = class extends EventEmitter {
1245
1260
  for (const [dep] of this.moduleDeps.entries())
1246
1261
  deps.push(dep);
1247
1262
  const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
1248
- exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
1263
+ if (exactDeps.length > 0)
1264
+ this.depsWatcher.add(exactDeps);
1249
1265
  });
1250
1266
  }
1251
1267
  close() {
@@ -1281,25 +1297,25 @@ var MockLoader = class extends EventEmitter {
1281
1297
  const { define, alias } = this.options;
1282
1298
  const { code, deps } = await transformWithEsbuild(
1283
1299
  filepath,
1284
- { isESM, define, alias }
1300
+ { isESM, define, alias, cwd: this.cwd }
1285
1301
  );
1286
1302
  try {
1287
- const raw = await loadFromCode(
1303
+ const raw = await loadFromCode({
1288
1304
  filepath,
1289
1305
  code,
1290
1306
  isESM,
1291
- this.cwd
1292
- ) || {};
1307
+ cwd: this.cwd
1308
+ }) || {};
1293
1309
  let mockConfig;
1294
1310
  if (hasOwn(raw, "default")) {
1295
1311
  mockConfig = raw.default;
1296
1312
  } else {
1297
1313
  mockConfig = [];
1298
1314
  Object.keys(raw).forEach(
1299
- (key) => mockConfig.push(...toArray2(raw[key]))
1315
+ (key) => mockConfig.push(...toArray3(raw[key]))
1300
1316
  );
1301
1317
  }
1302
- if (isArray5(mockConfig)) {
1318
+ if (isArray4(mockConfig)) {
1303
1319
  mockConfig.forEach((mock) => mock.__filepath__ = filepath);
1304
1320
  } else {
1305
1321
  ;
@@ -1331,17 +1347,20 @@ function mockWebSocket({
1331
1347
  const wssContextMap = /* @__PURE__ */ new WeakMap();
1332
1348
  const getWssMap = (mockUrl) => {
1333
1349
  let wssMap = poolMap.get(mockUrl);
1334
- !wssMap && poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1350
+ if (!wssMap)
1351
+ poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1335
1352
  return wssMap;
1336
1353
  };
1337
1354
  const getWss = (wssMap, pathname) => {
1338
1355
  let wss = wssMap.get(pathname);
1339
- !wss && wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
1356
+ if (!wss)
1357
+ wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
1340
1358
  return wss;
1341
1359
  };
1342
1360
  const addHmr = (filepath, mockUrl) => {
1343
1361
  let urlList = hmrMap.get(filepath);
1344
- !urlList && hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1362
+ if (!urlList)
1363
+ hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1345
1364
  urlList.add(mockUrl);
1346
1365
  };
1347
1366
  const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
@@ -1478,8 +1497,9 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1478
1497
  isBoolean2(options.log) ? options.log ? "info" : "error" : options.log
1479
1498
  );
1480
1499
  const loader = new MockLoader({
1481
- include: toArray3(options.include),
1482
- exclude: toArray3(options.exclude),
1500
+ cwd: options.cwd,
1501
+ include: toArray4(options.include),
1502
+ exclude: toArray4(options.exclude),
1483
1503
  define: viteDefine(config),
1484
1504
  alias: config.resolve.alias
1485
1505
  });
@@ -1490,14 +1510,14 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1490
1510
  });
1491
1511
  httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
1492
1512
  const { httpProxies } = ensureProxies(config.server.proxy || {});
1493
- const prefix = toArray3(options.prefix);
1513
+ const prefix = toArray4(options.prefix);
1494
1514
  const proxies = uniq2([...prefix, ...httpProxies]);
1495
- if (!proxies.length && !toArray3(options.wsPrefix).length)
1515
+ if (!proxies.length && !toArray4(options.wsPrefix).length)
1496
1516
  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
1517
  mockWebSocket({
1498
1518
  loader,
1499
1519
  httpServer,
1500
- proxies: toArray3(options.wsPrefix),
1520
+ proxies: toArray4(options.wsPrefix),
1501
1521
  cookiesOptions: options.cookiesOptions,
1502
1522
  logger
1503
1523
  });
@@ -1562,6 +1582,7 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1562
1582
  function mockDevServerPlugin({
1563
1583
  prefix = [],
1564
1584
  wsPrefix = [],
1585
+ cwd = process5.cwd(),
1565
1586
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
1566
1587
  exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
1567
1588
  reload = false,
@@ -1576,6 +1597,7 @@ function mockDevServerPlugin({
1576
1597
  const pluginOptions = {
1577
1598
  prefix,
1578
1599
  wsPrefix,
1600
+ cwd,
1579
1601
  include,
1580
1602
  exclude,
1581
1603
  reload,
@@ -1629,7 +1651,7 @@ function serverPlugin(pluginOptions) {
1629
1651
  apply: "serve",
1630
1652
  config(config) {
1631
1653
  var _a;
1632
- const wsPrefix = toArray4(pluginOptions.wsPrefix);
1654
+ const wsPrefix = toArray5(pluginOptions.wsPrefix);
1633
1655
  if (wsPrefix.length && ((_a = config.server) == null ? void 0 : _a.proxy)) {
1634
1656
  const proxy = {};
1635
1657
  Object.keys(config.server.proxy).forEach((key) => {
@@ -1665,13 +1687,13 @@ function serverPlugin(pluginOptions) {
1665
1687
  }
1666
1688
 
1667
1689
  // src/defineMock.ts
1668
- import { isArray as isArray6 } from "@pengzhanbo/utils";
1690
+ import { isArray as isArray5 } from "@pengzhanbo/utils";
1669
1691
  function defineMock(config) {
1670
1692
  return config;
1671
1693
  }
1672
1694
  function createDefineMock(transformer) {
1673
1695
  const define = (config) => {
1674
- if (isArray6(config))
1696
+ if (isArray5(config))
1675
1697
  config = config.map((item) => transformer(item) || item);
1676
1698
  else
1677
1699
  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.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",
@@ -48,20 +48,20 @@
48
48
  "co-body": "^6.2.0",
49
49
  "cookies": "^0.9.1",
50
50
  "cors": "^2.8.5",
51
- "debug": "^4.3.5",
52
- "esbuild": "^0.21.5",
51
+ "debug": "^4.3.6",
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.13",
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.8.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.5",
81
+ "vitepress": "^1.3.1",
82
+ "vitest": "^2.0.4"
83
83
  },
84
84
  "scripts": {
85
85
  "build": "tsup && node ./deprecate.mjs",