vite-plugin-mock-dev-server 1.9.3 → 2.0.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/dist/index.js CHANGED
@@ -1,36 +1,34 @@
1
- import { isArray, isBoolean, promiseParallel, toArray, uniq } from "./dist-CAA1v47s.js";
2
- import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-DHb-Bj_j.js";
3
- import { baseMiddleware, createLogger, debug, doesProxyContextMatchUrl, ensureProxies, logLevels, lookupFile, mockWebSocket, normalizePath, recoverRequest, sortByValidator, transformMockData, transformRawData, urlParse } from "./server-C-u7jwot.js";
4
- import pc from "picocolors";
1
+ import { createLogger, createMatcher, createMockMiddleware, debug, doesProxyContextMatchUrl, isPackageExists, isPathMatch, logLevels, mockWebSocket, normalizePath, processMockData, processRawData, recoverRequest, sortByValidator, urlParse } from "./server-G9rXmGpR.js";
2
+ import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-BbR8Si2U.js";
3
+ import { isArray, isBoolean, promiseParallel, toArray, uniq } from "@pengzhanbo/utils";
5
4
  import fs, { promises } from "node:fs";
6
5
  import fsp from "node:fs/promises";
7
6
  import path from "node:path";
8
7
  import process from "node:process";
9
- import { createFilter } from "@rollup/pluginutils";
10
- import fg from "fast-glob";
11
- import isCore from "is-core-module";
8
+ import ansis from "ansis";
9
+ import { getPackageInfoSync, loadPackageJSON, loadPackageJSONSync } from "local-pkg";
12
10
  import { pathToFileURL } from "node:url";
13
- import { build } from "esbuild";
14
11
  import JSON5 from "json5";
15
- import { pathToRegexp } from "path-to-regexp";
16
- import cors from "cors";
17
12
  import EventEmitter from "node:events";
18
- import chokidar from "chokidar";
13
+ import { watch } from "chokidar";
14
+ import { glob } from "tinyglobby";
15
+ import isCore from "is-core-module";
16
+ import cors from "cors";
19
17
 
