vite-plugin-mock-dev-server 1.4.0 → 1.4.2

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
@@ -232,6 +232,11 @@ export default defineConfig({
232
232
  * @default 'mockServer'
233
233
  */
234
234
  dist?: string
235
+ /**
236
+ * log level
237
+ * @default 'error'
238
+ */
239
+ log?: LogLevel
235
240
  }
236
241
  ```
237
242
 
package/README.zh-CN.md CHANGED
@@ -227,6 +227,12 @@ export default defineConfig({
227
227
  * @default 'mockServer'
228
228
  */
229
229
  dist?: string
230
+
231
+ /**
232
+ * 日志级别
233
+ * @default 'error'
234
+ */
235
+ log?: LogLevel
230
236
  }
231
237
  ```
232
238
 
package/dist/index.cjs CHANGED
@@ -32,9 +32,11 @@ var src_exports = {};
32
32
  __export(src_exports, {
33
33
  baseMiddleware: () => baseMiddleware,
34
34
  createDefineMock: () => createDefineMock,
35
+ createLogger: () => createLogger,
35
36
  default: () => src_default,
36
37
  defineMock: () => defineMock,
37
38
  defineMockData: () => defineMockData,
39
+ logLevels: () => logLevels,
38
40
  mockDevServerPlugin: () => mockDevServerPlugin,
39
41
  mockWebSocket: () => mockWebSocket,
40
42
  sortByValidator: () => sortByValidator,
@@ -42,7 +44,7 @@ __export(src_exports, {
42
44
  });
43
45
  module.exports = __toCommonJS(src_exports);
44
46
 
45
- // node_modules/.pnpm/tsup@8.0.1_typescript@5.3.2/node_modules/tsup/assets/cjs_shims.js
47
+ // node_modules/.pnpm/tsup@8.0.1_typescript@5.3.3/node_modules/tsup/assets/cjs_shims.js
46
48
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
47
49
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
48
50
 
@@ -57,11 +59,11 @@ var import_node_process2 = __toESM(require("process"), 1);
57
59
  var import_utils3 = require("@pengzhanbo/utils");
58
60
  var import_fast_glob = __toESM(require("fast-glob"), 1);
59
61
  var import_is_core_module = __toESM(require("is-core-module"), 1);
60
- var import_vite = require("vite");
62
+ var import_pluginutils = require("@rollup/pluginutils");
61
63
 
62
64
  // package.json
63
65
  var name = "vite-plugin-mock-dev-server";
64
- var version = "1.4.0";
66
+ var version = "1.4.2";
65
67
 
66
68
  // src/compiler.ts
67
69
  var import_node_fs2 = __toESM(require("fs"), 1);
@@ -76,6 +78,7 @@ var import_node_fs = __toESM(require("fs"), 1);
76
78
  var import_node_path = __toESM(require("path"), 1);
77
79
  var import_node_querystring = require("querystring");
78
80
  var import_node_url = require("url");
81
+ var import_node_os = __toESM(require("os"), 1);
79
82
  var import_debug = __toESM(require("debug"), 1);
80
83
  var import_path_to_regexp = require("path-to-regexp");
81
84
  function isStream(stream) {
@@ -129,6 +132,14 @@ function urlParse(input) {
129
132
  const query = (0, import_node_querystring.parse)(url.search.replace(/^\?/, ""));
130
133
  return { pathname, query };
131
134
  }
135
+ var windowsSlashRE = /\\/g;
136
+ var isWindows = import_node_os.default.platform() === "win32";
137
+ function slash(p) {
138
+ return p.replace(windowsSlashRE, "/");
139
+ }
140
+ function normalizePath(id) {
141
+ return import_node_path.default.posix.normalize(isWindows ? slash(id) : id);
142
+ }
132
143
 
133
144
  // src/compiler.ts
134
145
  var externalizeDeps = {
@@ -169,7 +180,7 @@ function aliasPlugin(alias) {
169
180
  name: "alias-plugin",
170
181
  setup(build2) {
171
182
  build2.onResolve({ filter: /.*/ }, async ({ path: id }) => {
172
- const matchedEntry = alias.find(({ find: find2 }) => matches(find2, id));
183
+ const matchedEntry = alias.find(({ find: find2 }) => aliasMatches(find2, id));
173
184
  if (!matchedEntry)
174
185
  return null;
175
186
  const { find, replacement } = matchedEntry;
@@ -186,7 +197,7 @@ function aliasPlugin(alias) {
186
197
  }
187
198
  };
188
199
  }
189
- function matches(pattern, importee) {
200
+ function aliasMatches(pattern, importee) {
190
201
  if (pattern instanceof RegExp)
191
202
  return pattern.test(importee);
192
203
  if (importee.length < pattern.length)
@@ -385,7 +396,7 @@ async function generateMockServer(ctx, config, options) {
385
396
  define,
386
397
  alias: config.resolve.alias
387
398
  });
388
- const mockDeps = getMockDependencies(deps);
399
+ const mockDeps = getMockDependencies(deps, config.resolve.alias);
389
400
  await import_promises.default.unlink(mockEntry);
390
401
  const outputList = [
391
402
  {
@@ -399,7 +410,7 @@ async function generateMockServer(ctx, config, options) {
399
410
  wsProxies,
400
411
  options.cookiesOptions,
401
412
  options.priority,
402
- options.build.serverPort
413
+ options.build
403
414
  )
404
415
  },
405
416
  {
@@ -409,7 +420,8 @@ async function generateMockServer(ctx, config, options) {
409
420
  ];
410
421
  try {
411
422
  if (import_node_path3.default.isAbsolute(outputDir)) {
412
- await import_promises.default.rm(outputDir, { recursive: true });
423
+ for (const { filename } of outputList)
424
+ await import_promises.default.rm(filename);
413
425
  import_node_fs3.default.mkdirSync(outputDir, { recursive: true });
414
426
  for (const { filename, source } of outputList)
415
427
  await import_promises.default.writeFile(filename, source, "utf-8");
@@ -425,11 +437,12 @@ async function generateMockServer(ctx, config, options) {
425
437
  } catch {
426
438
  }
427
439
  }
428
- function getMockDependencies(deps) {
440
+ function getMockDependencies(deps, alias) {
429
441
  const list = /* @__PURE__ */ new Set();
430
442
  const excludeDeps = [name, "connect", "cors"];
443
+ const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
431
444
  Object.keys(deps).forEach((mPath) => {
432
- const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:")).map((_) => _.path);
445
+ const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
433
446
  imports.forEach((dep) => {
434
447
  if (!excludeDeps.includes(dep) && !(0, import_is_core_module.default)(dep))
435
448
  list.add(dep);
@@ -458,21 +471,29 @@ function generatePackageJson(pkg, mockDeps) {
458
471
  });
459
472
  return JSON.stringify(mockPkg, null, 2);
460
473
  }
461
- function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, port = 8080) {
474
+ function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, build2) {
475
+ const { serverPort, log } = build2;
462
476
  return `import { createServer } from 'node:http';
463
477
  import connect from 'connect';
464
478
  import corsMiddleware from 'cors';
465
- import { baseMiddleware, mockWebSocket } from 'vite-plugin-mock-dev-server';
479
+ import { baseMiddleware, mockWebSocket, createLogger } from 'vite-plugin-mock-dev-server';
466
480
  import mockData from './mock-data.js';
467
481
 
468
482
  const app = connect();
469
483
  const server = createServer(app);
484
+ const logger = createLogger('mock-server', '${log}');
470
485
  const httpProxies = ${JSON.stringify(httpProxies)};
471
486
  const wsProxies = ${JSON.stringify(wsProxies)};
472
487
  const cookiesOptions = ${JSON.stringify(cookiesOptions)};
473
488
  const priority = ${JSON.stringify(priority)};
474
489
 
475
- mockWebSocket({ mockData }, server, wsProxies, cookiesOptions);
490
+ mockWebSocket({
491
+ loader: { mockData },
492
+ httpServer: server,
493
+ proxies: wsProxies,
494
+ cookiesOptions,
495
+ logger,
496
+ });
476
497
 
477
498
  app.use(corsMiddleware());
478
499
  app.use(baseMiddleware({ mockData }, {
@@ -480,23 +501,24 @@ app.use(baseMiddleware({ mockData }, {
480
501
  proxies: httpProxies,
481
502
  priority,
482
503
  cookiesOptions,
504
+ logger,
483
505
  }));
484
506
 
485
- server.listen(${port});
507
+ server.listen(${serverPort});
486
508
 
487
- console.log('listen: http://localhost:${port}');
509
+ console.log('listen: http://localhost:${serverPort}');
488
510
  `;
489
511
  }
490
512
  async function generateMockEntryCode(cwd, include, exclude) {
491
513
  const includePaths = await (0, import_fast_glob.default)(include, { cwd });
492
- const includeFilter = (0, import_vite.createFilter)(include, exclude, {
514
+ const includeFilter = (0, import_pluginutils.createFilter)(include, exclude, {
493
515
  resolve: false
494
516
  });
495
517
  const mockFiles = includePaths.filter(includeFilter);
496
518
  let importers = "";
497
519
  let exporters = "";
498
520
  mockFiles.forEach((filepath, index) => {
499
- const file = (0, import_vite.normalizePath)(import_node_path3.default.join(cwd, filepath));
521
+ const file = normalizePath(import_node_path3.default.join(cwd, filepath));
500
522
  importers += `import * as m${index} from '${file}';
501
523
  `;
502
524
  exporters += `m${index}, `;
@@ -511,7 +533,7 @@ const mockList = exporters.map((raw) => {
511
533
  } else {
512
534
  mockConfig = []
513
535
  Object.keys(raw || {}).forEach((key) => {
514
- isArray(raw[key])
536
+ Array.isArray(raw[key])
515
537
  ? mockConfig.push(...raw[key])
516
538
  : mockConfig.push(raw[key])
517
539
  })
@@ -957,7 +979,7 @@ async function provideHeaders(req, res, mock, logger) {
957
979
  contentType2 && res.setHeader("Content-Type", contentType2);
958
980
  res.setHeader("Cache-Control", "no-cache,max-age=0");
959
981
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
960
- res.setHeader("X-File-Path", filepath);
982
+ filepath && res.setHeader("X-File-Path", filepath);
961
983
  if (!headers)
962
984
  return;
963
985
  try {
@@ -1050,7 +1072,7 @@ var import_node_process3 = __toESM(require("process"), 1);
1050
1072
  var import_utils11 = require("@pengzhanbo/utils");
1051
1073
  var import_chokidar = __toESM(require("chokidar"), 1);
1052
1074
  var import_fast_glob2 = __toESM(require("fast-glob"), 1);
1053
- var import_vite2 = require("vite");
1075
+ var import_pluginutils2 = require("@rollup/pluginutils");
1054
1076
 
1055
1077
  // src/transform.ts
1056
1078
  var import_utils9 = require("@pengzhanbo/utils");
@@ -1133,7 +1155,7 @@ var MockLoader = class extends import_node_events.default {
1133
1155
  }
1134
1156
  load() {
1135
1157
  const { include, exclude } = this.options;
1136
- const includeFilter = (0, import_vite2.createFilter)(include, exclude, {
1158
+ const includeFilter = (0, import_pluginutils2.createFilter)(include, exclude, {
1137
1159
  resolve: false
1138
1160
  });
1139
1161
  (0, import_fast_glob2.default)(include, { cwd: this.cwd }).then(
@@ -1170,17 +1192,17 @@ var MockLoader = class extends import_node_events.default {
1170
1192
  });
1171
1193
  otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1172
1194
  watcher.on("add", async (filepath) => {
1173
- filepath = (0, import_vite2.normalizePath)(filepath);
1195
+ filepath = normalizePath(filepath);
1174
1196
  this.emit("mock:update", filepath);
1175
1197
  debug("watcher:add", filepath);
1176
1198
  });
1177
1199
  watcher.on("change", async (filepath) => {
1178
- filepath = (0, import_vite2.normalizePath)(filepath);
1200
+ filepath = normalizePath(filepath);
1179
1201
  this.emit("mock:update", filepath);
1180
1202
  debug("watcher:change", filepath);
1181
1203
  });
1182
1204
  watcher.on("unlink", async (filepath) => {
1183
- filepath = (0, import_vite2.normalizePath)(filepath);
1205
+ filepath = normalizePath(filepath);
1184
1206
  this.emit("mock:unlink", filepath);
1185
1207
  debug("watcher:unlink", filepath);
1186
1208
  });
@@ -1196,14 +1218,14 @@ var MockLoader = class extends import_node_events.default {
1196
1218
  cwd: this.cwd
1197
1219
  });
1198
1220
  this.depsWatcher.on("change", (filepath) => {
1199
- filepath = (0, import_vite2.normalizePath)(filepath);
1221
+ filepath = normalizePath(filepath);
1200
1222
  const mockFiles = this.moduleDeps.get(filepath);
1201
1223
  mockFiles && mockFiles.forEach((file) => {
1202
1224
  this.emit("mock:update", file);
1203
1225
  });
1204
1226
  });
1205
1227
  this.depsWatcher.on("unlink", (filepath) => {
1206
- filepath = (0, import_vite2.normalizePath)(filepath);
1228
+ filepath = normalizePath(filepath);
1207
1229
  this.moduleDeps.delete(filepath);
1208
1230
  });
1209
1231
  this.on("update:deps", () => {
@@ -1551,7 +1573,8 @@ function mockDevServerPlugin({
1551
1573
  build: build2 ? Object.assign(
1552
1574
  {
1553
1575
  serverPort: 8080,
1554
- dist: "mockServer"
1576
+ dist: "mockServer",
1577
+ log: "error"
1555
1578
  },
1556
1579
  typeof build2 === "object" ? build2 : {}
1557
1580
  ) : false
@@ -1697,10 +1720,24 @@ var src_default = mockDevServerPlugin;
1697
1720
  0 && (module.exports = {
1698
1721
  baseMiddleware,
1699
1722
  createDefineMock,
1723
+ createLogger,
1700
1724
  defineMock,
1701
1725
  defineMockData,
1726
+ logLevels,
1702
1727
  mockDevServerPlugin,
1703
1728
  mockWebSocket,
1704
1729
  sortByValidator,
1705
1730
  transformMockData
1706
1731
  });
1732
+
1733
+ warnCjsUsage()
1734
+ function warnCjsUsage() {
1735
+ if (process.env.VITE_CJS_IGNORE_WARNING) return
1736
+ const yellow = (str) => `\u001b[33m${str}\u001b[39m`
1737
+ const log = process.env.VITE_CJS_TRACE ? console.trace : console.warn
1738
+ log(
1739
+ yellow(
1740
+ `The CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.`,
1741
+ ),
1742
+ )
1743
+ }
package/dist/index.d.cts CHANGED
@@ -208,6 +208,13 @@ interface ServerBuildOption {
208
208
  * @default 'dist/mockServer'
209
209
  */
210
210
  dist?: string;
211
+ /**
212
+ * Service application log level
213
+ *
214
+ * 服务应用日志级别
215
+ * @default 'error'
216
+ */
217
+ log?: LogLevel;
211
218
  }
212
219
  type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'TRACE' | 'OPTIONS';
213
220
  type Headers = http.IncomingHttpHeaders;
@@ -542,6 +549,7 @@ type FormidableFile = formidable.File | formidable.File[];
542
549
  type LogType = 'info' | 'warn' | 'error' | 'debug';
543
550
  type LogLevel = LogType | 'silent';
544
551
 
552
+ /** @deprecated The CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details. */
545
553
  declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, priority, }?: MockServerPluginOptions): Plugin[];
546
554
 
547
555
  /**
@@ -624,6 +632,8 @@ interface Logger {
624
632
  warn(msg: string, level?: boolean | LogLevel): void;
625
633
  error(msg: string, level?: boolean | LogLevel): void;
626
634
  }
635
+ declare const logLevels: Record<LogLevel, number>;
636
+ declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
627
637
 
628
638
  interface MockLoaderOptions {
629
639
  cwd?: string;
@@ -692,4 +702,4 @@ declare function mockWebSocket({ loader, httpServer, proxies, cookiesOptions, lo
692
702
  declare function transformMockData(mockList: Map<string, MockHttpItem | MockWebsocketItem | MockOptions> | (MockHttpItem | MockWebsocketItem | MockOptions)[]): Record<string, MockOptions>;
693
703
  declare function sortByValidator(mocks: MockOptions): (MockHttpItem | MockWebsocketItem)[];
694
704
 
695
- export { type BaseMiddlewareOptions, type FormidableFile, type MockData, type MockHttpItem, type MockOptions, type MockRequest, type MockServerPluginOptions, type MockSocketOptions, type MockWebsocketItem, baseMiddleware, createDefineMock, mockDevServerPlugin as default, defineMock, defineMockData, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData };
705
+ export { type BaseMiddlewareOptions, type FormidableFile, type Logger, type MockData, type MockHttpItem, type MockOptions, type MockRequest, type MockServerPluginOptions, type MockSocketOptions, type MockWebsocketItem, baseMiddleware, createDefineMock, createLogger, mockDevServerPlugin as default, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData };
package/dist/index.d.ts CHANGED
@@ -208,6 +208,13 @@ interface ServerBuildOption {
208
208
  * @default 'dist/mockServer'
209
209
  */
210
210
  dist?: string;
211
+ /**
212
+ * Service application log level
213
+ *
214
+ * 服务应用日志级别
215
+ * @default 'error'
216
+ */
217
+ log?: LogLevel;
211
218
  }
212
219
  type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'TRACE' | 'OPTIONS';
213
220
  type Headers = http.IncomingHttpHeaders;
@@ -624,6 +631,8 @@ interface Logger {
624
631
  warn(msg: string, level?: boolean | LogLevel): void;
625
632
  error(msg: string, level?: boolean | LogLevel): void;
626
633
  }
634
+ declare const logLevels: Record<LogLevel, number>;
635
+ declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
627
636
 
628
637
  interface MockLoaderOptions {
629
638
  cwd?: string;
@@ -692,4 +701,4 @@ declare function mockWebSocket({ loader, httpServer, proxies, cookiesOptions, lo
692
701
  declare function transformMockData(mockList: Map<string, MockHttpItem | MockWebsocketItem | MockOptions> | (MockHttpItem | MockWebsocketItem | MockOptions)[]): Record<string, MockOptions>;
693
702
  declare function sortByValidator(mocks: MockOptions): (MockHttpItem | MockWebsocketItem)[];
694
703
 
695
- export { type BaseMiddlewareOptions, type FormidableFile, type MockData, type MockHttpItem, type MockOptions, type MockRequest, type MockServerPluginOptions, type MockSocketOptions, type MockWebsocketItem, baseMiddleware, createDefineMock, mockDevServerPlugin as default, defineMock, defineMockData, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData };
704
+ export { type BaseMiddlewareOptions, type FormidableFile, type Logger, type MockData, type MockHttpItem, type MockOptions, type MockRequest, type MockServerPluginOptions, type MockSocketOptions, type MockWebsocketItem, baseMiddleware, createDefineMock, createLogger, mockDevServerPlugin as default, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData };
package/dist/index.js CHANGED
@@ -9,11 +9,11 @@ import process2 from "node:process";
9
9
  import { toArray } from "@pengzhanbo/utils";
10
10
  import fg from "fast-glob";
11
11
  import isCore from "is-core-module";
12
- import { createFilter, normalizePath } from "vite";
12
+ import { createFilter } from "@rollup/pluginutils";
13
13
 
14
14
  // package.json
15
15
  var name = "vite-plugin-mock-dev-server";
16
- var version = "1.4.0";
16
+ var version = "1.4.2";
17
17
 
18
18
  // src/compiler.ts
19
19
  import fs2, { promises as fsp } from "node:fs";
@@ -28,6 +28,7 @@ import fs from "node:fs";
28
28
  import path from "node:path";
29
29
  import { parse as queryParse } from "node:querystring";
30
30
  import { URL as URL2, fileURLToPath } from "node:url";
31
+ import os from "node:os";
31
32
  import Debug from "debug";
32
33
  import { match } from "path-to-regexp";
33
34
  function isStream(stream) {
@@ -81,6 +82,14 @@ function urlParse(input) {
81
82
  const query = queryParse(url.search.replace(/^\?/, ""));
82
83
  return { pathname, query };
83
84
  }
85
+ var windowsSlashRE = /\\/g;
86
+ var isWindows = os.platform() === "win32";
87
+ function slash(p) {
88
+ return p.replace(windowsSlashRE, "/");
89
+ }
90
+ function normalizePath(id) {
91
+ return path.posix.normalize(isWindows ? slash(id) : id);
92
+ }
84
93
 
85
94
  // src/compiler.ts
86
95
  var externalizeDeps = {
@@ -121,7 +130,7 @@ function aliasPlugin(alias) {
121
130
  name: "alias-plugin",
122
131
  setup(build2) {
123
132
  build2.onResolve({ filter: /.*/ }, async ({ path: id }) => {
124
- const matchedEntry = alias.find(({ find: find2 }) => matches(find2, id));
133
+ const matchedEntry = alias.find(({ find: find2 }) => aliasMatches(find2, id));
125
134
  if (!matchedEntry)
126
135
  return null;
127
136
  const { find, replacement } = matchedEntry;
@@ -138,7 +147,7 @@ function aliasPlugin(alias) {
138
147
  }
139
148
  };
140
149
  }
141
- function matches(pattern, importee) {
150
+ function aliasMatches(pattern, importee) {
142
151
  if (pattern instanceof RegExp)
143
152
  return pattern.test(importee);
144
153
  if (importee.length < pattern.length)
@@ -337,7 +346,7 @@ async function generateMockServer(ctx, config, options) {
337
346
  define,
338
347
  alias: config.resolve.alias
339
348
  });
340
- const mockDeps = getMockDependencies(deps);
349
+ const mockDeps = getMockDependencies(deps, config.resolve.alias);
341
350
  await fsp2.unlink(mockEntry);
342
351
  const outputList = [
343
352
  {
@@ -351,7 +360,7 @@ async function generateMockServer(ctx, config, options) {
351
360
  wsProxies,
352
361
  options.cookiesOptions,
353
362
  options.priority,
354
- options.build.serverPort
363
+ options.build
355
364
  )
356
365
  },
357
366
  {
@@ -361,7 +370,8 @@ async function generateMockServer(ctx, config, options) {
361
370
  ];
362
371
  try {
363
372
  if (path3.isAbsolute(outputDir)) {
364
- await fsp2.rm(outputDir, { recursive: true });
373
+ for (const { filename } of outputList)
374
+ await fsp2.rm(filename);
365
375
  fs3.mkdirSync(outputDir, { recursive: true });
366
376
  for (const { filename, source } of outputList)
367
377
  await fsp2.writeFile(filename, source, "utf-8");
@@ -377,11 +387,12 @@ async function generateMockServer(ctx, config, options) {
377
387
  } catch {
378
388
  }
379
389
  }
380
- function getMockDependencies(deps) {
390
+ function getMockDependencies(deps, alias) {
381
391
  const list = /* @__PURE__ */ new Set();
382
392
  const excludeDeps = [name, "connect", "cors"];
393
+ const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
383
394
  Object.keys(deps).forEach((mPath) => {
384
- const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:")).map((_) => _.path);
395
+ const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
385
396
  imports.forEach((dep) => {
386
397
  if (!excludeDeps.includes(dep) && !isCore(dep))
387
398
  list.add(dep);
@@ -410,21 +421,29 @@ function generatePackageJson(pkg, mockDeps) {
410
421
  });
411
422
  return JSON.stringify(mockPkg, null, 2);
412
423
  }
413
- function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, port = 8080) {
424
+ function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, build2) {
425
+ const { serverPort, log } = build2;
414
426
  return `import { createServer } from 'node:http';
415
427
  import connect from 'connect';
416
428
  import corsMiddleware from 'cors';
417
- import { baseMiddleware, mockWebSocket } from 'vite-plugin-mock-dev-server';
429
+ import { baseMiddleware, mockWebSocket, createLogger } from 'vite-plugin-mock-dev-server';
418
430
  import mockData from './mock-data.js';
419
431
 
420
432
  const app = connect();
421
433
  const server = createServer(app);
434
+ const logger = createLogger('mock-server', '${log}');
422
435
  const httpProxies = ${JSON.stringify(httpProxies)};
423
436
  const wsProxies = ${JSON.stringify(wsProxies)};
424
437
  const cookiesOptions = ${JSON.stringify(cookiesOptions)};
425
438
  const priority = ${JSON.stringify(priority)};
426
439
 
427
- mockWebSocket({ mockData }, server, wsProxies, cookiesOptions);
440
+ mockWebSocket({
441
+ loader: { mockData },
442
+ httpServer: server,
443
+ proxies: wsProxies,
444
+ cookiesOptions,
445
+ logger,
446
+ });
428
447
 
429
448
  app.use(corsMiddleware());
430
449
  app.use(baseMiddleware({ mockData }, {
@@ -432,11 +451,12 @@ app.use(baseMiddleware({ mockData }, {
432
451
  proxies: httpProxies,
433
452
  priority,
434
453
  cookiesOptions,
454
+ logger,
435
455
  }));
436
456
 
437
- server.listen(${port});
457
+ server.listen(${serverPort});
438
458
 
439
- console.log('listen: http://localhost:${port}');
459
+ console.log('listen: http://localhost:${serverPort}');
440
460
  `;
441
461
  }
442
462
  async function generateMockEntryCode(cwd, include, exclude) {
@@ -463,7 +483,7 @@ const mockList = exporters.map((raw) => {
463
483
  } else {
464
484
  mockConfig = []
465
485
  Object.keys(raw || {}).forEach((key) => {
466
- isArray(raw[key])
486
+ Array.isArray(raw[key])
467
487
  ? mockConfig.push(...raw[key])
468
488
  : mockConfig.push(raw[key])
469
489
  })
@@ -922,7 +942,7 @@ async function provideHeaders(req, res, mock, logger) {
922
942
  contentType2 && res.setHeader("Content-Type", contentType2);
923
943
  res.setHeader("Cache-Control", "no-cache,max-age=0");
924
944
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
925
- res.setHeader("X-File-Path", filepath);
945
+ filepath && res.setHeader("X-File-Path", filepath);
926
946
  if (!headers)
927
947
  return;
928
948
  try {
@@ -1015,7 +1035,7 @@ import process3 from "node:process";
1015
1035
  import { hasOwn, isArray as isArray5, promiseParallel, toArray as toArray2 } from "@pengzhanbo/utils";
1016
1036
  import chokidar from "chokidar";
1017
1037
  import fastGlob from "fast-glob";
1018
- import { createFilter as createFilter2, normalizePath as normalizePath2 } from "vite";
1038
+ import { createFilter as createFilter2 } from "@rollup/pluginutils";
1019
1039
 
1020
1040
  // src/transform.ts
1021
1041
  import {
@@ -1141,17 +1161,17 @@ var MockLoader = class extends EventEmitter {
1141
1161
  });
1142
1162
  otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1143
1163
  watcher.on("add", async (filepath) => {
1144
- filepath = normalizePath2(filepath);
1164
+ filepath = normalizePath(filepath);
1145
1165
  this.emit("mock:update", filepath);
1146
1166
  debug("watcher:add", filepath);
1147
1167
  });
1148
1168
  watcher.on("change", async (filepath) => {
1149
- filepath = normalizePath2(filepath);
1169
+ filepath = normalizePath(filepath);
1150
1170
  this.emit("mock:update", filepath);
1151
1171
  debug("watcher:change", filepath);
1152
1172
  });
1153
1173
  watcher.on("unlink", async (filepath) => {
1154
- filepath = normalizePath2(filepath);
1174
+ filepath = normalizePath(filepath);
1155
1175
  this.emit("mock:unlink", filepath);
1156
1176
  debug("watcher:unlink", filepath);
1157
1177
  });
@@ -1167,14 +1187,14 @@ var MockLoader = class extends EventEmitter {
1167
1187
  cwd: this.cwd
1168
1188
  });
1169
1189
  this.depsWatcher.on("change", (filepath) => {
1170
- filepath = normalizePath2(filepath);
1190
+ filepath = normalizePath(filepath);
1171
1191
  const mockFiles = this.moduleDeps.get(filepath);
1172
1192
  mockFiles && mockFiles.forEach((file) => {
1173
1193
  this.emit("mock:update", file);
1174
1194
  });
1175
1195
  });
1176
1196
  this.depsWatcher.on("unlink", (filepath) => {
1177
- filepath = normalizePath2(filepath);
1197
+ filepath = normalizePath(filepath);
1178
1198
  this.moduleDeps.delete(filepath);
1179
1199
  });
1180
1200
  this.on("update:deps", () => {
@@ -1522,7 +1542,8 @@ function mockDevServerPlugin({
1522
1542
  build: build2 ? Object.assign(
1523
1543
  {
1524
1544
  serverPort: 8080,
1525
- dist: "mockServer"
1545
+ dist: "mockServer",
1546
+ log: "error"
1526
1547
  },
1527
1548
  typeof build2 === "object" ? build2 : {}
1528
1549
  ) : false
@@ -1667,9 +1688,11 @@ var src_default = mockDevServerPlugin;
1667
1688
  export {
1668
1689
  baseMiddleware,
1669
1690
  createDefineMock,
1691
+ createLogger,
1670
1692
  src_default as default,
1671
1693
  defineMock,
1672
1694
  defineMockData,
1695
+ logLevels,
1673
1696
  mockDevServerPlugin,
1674
1697
  mockWebSocket,
1675
1698
  sortByValidator,
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.4.0",
4
+ "version": "1.4.2",
5
5
  "packageManager": "pnpm@8.11.0",
6
6
  "author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
7
7
  "license": "MIT",
@@ -44,12 +44,13 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@pengzhanbo/utils": "^1.1.1",
47
+ "@rollup/pluginutils": "^5.1.0",
47
48
  "chokidar": "^3.5.3",
48
49
  "co-body": "^6.1.0",
49
50
  "cookies": "^0.8.0",
50
51
  "cors": "^2.8.5",
51
52
  "debug": "^4.3.4",
52
- "esbuild": "^0.19.8",
53
+ "esbuild": "^0.19.9",
53
54
  "fast-glob": "^3.3.2",
54
55
  "formidable": "2.1.1",
55
56
  "http-status": "^1.7.3",
@@ -58,10 +59,10 @@
58
59
  "mime-types": "^2.1.35",
59
60
  "path-to-regexp": "^6.2.1",
60
61
  "picocolors": "^1.0.0",
61
- "ws": "^8.14.2"
62
+ "ws": "^8.15.1"
62
63
  },
63
64
  "devDependencies": {
64
- "@pengzhanbo/eslint-config": "^1.2.5",
65
+ "@pengzhanbo/eslint-config": "^1.3.1",
65
66
  "@types/co-body": "^6.1.3",
66
67
  "@types/cookies": "^0.7.10",
67
68
  "@types/cors": "^2.8.17",
@@ -69,20 +70,20 @@
69
70
  "@types/formidable": "2.0.6",
70
71
  "@types/is-core-module": "^2.2.2",
71
72
  "@types/mime-types": "^2.1.4",
72
- "@types/node": "^20.10.2",
73
+ "@types/node": "^20.10.3",
73
74
  "@types/ws": "^8.5.10",
74
- "bumpp": "^9.2.0",
75
+ "bumpp": "^9.2.1",
75
76
  "conventional-changelog-cli": "^4.1.0",
76
77
  "eslint": "^8.55.0",
77
78
  "mockjs": "^1.1.0",
78
79
  "tsup": "^8.0.1",
79
- "typescript": "^5.3.2",
80
- "vite": "^5.0.4",
80
+ "typescript": "^5.3.3",
81
+ "vite": "^5.0.8",
81
82
  "vitepress": "^1.0.0-rc.31",
82
- "vitest": "^0.34.6"
83
+ "vitest": "^1.0.4"
83
84
  },
84
85
  "scripts": {
85
- "build": "tsup",
86
+ "build": "tsup && node ./deprecate.mjs",
86
87
  "dev": "DEBUG=vite:mock-dev-server vite example --config ./example/vite.config.ts",
87
88
  "example:build": "DEBUG=vite:mock-dev-server vite build example --config ./example/vite.config.ts",
88
89
  "docs:build": "vitepress build docs",