20
- //#region src/core/compiler.ts
18
+ //#region src/compiler/esbuild.ts
21
19
  const externalizeDeps = {
22
20
  name: "externalize-deps",
23
- setup(build$1) {
24
- build$1.onResolve({ filter: /.*/ }, ({ path: id }) => {
21
+ setup(build) {
22
+ build.onResolve({ filter: /.*/ }, ({ path: id }) => {
25
23
  if (id[0] !== "." && !path.isAbsolute(id)) return { external: true };
26
24
  });
27
25
  }
28
26
  };
29
27
  const json5Loader = {
30
28
  name: "json5-loader",
31
- setup(build$1) {
32
- build$1.onLoad({ filter: /\.json5$/ }, async ({ path: path$1 }) => {
33
- const content = await promises.readFile(path$1, "utf-8");
29
+ setup(build) {
30
+ build.onLoad({ filter: /\.json5$/ }, async ({ path: path$1 }) => {
31
+ const content = await fsp.readFile(path$1, "utf-8");
34
32
  return {
35
33
  contents: `export default ${JSON.stringify(JSON5.parse(content))}`,
36
34
  loader: "js"
@@ -40,9 +38,9 @@ const json5Loader = {
40
38
  };
41
39
  const jsonLoader = {
42
40
  name: "json-loader",
43
- setup(build$1) {
44
- build$1.onLoad({ filter: /\.json$/ }, async ({ path: path$1 }) => {
45
- const content = await promises.readFile(path$1, "utf-8");
41
+ setup(build) {
42
+ build.onLoad({ filter: /\.json$/ }, async ({ path: path$1 }) => {
43
+ const content = await fsp.readFile(path$1, "utf-8");
46
44
  return {
47
45
  contents: `export default ${content}`,
48
46
  loader: "js"
@@ -50,10 +48,10 @@ const jsonLoader = {
50
48
  });
51
49
  }
52
50
  };
53
- const renamePlugin = {
51
+ const renamePlugin$1 = {
54
52
  name: "rename-plugin",
55
- setup(build$1) {
56
- build$1.onResolve({ filter: /.*/ }, ({ path: id }) => {
53
+ setup(build) {
54
+ build.onResolve({ filter: /.*/ }, ({ path: id }) => {
57
55
  if (id === "vite-plugin-mock-dev-server") return {
58
56
  path: "vite-plugin-mock-dev-server/helper",
59
57
  external: true
@@ -65,12 +63,12 @@ const renamePlugin = {
65
63
  function aliasPlugin(alias) {
66
64
  return {
67
65
  name: "alias-plugin",
68
- setup(build$1) {
69
- build$1.onResolve({ filter: /.*/ }, async ({ path: id }) => {
66
+ setup(build) {
67
+ build.onResolve({ filter: /.*/ }, async ({ path: id }) => {
70
68
  const matchedEntry = alias.find(({ find: find$1 }) => aliasMatches(find$1, id));
71
69
  if (!matchedEntry) return null;
72
70
  const { find, replacement } = matchedEntry;
73
- const result = await build$1.resolve(id.replace(find, replacement), {
71
+ const result = await build.resolve(id.replace(find, replacement), {
74
72
  kind: "import-statement",
75
73
  resolveDir: replacement,
76
74
  namespace: "file"
@@ -89,12 +87,17 @@ function aliasMatches(pattern, importee) {
89
87
  if (importee === pattern) return true;
90
88
  return importee.startsWith(`${pattern}/`);
91
89
  }
92
- async function transformWithEsbuild(entryPoint, options) {
93
- const { isESM = true, define, alias, cwd = process.cwd() } = options;
90
+ let _build = null;
91
+ async function esbuild() {
92
+ _build ||= (await import("esbuild")).build;
93
+ return _build;
94
+ }
95
+ async function transformWithEsbuild(entryPoint, { isESM = true, define, alias, cwd = process.cwd() }) {
94
96
  const filepath = path.resolve(cwd, entryPoint);
95
97
  const filename = path.basename(entryPoint);
96
98
  const dirname = path.dirname(filepath);
97
99
  try {
100
+ const build = await esbuild();
98
101
  const result = await build({
99
102
  entryPoints: [entryPoint],
100
103
  outfile: "out.js",
@@ -112,25 +115,31 @@ async function transformWithEsbuild(entryPoint, options) {
112
115
  },
113
116
  plugins: [
114
117
  aliasPlugin(alias),
115
- renamePlugin,
118
+ renamePlugin$1,
116
119
  externalizeDeps,
117
120
  jsonLoader,
118
121
  json5Loader
119
122
  ],
120
123
  absWorkingDir: cwd
121
124
  });
125
+ const deps = /* @__PURE__ */ new Set();
126
+ const inputs = result.metafile?.inputs || {};
127
+ Object.keys(inputs).forEach((key) => inputs[key].imports.forEach((dep) => deps.add(dep.path)));
122
128
  return {
123
129
  code: result.outputFiles[0].text,
124
- deps: result.metafile?.inputs || {}
130
+ deps: Array.from(deps)
125
131
  };
126
132
  } catch (e) {
127
133
  console.error(e);
128
134
  }
129
135
  return {
130
136
  code: "",
131
- deps: {}
137
+ deps: []
132
138
  };
133
139
  }
140
+
141
+ //#endregion
142
+ //#region src/compiler/loadFromCode.ts
134
143
  async function loadFromCode({ filepath, code, isESM, cwd }) {
135
144
  filepath = path.resolve(cwd, filepath);
136
145
  const ext = isESM ? ".mjs" : ".cjs";
@@ -148,223 +157,201 @@ async function loadFromCode({ filepath, code, isESM, cwd }) {
148
157
  }
149
158
 
150
159
  //#endregion
151
- //#region src/core/build.ts
152
- async function generateMockServer(ctx, options) {
153
- const include = toArray(options.include);
154
- const exclude = toArray(options.exclude);
155
- const cwd = options.cwd || process.cwd();
156
- let pkg = {};
157
- try {
158
- const pkgStr = lookupFile(options.context, ["package.json"]);
159
- if (pkgStr) pkg = JSON.parse(pkgStr);
160
- } catch {}
161
- const outputDir = options.build.dist;
162
- const content = await generateMockEntryCode(cwd, include, exclude);
163
- const mockEntry = path.join(cwd, `mock-data-${Date.now()}.js`);
164
- await fsp.writeFile(mockEntry, content, "utf-8");
165
- const { code, deps } = await transformWithEsbuild(mockEntry, options);
166
- const mockDeps = getMockDependencies(deps, options.alias);
167
- await fsp.unlink(mockEntry);
168
- const outputList = [
169
- {
170
- filename: path.join(outputDir, "mock-data.js"),
171
- source: code
172
- },
173
- {
174
- filename: path.join(outputDir, "index.js"),
175
- source: generatorServerEntryCode(options)
176
- },
177
- {
178
- filename: path.join(outputDir, "package.json"),
179
- source: generatePackageJson(pkg, mockDeps)
160
+ //#region src/compiler/rolldown.ts
161
+ const renamePlugin = {
162
+ name: "vite-mock:rename-plugin",
163
+ resolveId(id) {
164
+ if (id === "vite-plugin-mock-dev-server") return {
165
+ id: "vite-plugin-mock-dev-server/helper",
166
+ external: true
167
+ };
168
+ }
169
+ };
170
+ const json5Plugin = {
171
+ name: "vite-mock:json5-plugin",
172
+ transform: {
173
+ filter: { id: /\.json5$/ },
174
+ handler: (code) => {
175
+ return { code: `export default ${JSON5.stringify(JSON5.parse(code))}` };
180
176
  }
181
- ];
177
+ }
178
+ };
179
+ let _rolldown = null;
180
+ async function rolldown() {
181
+ _rolldown ||= {
182
+ build: (await import("rolldown")).build,
183
+ aliasPlugin: (await import("rolldown/experimental")).aliasPlugin
184
+ };
185
+ return _rolldown;
186
+ }
187
+ async function transformWithRolldown(entryPoint, { isESM = true, define, alias, cwd = process.cwd() }) {
188
+ const filepath = path.resolve(cwd, entryPoint);
189
+ const filename = path.basename(entryPoint);
190
+ const dirname = path.dirname(filepath);
191
+ const isAlias = (p) => !!alias.find(({ find }) => aliasMatches(find, p));
182
192
  try {
183
- if (path.isAbsolute(outputDir)) {
184
- for (const { filename } of outputList) if (fs.existsSync(filename)) await fsp.rm(filename);
185
- options.logger.info(`${pc.green("✓")} generate mock server in ${pc.cyan(outputDir)}`);
186
- for (const { filename, source } of outputList) {
187
- fs.mkdirSync(path.dirname(filename), { recursive: true });
188
- await fsp.writeFile(filename, source, "utf-8");
189
- const sourceSize = (source.length / 1024).toFixed(2);
190
- const name = path.relative(outputDir, filename);
191
- const space = name.length < 30 ? " ".repeat(30 - name.length) : "";
192
- options.logger.info(` ${pc.green(name)}${space}${pc.bold(pc.dim(`${sourceSize} kB`))}`);
193
- }
194
- } else for (const { filename, source } of outputList) ctx.emitFile({
195
- type: "asset",
196
- fileName: filename,
197
- source
193
+ const { build, aliasPlugin: aliasPlugin$1 } = await rolldown();
194
+ const result = await build({
195
+ input: entryPoint,
196
+ write: false,
197
+ cwd,
198
+ output: {
199
+ format: isESM ? "esm" : "cjs",
200
+ sourcemap: false,
201
+ file: "out.js"
202
+ },
203
+ platform: "node",
204
+ define: {
205
+ ...define,
206
+ __dirname: JSON.stringify(dirname),
207
+ __filename: JSON.stringify(filename),
208
+ ...isESM ? {} : { "import.meta.url": JSON.stringify(pathToFileURL(filepath)) }
209
+ },
210
+ external(id) {
211
+ if (isAlias(id)) return false;
212
+ if (id[0] !== "." && !path.isAbsolute(id) && id !== "vite-plugin-mock-dev-server") return true;
213
+ },
214
+ plugins: [
215
+ aliasPlugin$1({ entries: alias }),
216
+ renamePlugin,
217
+ json5Plugin
218
+ ]
198
219
  });
220
+ return {
221
+ code: result.output[0].code,
222
+ deps: result.output[0].imports
223
+ };
199
224
  } catch (e) {
200
225
  console.error(e);
201
226
  }
202
- }
203
- function getMockDependencies(deps, alias) {
204
- const list = /* @__PURE__ */ new Set();
205
- const excludeDeps = [
206
- "vite-plugin-mock-dev-server",
207
- "connect",
208
- "cors"
209
- ];
210
- const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
211
- Object.keys(deps).forEach((mPath) => {
212
- const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
213
- imports.forEach((dep) => {
214
- const name = normalizePackageName(dep);
215
- if (!excludeDeps.includes(name) && !isCore(name)) list.add(name);
216
- });
217
- });
218
- return Array.from(list);
219
- }
220
- function normalizePackageName(dep) {
221
- const [scope, name] = dep.split("/");
222
- if (scope[0] === "@") return `${scope}/${name}`;
223
- return scope;
224
- }
225
- function generatePackageJson(pkg, mockDeps) {
226
- const { dependencies = {}, devDependencies = {} } = pkg;
227
- const dependents = {
228
- ...dependencies,
229
- ...devDependencies
230
- };
231
- const mockPkg = {
232
- name: "mock-server",
233
- type: "module",
234
- scripts: { start: "node index.js" },
235
- dependencies: {
236
- connect: "^3.7.0",
237
- ["vite-plugin-mock-dev-server"]: `^1.9.2`,
238
- cors: "^2.8.5"
239
- },
240
- pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
227
+ return {
228
+ code: "",
229
+ deps: []
241
230
  };
242
- mockDeps.forEach((dep) => {
243
- mockPkg.dependencies[dep] = dependents[dep] || "latest";
244
- });
245
- return JSON.stringify(mockPkg, null, 2);
246
231
  }
247
- function generatorServerEntryCode({ proxies, wsProxies, cookiesOptions, bodyParserOptions, priority, build: build$1 }) {
248
- const { serverPort, log } = build$1;
249
- return `import { createServer } from 'node:http';
250
- import connect from 'connect';
251
- import corsMiddleware from 'cors';
252
- import { baseMiddleware, createLogger, mockWebSocket } from 'vite-plugin-mock-dev-server/server';
253
- import mockData from './mock-data.js';
254
-
255
- const app = connect();
256
- const server = createServer(app);
257
- const logger = createLogger('mock-server', '${log}');
258
- const proxies = ${JSON.stringify(proxies)};
259
- const wsProxies = ${JSON.stringify(wsProxies)};
260
- const cookiesOptions = ${JSON.stringify(cookiesOptions)};
261
- const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
262
- const priority = ${JSON.stringify(priority)};
263
- const compiler = { mockData }
264
-
265
- mockWebSocket(compiler, server, { wsProxies, cookiesOptions, logger });
266
-
267
- app.use(corsMiddleware());
268
- app.use(baseMiddleware(compiler, {
269
- formidableOptions: { multiples: true },
270
- proxies,
271
- priority,
272
- cookiesOptions,
273
- bodyParserOptions,
274
- logger,
275
- }));
276
232
 
277
- server.listen(${serverPort});
278
-
279
- console.log('listen: http://localhost:${serverPort}');
280
- `;
233
+ //#endregion
234
+ //#region src/compiler/compile.ts
235
+ async function transform(entryPoint, options) {
236
+ if (await isPackageExists("rolldown")) return transformWithRolldown(entryPoint, options);
237
+ if (await isPackageExists("esbuild")) return transformWithEsbuild(entryPoint, options);
238
+ throw new Error("rolldown or esbuild not found");
281
239
  }
282
- async function generateMockEntryCode(cwd, include, exclude) {
283
- const includePaths = await fg(include, { cwd });
284
- const includeFilter = createFilter(include, exclude, { resolve: false });
285
- const mockFiles = includePaths.filter(includeFilter);
286
- let importers = "";
287
- const exporters = [];
288
- mockFiles.forEach((filepath, index) => {
289
- const file = normalizePath(path.join(cwd, filepath));
290
- importers += `import * as m${index} from '${file}';\n`;
291
- exporters.push(`[m${index}, '${filepath}']`);
240
+ async function compile(filepath, options) {
241
+ let isESM = false;
242
+ if (/\.m[jt]s$/.test(filepath)) isESM = true;
243
+ else if (/\.c[jt]s$/.test(filepath)) isESM = false;
244
+ else isESM = options.isESM || false;
245
+ const { code, deps } = await transform(filepath, {
246
+ ...options,
247
+ isESM
292
248
  });
293
- return `import { transformMockData, transformRawData } from 'vite-plugin-mock-dev-server/server';
294
- ${importers}
295
- const exporters = [\n ${exporters.join(",\n ")}\n];
296
- const mockList = exporters.map(([mod, filepath]) => {
297
- const raw = mod.default || mod;
298
- return transformRawData(raw, filepath);
299
- });
300
- export default transformMockData(mockList);`;
249
+ const data = await loadFromCode({
250
+ filepath,
251
+ code,
252
+ isESM,
253
+ cwd: options.cwd || process.cwd()
254
+ }) || {};
255
+ return {
256
+ data,
257
+ deps
258
+ };
301
259
  }
302
260
 
303
261
  //#endregion
304
- //#region src/core/mockCompiler.ts
305
- function createMockCompiler(options) {
306
- return new MockCompiler(options);
307
- }
262
+ //#region src/compiler/compiler.ts
308
263
  /**
309
- * mock配置加载器
264
+ * Mock 文件加载编译,并转换为 Mock 数据
310
265
  */
311
- var MockCompiler = class extends EventEmitter {
266
+ var Compiler = class extends EventEmitter {
312
267
  moduleCache = /* @__PURE__ */ new Map();
313
268
  moduleDeps = /* @__PURE__ */ new Map();
314
269
  cwd;
315
270
  mockWatcher;
316
271
  depsWatcher;
317
- moduleType = "cjs";
272
+ isESM = false;
318
273
  _mockData = {};
319
274
  constructor(options) {
320
275
  super();
321
276
  this.options = options;
322
277
  this.cwd = options.cwd || process.cwd();
323
278
  try {
324
- const pkg = lookupFile(this.cwd, ["package.json"]);
325
- this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
279
+ const pkg = loadPackageJSONSync(this.cwd);
280
+ this.isESM = pkg?.type === "module";
326
281
  } catch {}
327
282
  }
328
283
  get mockData() {
329
284
  return this._mockData;
330
285
  }
331
- run(watch) {
286
+ run(watch$1) {
332
287
  const { include, exclude } = this.options;
333
- /**
334
- * 使用 rollup 提供的 include/exclude 规则,
335
- * 过滤包含文件
336
- */
337
- const includeFilter = createFilter(include, exclude, { resolve: false });
338
- fg(include, { cwd: this.cwd }).then((files) => files.filter(includeFilter).map((file) => () => this.loadMock(file))).then((loadList) => promiseParallel(loadList, 10)).then(() => this.updateMockList());
339
- if (!watch) return;
340
- this.watchMockEntry();
288
+ const { pattern, ignore, isMatch } = createMatcher(include, exclude);
289
+ glob(pattern, {
290
+ ignore,
291
+ cwd: path.join(this.cwd, this.options.dir)
292
+ }).then((files) => files.map((file) => () => this.load(path.join(this.options.dir, file)))).then((loaders) => promiseParallel(loaders, 64)).then(() => this.updateMockData());
293
+ if (!watch$1) return;
294
+ this.watchMockEntry(isMatch);
341
295
  this.watchDeps();
342
296
  let timer = null;
343
297
  this.on("mock:update", async (filepath) => {
344
- if (!includeFilter(filepath)) return;
345
- await this.loadMock(filepath);
298
+ if (!isMatch(filepath)) return;
299
+ await this.load(filepath);
346
300
  if (timer) clearImmediate(timer);
347
301
  timer = setImmediate(() => {
348
- this.updateMockList();
349
- this.emit("mock:update-end", filepath);
302
+ this.updateMockData();
303
+ this.emit("mock:update-end", normalizePath(filepath));
350
304
  timer = null;
351
305
  });
352
306
  });
353
307
  this.on("mock:unlink", async (filepath) => {
354
- if (!includeFilter(filepath)) return;
308
+ if (!isMatch(filepath)) return;
309
+ filepath = normalizePath(path.join(this.options.dir, filepath));
355
310
  this.moduleCache.delete(filepath);
356
- this.updateMockList();
311
+ this.updateMockData();
357
312
  this.emit("mock:update-end", filepath);
358
313
  });
359
314
  }
360
- watchMockEntry() {
361
- const { include } = this.options;
362
- const [firstGlob, ...otherGlob] = toArray(include);
363
- const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
315
+ close() {
316
+ this.mockWatcher?.close();
317
+ this.depsWatcher?.close();
318
+ }
319
+ async load(filepath) {
320
+ if (!filepath) return;
321
+ try {
322
+ const { define, alias } = this.options;
323
+ const { data, deps } = await compile(filepath, {
324
+ cwd: this.cwd,
325
+ isESM: this.isESM,
326
+ define,
327
+ alias
328
+ });
329
+ this.moduleCache.set(filepath, processRawData(data, filepath));
330
+ this.updateModuleDeps(filepath, deps);
331
+ } catch (e) {
332
+ console.error(e);
333
+ }
334
+ }
335
+ updateMockData() {
336
+ this._mockData = processMockData(this.moduleCache);
337
+ }
338
+ updateModuleDeps(filepath, deps) {
339
+ for (const dep of deps) {
340
+ if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
341
+ const cur = this.moduleDeps.get(dep);
342
+ cur.add(filepath);
343
+ }
344
+ this.emit("update:deps");
345
+ }
346
+ watchMockEntry(isMatch) {
347
+ const watcher = this.mockWatcher = watch(this.options.dir, {
364
348
  ignoreInitial: true,
365
- cwd: this.cwd
349
+ cwd: this.cwd,
350
+ ignored: (filepath, stats) => {
351
+ if (filepath.includes("node_modules")) return true;
352
+ return !!stats?.isFile() && !isMatch(filepath);
353
+ }
366
354
  });
367
- if (otherGlob.length > 0) otherGlob.forEach((glob) => watcher.add(glob));
368
355
  watcher.on("add", async (filepath) => {
369
356
  filepath = normalizePath(filepath);
370
357
  this.emit("mock:update", filepath);
@@ -381,131 +368,212 @@ var MockCompiler = class extends EventEmitter {
381
368
  debug("watcher:unlink", filepath);
382
369
  });
383
370
  }
384
- /**
385
- * 监听 mock文件依赖的本地文件变动,
386
- * mock依赖文件更新,mock文件也一并更新
387
- */
388
371
  watchDeps() {
389
- const oldDeps = [];
390
- this.depsWatcher = chokidar.watch([], {
372
+ let oldDeps = [...this.moduleDeps.keys()];
373
+ const watcher = this.depsWatcher = watch([...oldDeps], {
391
374
  ignoreInitial: true,
392
375
  cwd: this.cwd
393
376
  });
394
- this.depsWatcher.on("change", (filepath) => {
377
+ watcher.on("change", (filepath) => {
395
378
  filepath = normalizePath(filepath);
396
379
  const mockFiles = this.moduleDeps.get(filepath);
397
- mockFiles?.forEach((file) => {
398
- this.emit("mock:update", file);
399
- });
380
+ mockFiles?.forEach((file) => this.emit("mock:update", file));
400
381
  });
401
- this.depsWatcher.on("unlink", (filepath) => {
382
+ watcher.on("unlink", (filepath) => {
402
383
  filepath = normalizePath(filepath);
403
384
  this.moduleDeps.delete(filepath);
404
385
  });
405
386
  this.on("update:deps", () => {
406
- const deps = [];
407
- for (const [dep] of this.moduleDeps.entries()) deps.push(dep);
387
+ const deps = [...this.moduleDeps.keys()];
408
388
  const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
409
- if (exactDeps.length > 0) this.depsWatcher.add(exactDeps);
389
+ oldDeps = deps;
390
+ if (exactDeps.length > 0) watcher.add(exactDeps);
410
391
  });
411
392
  }
412
- close() {
413
- this.mockWatcher?.close();
414
- this.depsWatcher?.close();
415
- }
416
- updateMockList() {
417
- this._mockData = transformMockData(this.moduleCache);
418
- }
419
- updateModuleDeps(filepath, deps) {
420
- Object.keys(deps).forEach((mPath) => {
421
- const imports = deps[mPath].imports.map((_) => _.path);
422
- imports.forEach((dep) => {
423
- if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
424
- const cur = this.moduleDeps.get(dep);
425
- cur.add(filepath);
426
- });
427
- });
428
- this.emit("update:deps");
429
- }
430
- async loadMock(filepath) {
431
- if (!filepath) return;
432
- let isESM = false;
433
- if (/\.m[jt]s$/.test(filepath)) isESM = true;
434
- else if (/\.c[jt]s$/.test(filepath)) isESM = false;
435
- else isESM = this.moduleType === "esm";
436
- const { define, alias } = this.options;
437
- const { code, deps } = await transformWithEsbuild(filepath, {
438
- isESM,
439
- define,
440
- alias,
441
- cwd: this.cwd
442
- });
443
- try {
444
- const raw = await loadFromCode({
445
- filepath,
446
- code,
447
- isESM,
448
- cwd: this.cwd
449
- }) || {};
450
- this.moduleCache.set(filepath, transformRawData(raw, filepath));
451
- this.updateModuleDeps(filepath, deps);
452
- } catch (e) {
453
- console.error(e);
454
- }
455
- }
456
393
  };
457
394
 
458
395
  //#endregion
459
- //#region src/core/mockMiddleware.ts
460
- function mockServerMiddleware(options, server, ws) {
461
- /**
462
- * 加载 mock 文件, 包括监听 mock 文件的依赖文件变化,
463
- * 并注入 vite `define` / `alias`
464
- */
465
- const compiler = createMockCompiler(options);
466
- compiler.run(!!server);
467
- /**
468
- * 监听 mock 文件是否发生变更,如何配置了 reload 为 true,
469
- * 当发生变更时,通知当前页面进行重新加载
470
- */
471
- compiler.on("mock:update-end", () => {
472
- if (options.reload) ws?.send({ type: "full-reload" });
396
+ //#region src/build/mockEntryCode.ts
397
+ async function generateMockEntryCode(cwd, dir, include, exclude) {
398
+ const { pattern, ignore } = createMatcher(include, exclude);
399
+ const mockFiles = await glob(pattern, {
400
+ ignore,
401
+ cwd: path.join(cwd, dir)
473
402
  });
474
- server?.on("close", () => compiler.close());
475
- /**
476
- * 虽然 config.server.proxy 中有关于 ws 的代理配置,
477
- * 但是由于 vite 内部在启动时,直接对 ws相关的请求,通过 upgrade 事件,发送给 http-proxy
478
- * ws 代理方法。如果插件直接使用 config.server.proxy 中的 ws 配置,
479
- * 就会导致两次 upgrade 事件 对 wss 实例的冲突。
480
- * 由于 vite 内部并没有提供其他的方式跳过 内部 upgrade 的方式,(个人认为也没有必要提供此类方式)
481
- * 所以插件选择了通过插件的配置项 `wsPrefix` 来做 判断的首要条件。
482
- * 当前插件默认会将已配置在 wsPrefix 的值,从 config.server.proxy 的删除,避免发生冲突问题。
483
- */
484
- mockWebSocket(compiler, server, options);
485
- const middlewares = [];
486
- middlewares.push(
487
- /**
488
- * 在 vite 的开发服务中,由于插件 的 enforce 为 `pre`,
489
- * mock 中间件的执行顺序 早于 vite 内部的 cors 中间件执行,
490
- * 这导致了 vite 默认开启的 cors 对 mock 请求不生效。
491
- * 在一些比如 微前端项目、或者联合项目中,会由于端口不一致而导致跨域问题。
492
- * 所以在这里,使用 cors 中间件 来解决这个问题。
493
- *
494
- * 同时为了使 插件内的 cors 和 vite 的 cors 不产生冲突,并拥有一致的默认行为,
495
- * 也会使用 viteConfig.server.cors 配置,并支持 用户可以对 mock 中的 cors 中间件进行配置。
496
- * 而用户的配置也仅对 mock 的接口生效。
497
- */
498
- corsMiddleware(compiler, options),
499
- baseMiddleware(compiler, options)
500
- );
501
- return middlewares.filter(Boolean);
403
+ let importers = "";
404
+ const exporters = [];
405
+ mockFiles.forEach((filepath, index) => {
406
+ const file = normalizePath(path.join(cwd, dir, filepath));
407
+ importers += `import * as m${index} from '${file}';\n`;
408
+ exporters.push(`[m${index}, '${normalizePath(path.join(dir, filepath))}']`);
409
+ });
410
+ return `import { processMockData, processRawData } from 'vite-plugin-mock-dev-server/server';
411
+ ${importers}
412
+ const exporters = [\n ${exporters.join(",\n ")}\n];
413
+ const mockList = exporters.map(([mod, filepath]) => processRawData(mod.default || mod, filepath));
414
+ export default processMockData(mockList);`;
415
+ }
416
+
417
+ //#endregion
418
+ //#region package.json
419
+ var name = "vite-plugin-mock-dev-server";
420
+ var version = "2.0.1";
421
+
422
+ //#endregion
423
+ //#region src/build/packageJson.ts
424
+ /**
425
+ * mock 文件的 importers 中获取依赖
426
+ */
427
+ function getMockDependencies(deps, alias) {
428
+ const list = /* @__PURE__ */ new Set();
429
+ const excludeDeps = [
430
+ name,
431
+ "connect",
432
+ "cors"
433
+ ];
434
+ const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
435
+ deps.forEach((dep) => {
436
+ const name$1 = normalizePackageName(dep);
437
+ if (name$1.startsWith("<define:") || isAlias(name$1) || isCore(name$1)) return;
438
+ if (name$1[0] === "/" || name$1.startsWith("./") || name$1.startsWith("../")) return;
439
+ if (!excludeDeps.includes(name$1)) list.add(name$1);
440
+ });
441
+ return Array.from(list);
442
+ }
443
+ function normalizePackageName(dep) {
444
+ const [scope, name$1] = dep.split("/");
445
+ if (scope[0] === "@") return `${scope}/${name$1}`;
446
+ return scope;
502
447
  }
503
- function corsMiddleware(compiler, { proxies, cors: corsOptions }) {
448
+ function generatePackageJson(pkg, mockDeps) {
449
+ const { dependencies = {}, devDependencies = {} } = pkg;
450
+ const dependents = {
451
+ ...dependencies,
452
+ ...devDependencies
453
+ };
454
+ const mockPkg = {
455
+ name: "mock-server",
456
+ type: "module",
457
+ scripts: { start: "node index.js" },
458
+ dependencies: {
459
+ connect: "^3.7.0",
460
+ [name]: `^${version}`,
461
+ cors: "^2.8.5"
462
+ },
463
+ pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
464
+ };
465
+ const ignores = [
466
+ "catalog:",
467
+ "file:",
468
+ "workspace:"
469
+ ];
470
+ for (const dep of mockDeps) {
471
+ const version$1 = dependents[dep];
472
+ if (!version$1 || ignores.some((ignore) => version$1.startsWith(ignore))) {
473
+ const info = getPackageInfoSync(dep);
474
+ mockPkg.dependencies[dep] = info?.version ? `^${info.version}` : "latest";
475
+ } else mockPkg.dependencies[dep] = "latest";
476
+ }
477
+ return JSON.stringify(mockPkg, null, 2);
478
+ }
479
+
480
+ //#endregion
481
+ //#region src/build/serverEntryCode.ts
482
+ function generatorServerEntryCode({ proxies, wsProxies, cookiesOptions, bodyParserOptions, priority, build }) {
483
+ const { serverPort, log } = build;
484
+ return `import { createServer } from 'node:http';
485
+ import connect from 'connect';
486
+ import corsMiddleware from 'cors';
487
+ import { createMockMiddleware, createLogger, mockWebSocket } from 'vite-plugin-mock-dev-server/server';
488
+ import mockData from './mock-data.js';
489
+
490
+ const app = connect();
491
+ const server = createServer(app);
492
+ const logger = createLogger('mock-server', '${log}');
493
+ const proxies = ${JSON.stringify(proxies)};
494
+ const wsProxies = ${JSON.stringify(wsProxies)};
495
+ const cookiesOptions = ${JSON.stringify(cookiesOptions)};
496
+ const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
497
+ const priority = ${JSON.stringify(priority)};
498
+ const compiler = { mockData }
499
+
500
+ mockWebSocket(compiler, server, { wsProxies, cookiesOptions, logger });
501
+
502
+ app.use(corsMiddleware());
503
+ app.use(createMockMiddleware(compiler, {
504
+ formidableOptions: { multiples: true },
505
+ proxies,
506
+ priority,
507
+ cookiesOptions,
508
+ bodyParserOptions,
509
+ logger,
510
+ }));
511
+
512
+ server.listen(${serverPort});
513
+
514
+ console.log('listen: http://localhost:${serverPort}');
515
+ `;
516
+ }
517
+
518
+ //#endregion
519
+ //#region src/build/generate.ts
520
+ async function generateMockServer(ctx, options) {
521
+ const include = toArray(options.include);
522
+ const exclude = toArray(options.exclude);
523
+ const cwd = options.cwd || process.cwd();
524
+ const dir = options.dir;
525
+ const pkg = await loadPackageJSON(options.context) || {};
526
+ const outputDir = options.build.dist;
527
+ const content = await generateMockEntryCode(cwd, dir, include, exclude);
528
+ const mockEntry = path.join(cwd, `mock-data-${Date.now()}.js`);
529
+ await fsp.writeFile(mockEntry, content, "utf-8");
530
+ const { code, deps } = await transform(mockEntry, options);
531
+ const mockDeps = getMockDependencies(deps, options.alias);
532
+ await fsp.unlink(mockEntry);
533
+ const outputList = [
534
+ {
535
+ filename: path.join(outputDir, "mock-data.js"),
536
+ source: code
537
+ },
538
+ {
539
+ filename: path.join(outputDir, "index.js"),
540
+ source: generatorServerEntryCode(options)
541
+ },
542
+ {
543
+ filename: path.join(outputDir, "package.json"),
544
+ source: generatePackageJson(pkg, mockDeps)
545
+ }
546
+ ];
547
+ try {
548
+ if (path.isAbsolute(outputDir)) {
549
+ for (const { filename } of outputList) if (fs.existsSync(filename)) await fsp.rm(filename);
550
+ options.logger.info(`${ansis.green("✓")} generate mock server in ${ansis.cyan(outputDir)}`);
551
+ for (const { filename, source } of outputList) {
552
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
553
+ await fsp.writeFile(filename, source, "utf-8");
554
+ const sourceSize = (source.length / 1024).toFixed(2);
555
+ const name$1 = path.relative(outputDir, filename);
556
+ const space = name$1.length < 30 ? " ".repeat(30 - name$1.length) : "";
557
+ options.logger.info(` ${ansis.green(name$1)}${space}${ansis.bold.dim(`${sourceSize} kB`)}`);
558
+ }
559
+ } else for (const { filename, source } of outputList) ctx.emitFile({
560
+ type: "asset",
561
+ fileName: filename,
562
+ source
563
+ });
564
+ } catch (e) {
565
+ console.error(e);
566
+ }
567
+ }
568
+
569
+ //#endregion
570
+ //#region src/core/corsMiddleware.ts
571
+ function createCorsMiddleware(compiler, { proxies, cors: corsOptions }) {
504
572
  return !corsOptions ? void 0 : function(req, res, next) {
505
573
  const { pathname } = urlParse(req.url);
506
574
  if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) return next();
507
575
  const mockData = compiler.mockData;
508
- const mockUrl = Object.keys(mockData).find((key) => pathToRegexp(key).test(pathname));
576
+ const mockUrl = Object.keys(mockData).find((pattern) => isPathMatch(pattern, pathname));
509
577
  if (!mockUrl) return next();
510
578
  cors(corsOptions)(req, res, next);
511
579
  };
@@ -589,17 +657,59 @@ function canJsonParse(value) {
589
657
  }
590
658
 
591
659
  //#endregion
592
- //#region src/core/resolvePluginOptions.ts
593
- function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"], exclude = [
594
- "**/node_modules/**",
595
- "**/.vscode/**",
596
- "**/.git/**"
597
- ], reload = false, log = "info", cors: cors$1 = true, formidableOptions = {}, build: build$1 = false, cookiesOptions = {}, bodyParserOptions = {}, priority = {} }, config) {
660
+ //#region src/core/init.ts
661
+ function initMockMiddlewares(options, server, ws) {
662
+ /**
663
+ * 加载 mock 文件, 包括监听 mock 文件的依赖文件变化,
664
+ * 并注入 vite `define` / `alias`
665
+ */
666
+ const compiler = new Compiler(options);
667
+ compiler.run(!!server);
668
+ /**
669
+ * 监听 mock 文件是否发生变更,如何配置了 reload 为 true,
670
+ * 当发生变更时,通知当前页面进行重新加载
671
+ */
672
+ compiler.on("mock:update-end", () => {
673
+ if (options.reload) ws?.send({ type: "full-reload" });
674
+ });
675
+ server?.on("close", () => compiler.close());
676
+ /**
677
+ * 虽然 config.server.proxy 中有关于 ws 的代理配置,
678
+ * 但是由于 vite 内部在启动时,直接对 ws相关的请求,通过 upgrade 事件,发送给 http-proxy
679
+ * 的 ws 代理方法。如果插件直接使用 config.server.proxy 中的 ws 配置,
680
+ * 就会导致两次 upgrade 事件 对 wss 实例的冲突。
681
+ * 由于 vite 内部并没有提供其他的方式跳过 内部 upgrade 的方式,(个人认为也没有必要提供此类方式)
682
+ * 所以插件选择了通过插件的配置项 `wsPrefix` 来做 判断的首要条件。
683
+ * 当前插件默认会将已配置在 wsPrefix 的值,从 config.server.proxy 的删除,避免发生冲突问题。
684
+ */
685
+ mockWebSocket(compiler, server, options);
686
+ const middlewares = [];
687
+ middlewares.push(
688
+ /**
689
+ * 在 vite 的开发服务中,由于插件 的 enforce 为 `pre`,
690
+ * mock 中间件的执行顺序 早于 vite 内部的 cors 中间件执行,
691
+ * 这导致了 vite 默认开启的 cors 对 mock 请求不生效。
692
+ * 在一些比如 微前端项目、或者联合项目中,会由于端口不一致而导致跨域问题。
693
+ * 所以在这里,使用 cors 中间件 来解决这个问题。
694
+ *
695
+ * 同时为了使 插件内的 cors 和 vite 的 cors 不产生冲突,并拥有一致的默认行为,
696
+ * 也会使用 viteConfig.server.cors 配置,并支持 用户可以对 mock 中的 cors 中间件进行配置。
697
+ * 而用户的配置也仅对 mock 的接口生效。
698
+ */
699
+ createCorsMiddleware(compiler, options),
700
+ createMockMiddleware(compiler, options)
701
+ );
702
+ return middlewares.filter(Boolean);
703
+ }
704
+
705
+ //#endregion
706
+ //#region src/options.ts
707
+ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, dir = "mock", include = ["**/*.mock.{js,ts,cjs,mjs,json,json5}"], exclude = [], reload = false, log = "info", cors: cors$1 = true, formidableOptions = {}, build = false, cookiesOptions = {}, bodyParserOptions = {}, priority = {} }, config) {
598
708
  const logger = createLogger("vite:mock", isBoolean(log) ? log ? "info" : "error" : log);
599
709
  const { httpProxies } = ensureProxies(config.server.proxy || {});
600
710
  const proxies = uniq([...toArray(prefix), ...httpProxies]);
601
711
  const wsProxies = toArray(wsPrefix);
602
- if (!proxies.length && !wsProxies.length) logger.warn(`No proxy was configured, mock server will not work. See ${pc.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
712
+ if (!proxies.length && !wsProxies.length) logger.warn(`No proxy was configured, mock server will not work. See ${ansis.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
603
713
  const enabled = cors$1 === false ? false : config.server.cors !== false;
604
714
  let corsOptions = {};
605
715
  if (enabled && config.server.cors !== false) corsOptions = {
@@ -621,6 +731,7 @@ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["moc
621
731
  });
622
732
  return {
623
733
  cwd: cwd || process.cwd(),
734
+ dir,
624
735
  include,
625
736
  exclude,
626
737
  context: config.root,
@@ -634,11 +745,12 @@ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["moc
634
745
  },
635
746
  bodyParserOptions,
636
747
  priority,
637
- build: build$1 ? Object.assign({
748
+ build: build ? {
638
749
  serverPort: 8080,
639
750
  dist: "mockServer",
640
- log: "error"
641
- }, typeof build$1 === "object" ? build$1 : {}) : false,
751
+ log: "error",
752
+ ...typeof build === "object" ? build : {}
753
+ } : false,
642
754
  proxies,
643
755
  wsProxies,
644
756
  logger,
@@ -646,6 +758,19 @@ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["moc
646
758
  define: viteDefine(config)
647
759
  };
648
760
  }
761
+ function ensureProxies(serverProxy = {}) {
762
+ const httpProxies = [];
763
+ const wsProxies = [];
764
+ Object.keys(serverProxy).forEach((key) => {
765
+ const value = serverProxy[key];
766
+ if (typeof value === "string" || !value.ws && !value.target?.toString().startsWith("ws:") && !value.target?.toString().startsWith("wss:")) httpProxies.push(key);
767
+ else wsProxies.push(key);
768
+ });
769
+ return {
770
+ httpProxies,
771
+ wsProxies
772
+ };
773
+ }
649
774
 
650
775
  //#endregion
651
776
  //#region src/plugin.ts
@@ -694,25 +819,15 @@ function serverPlugin(options) {
694
819
  config.logger.warn("");
695
820
  },
696
821
  configureServer({ middlewares, httpServer, ws }) {
697
- const middlewareList = mockServerMiddleware(resolvedOptions, httpServer, ws);
822
+ const middlewareList = initMockMiddlewares(resolvedOptions, httpServer, ws);
698
823
  middlewareList.forEach((middleware) => middlewares.use(middleware));
699
824
  },
700
825
  configurePreviewServer({ middlewares, httpServer }) {
701
- const middlewareList = mockServerMiddleware(resolvedOptions, httpServer);
826
+ const middlewareList = initMockMiddlewares(resolvedOptions, httpServer);
702
827
  middlewareList.forEach((middleware) => middlewares.use(middleware));
703
828
  }
704
829
  };
705
830
  }
706
831
 
707
832
  //#endregion
708
- //#region src/index.ts
709
- /**
710
- * @deprecated use named export instead
711
- */
712
- function mockDevServerPluginWithDefaultExportWasDeprecated(options = {}) {
713
- console.warn(`${pc.yellow("[vite-plugin-mock-dev-server]")} ${pc.yellow(pc.bold("WARNING:"))} The plugin default export is ${pc.bold("deprecated")}, it will be removed in next major version, use ${pc.bold("named export")} instead:\n\n ${pc.green("import { mockDevServerPlugin } from \"vite-plugin-mock-dev-server\"")}\n`);
714
- return mockDevServerPlugin(options);
715
- }
716
-
717
- //#endregion
718
- export { baseMiddleware, createDefineMock, createLogger, createSSEStream, mockDevServerPluginWithDefaultExportWasDeprecated as default, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData, transformRawData };
833
+ export { createDefineMock, createLogger, createMockMiddleware, createSSEStream, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, processMockData, processRawData, sortByValidator };