vite-plugin-mock-dev-server 1.9.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,730 +0,0 @@
1
- Object.defineProperty(exports, '__esModule', { value: true });
2
- const require_dist = require('./dist-DrfpZ4UT.cjs');
3
- const require_helper = require('./helper-CCVedLL0.cjs');
4
- const require_server = require('./server-BwOfV_62.cjs');
5
- const picocolors = require_dist.__toESM(require("picocolors"));
6
- const node_fs = require_dist.__toESM(require("node:fs"));
7
- const node_fs_promises = require_dist.__toESM(require("node:fs/promises"));
8
- const node_path = require_dist.__toESM(require("node:path"));
9
- const node_process = require_dist.__toESM(require("node:process"));
10
- const __rollup_pluginutils = require_dist.__toESM(require("@rollup/pluginutils"));
11
- const fast_glob = require_dist.__toESM(require("fast-glob"));
12
- const is_core_module = require_dist.__toESM(require("is-core-module"));
13
- const node_url = require_dist.__toESM(require("node:url"));
14
- const esbuild = require_dist.__toESM(require("esbuild"));
15
- const json5 = require_dist.__toESM(require("json5"));
16
- const path_to_regexp = require_dist.__toESM(require("path-to-regexp"));
17
- const cors = require_dist.__toESM(require("cors"));
18
- const node_events = require_dist.__toESM(require("node:events"));
19
- const chokidar = require_dist.__toESM(require("chokidar"));
20
-
21
- //#region src/core/compiler.ts
22
- const externalizeDeps = {
23
- name: "externalize-deps",
24
- setup(build$1) {
25
- build$1.onResolve({ filter: /.*/ }, ({ path: id }) => {
26
- if (id[0] !== "." && !node_path.default.isAbsolute(id)) return { external: true };
27
- });
28
- }
29
- };
30
- const json5Loader = {
31
- name: "json5-loader",
32
- setup(build$1) {
33
- build$1.onLoad({ filter: /\.json5$/ }, async ({ path: path$2 }) => {
34
- const content = await node_fs.promises.readFile(path$2, "utf-8");
35
- return {
36
- contents: `export default ${JSON.stringify(json5.default.parse(content))}`,
37
- loader: "js"
38
- };
39
- });
40
- }
41
- };
42
- const jsonLoader = {
43
- name: "json-loader",
44
- setup(build$1) {
45
- build$1.onLoad({ filter: /\.json$/ }, async ({ path: path$2 }) => {
46
- const content = await node_fs.promises.readFile(path$2, "utf-8");
47
- return {
48
- contents: `export default ${content}`,
49
- loader: "js"
50
- };
51
- });
52
- }
53
- };
54
- const renamePlugin = {
55
- name: "rename-plugin",
56
- setup(build$1) {
57
- build$1.onResolve({ filter: /.*/ }, ({ path: id }) => {
58
- if (id === "vite-plugin-mock-dev-server") return {
59
- path: "vite-plugin-mock-dev-server/helper",
60
- external: true
61
- };
62
- return null;
63
- });
64
- }
65
- };
66
- function aliasPlugin(alias) {
67
- return {
68
- name: "alias-plugin",
69
- setup(build$1) {
70
- build$1.onResolve({ filter: /.*/ }, async ({ path: id }) => {
71
- const matchedEntry = alias.find(({ find: find$1 }) => aliasMatches(find$1, id));
72
- if (!matchedEntry) return null;
73
- const { find, replacement } = matchedEntry;
74
- const result = await build$1.resolve(id.replace(find, replacement), {
75
- kind: "import-statement",
76
- resolveDir: replacement,
77
- namespace: "file"
78
- });
79
- return {
80
- path: result.path,
81
- external: false
82
- };
83
- });
84
- }
85
- };
86
- }
87
- function aliasMatches(pattern, importee) {
88
- if (pattern instanceof RegExp) return pattern.test(importee);
89
- if (importee.length < pattern.length) return false;
90
- if (importee === pattern) return true;
91
- return importee.startsWith(`${pattern}/`);
92
- }
93
- async function transformWithEsbuild(entryPoint, options) {
94
- const { isESM = true, define, alias, cwd = node_process.default.cwd() } = options;
95
- const filepath = node_path.default.resolve(cwd, entryPoint);
96
- const filename = node_path.default.basename(entryPoint);
97
- const dirname = node_path.default.dirname(filepath);
98
- try {
99
- const result = await (0, esbuild.build)({
100
- entryPoints: [entryPoint],
101
- outfile: "out.js",
102
- write: false,
103
- target: ["node18"],
104
- platform: "node",
105
- bundle: true,
106
- metafile: true,
107
- format: isESM ? "esm" : "cjs",
108
- define: {
109
- ...define,
110
- __dirname: JSON.stringify(dirname),
111
- __filename: JSON.stringify(filename),
112
- ...isESM ? {} : { "import.meta.url": JSON.stringify((0, node_url.pathToFileURL)(filepath)) }
113
- },
114
- plugins: [
115
- aliasPlugin(alias),
116
- renamePlugin,
117
- externalizeDeps,
118
- jsonLoader,
119
- json5Loader
120
- ],
121
- absWorkingDir: cwd
122
- });
123
- return {
124
- code: result.outputFiles[0].text,
125
- deps: result.metafile?.inputs || {}
126
- };
127
- } catch (e) {
128
- console.error(e);
129
- }
130
- return {
131
- code: "",
132
- deps: {}
133
- };
134
- }
135
- async function loadFromCode({ filepath, code, isESM, cwd }) {
136
- filepath = node_path.default.resolve(cwd, filepath);
137
- const ext = isESM ? ".mjs" : ".cjs";
138
- const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
139
- const file = (0, node_url.pathToFileURL)(filepathTmp).toString();
140
- await node_fs.promises.writeFile(filepathTmp, code, "utf8");
141
- try {
142
- const mod = await import(file);
143
- return mod.default || mod;
144
- } finally {
145
- try {
146
- node_fs.default.unlinkSync(filepathTmp);
147
- } catch {}
148
- }
149
- }
150
-
151
- //#endregion
152
- //#region src/core/build.ts
153
- async function generateMockServer(ctx, options) {
154
- const include = require_dist.toArray(options.include);
155
- const exclude = require_dist.toArray(options.exclude);
156
- const cwd = options.cwd || node_process.default.cwd();
157
- let pkg = {};
158
- try {
159
- const pkgStr = require_server.lookupFile(options.context, ["package.json"]);
160
- if (pkgStr) pkg = JSON.parse(pkgStr);
161
- } catch {}
162
- const outputDir = options.build.dist;
163
- const content = await generateMockEntryCode(cwd, include, exclude);
164
- const mockEntry = node_path.default.join(cwd, `mock-data-${Date.now()}.js`);
165
- await node_fs_promises.default.writeFile(mockEntry, content, "utf-8");
166
- const { code, deps } = await transformWithEsbuild(mockEntry, options);
167
- const mockDeps = getMockDependencies(deps, options.alias);
168
- await node_fs_promises.default.unlink(mockEntry);
169
- const outputList = [
170
- {
171
- filename: node_path.default.join(outputDir, "mock-data.js"),
172
- source: code
173
- },
174
- {
175
- filename: node_path.default.join(outputDir, "index.js"),
176
- source: generatorServerEntryCode(options)
177
- },
178
- {
179
- filename: node_path.default.join(outputDir, "package.json"),
180
- source: generatePackageJson(pkg, mockDeps)
181
- }
182
- ];
183
- try {
184
- if (node_path.default.isAbsolute(outputDir)) {
185
- for (const { filename } of outputList) if (node_fs.default.existsSync(filename)) await node_fs_promises.default.rm(filename);
186
- options.logger.info(`${picocolors.default.green("✓")} generate mock server in ${picocolors.default.cyan(outputDir)}`);
187
- for (const { filename, source } of outputList) {
188
- node_fs.default.mkdirSync(node_path.default.dirname(filename), { recursive: true });
189
- await node_fs_promises.default.writeFile(filename, source, "utf-8");
190
- const sourceSize = (source.length / 1024).toFixed(2);
191
- const name = node_path.default.relative(outputDir, filename);
192
- const space = name.length < 30 ? " ".repeat(30 - name.length) : "";
193
- options.logger.info(` ${picocolors.default.green(name)}${space}${picocolors.default.bold(picocolors.default.dim(`${sourceSize} kB`))}`);
194
- }
195
- } else for (const { filename, source } of outputList) ctx.emitFile({
196
- type: "asset",
197
- fileName: filename,
198
- source
199
- });
200
- } catch (e) {
201
- console.error(e);
202
- }
203
- }
204
- function getMockDependencies(deps, alias) {
205
- const list = /* @__PURE__ */ new Set();
206
- const excludeDeps = [
207
- "vite-plugin-mock-dev-server",
208
- "connect",
209
- "cors"
210
- ];
211
- const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
212
- Object.keys(deps).forEach((mPath) => {
213
- const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
214
- imports.forEach((dep) => {
215
- const name = normalizePackageName(dep);
216
- if (!excludeDeps.includes(name) && !(0, is_core_module.default)(name)) list.add(name);
217
- });
218
- });
219
- return Array.from(list);
220
- }
221
- function normalizePackageName(dep) {
222
- const [scope, name] = dep.split("/");
223
- if (scope[0] === "@") return `${scope}/${name}`;
224
- return scope;
225
- }
226
- function generatePackageJson(pkg, mockDeps) {
227
- const { dependencies = {}, devDependencies = {} } = pkg;
228
- const dependents = {
229
- ...dependencies,
230
- ...devDependencies
231
- };
232
- const mockPkg = {
233
- name: "mock-server",
234
- type: "module",
235
- scripts: { start: "node index.js" },
236
- dependencies: {
237
- connect: "^3.7.0",
238
- ["vite-plugin-mock-dev-server"]: `^1.9.1`,
239
- cors: "^2.8.5"
240
- },
241
- pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
242
- };
243
- mockDeps.forEach((dep) => {
244
- mockPkg.dependencies[dep] = dependents[dep] || "latest";
245
- });
246
- return JSON.stringify(mockPkg, null, 2);
247
- }
248
- function generatorServerEntryCode({ proxies, wsProxies, cookiesOptions, bodyParserOptions, priority, build: build$1 }) {
249
- const { serverPort, log } = build$1;
250
- return `import { createServer } from 'node:http';
251
- import connect from 'connect';
252
- import corsMiddleware from 'cors';
253
- import { baseMiddleware, createLogger, mockWebSocket } from 'vite-plugin-mock-dev-server/server';
254
- import mockData from './mock-data.js';
255
-
256
- const app = connect();
257
- const server = createServer(app);
258
- const logger = createLogger('mock-server', '${log}');
259
- const proxies = ${JSON.stringify(proxies)};
260
- const wsProxies = ${JSON.stringify(wsProxies)};
261
- const cookiesOptions = ${JSON.stringify(cookiesOptions)};
262
- const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
263
- const priority = ${JSON.stringify(priority)};
264
- const compiler = { mockData }
265
-
266
- mockWebSocket(compiler, server, { wsProxies, cookiesOptions, logger });
267
-
268
- app.use(corsMiddleware());
269
- app.use(baseMiddleware(compiler, {
270
- formidableOptions: { multiples: true },
271
- proxies,
272
- priority,
273
- cookiesOptions,
274
- bodyParserOptions,
275
- logger,
276
- }));
277
-
278
- server.listen(${serverPort});
279
-
280
- console.log('listen: http://localhost:${serverPort}');
281
- `;
282
- }
283
- async function generateMockEntryCode(cwd, include, exclude) {
284
- const includePaths = await (0, fast_glob.default)(include, { cwd });
285
- const includeFilter = (0, __rollup_pluginutils.createFilter)(include, exclude, { resolve: false });
286
- const mockFiles = includePaths.filter(includeFilter);
287
- let importers = "";
288
- const exporters = [];
289
- mockFiles.forEach((filepath, index) => {
290
- const file = require_server.normalizePath(node_path.default.join(cwd, filepath));
291
- importers += `import * as m${index} from '${file}';\n`;
292
- exporters.push(`[m${index}, '${filepath}']`);
293
- });
294
- return `import { transformMockData, transformRawData } from 'vite-plugin-mock-dev-server/server';
295
- ${importers}
296
- const exporters = [\n ${exporters.join(",\n ")}\n];
297
- const mockList = exporters.map(([mod, filepath]) => {
298
- const raw = mod.default || mod;
299
- return transformRawData(raw, filepath);
300
- });
301
- export default transformMockData(mockList);`;
302
- }
303
-
304
- //#endregion
305
- //#region src/core/mockCompiler.ts
306
- function createMockCompiler(options) {
307
- return new MockCompiler(options);
308
- }
309
- /**
310
- * mock配置加载器
311
- */
312
- var MockCompiler = class extends node_events.default {
313
- moduleCache = /* @__PURE__ */ new Map();
314
- moduleDeps = /* @__PURE__ */ new Map();
315
- cwd;
316
- mockWatcher;
317
- depsWatcher;
318
- moduleType = "cjs";
319
- _mockData = {};
320
- constructor(options) {
321
- super();
322
- this.options = options;
323
- this.cwd = options.cwd || node_process.default.cwd();
324
- try {
325
- const pkg = require_server.lookupFile(this.cwd, ["package.json"]);
326
- this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
327
- } catch {}
328
- }
329
- get mockData() {
330
- return this._mockData;
331
- }
332
- run() {
333
- const { include, exclude } = this.options;
334
- /**
335
- * 使用 rollup 提供的 include/exclude 规则,
336
- * 过滤包含文件
337
- */
338
- const includeFilter = (0, __rollup_pluginutils.createFilter)(include, exclude, { resolve: false });
339
- (0, fast_glob.default)(include, { cwd: this.cwd }).then((files) => files.filter(includeFilter).map((file) => () => this.loadMock(file))).then((loadList) => require_dist.promiseParallel(loadList, 10)).then(() => this.updateMockList());
340
- this.watchMockEntry();
341
- this.watchDeps();
342
- let timer = null;
343
- this.on("mock:update", async (filepath) => {
344
- if (!includeFilter(filepath)) return;
345
- await this.loadMock(filepath);
346
- if (timer) clearImmediate(timer);
347
- timer = setImmediate(() => {
348
- this.updateMockList();
349
- this.emit("mock:update-end", filepath);
350
- timer = null;
351
- });
352
- });
353
- this.on("mock:unlink", async (filepath) => {
354
- if (!includeFilter(filepath)) return;
355
- this.moduleCache.delete(filepath);
356
- this.updateMockList();
357
- this.emit("mock:update-end", filepath);
358
- });
359
- }
360
- watchMockEntry() {
361
- const { include } = this.options;
362
- const [firstGlob, ...otherGlob] = require_dist.toArray(include);
363
- const watcher = this.mockWatcher = chokidar.default.watch(firstGlob, {
364
- ignoreInitial: true,
365
- cwd: this.cwd
366
- });
367
- if (otherGlob.length > 0) otherGlob.forEach((glob) => watcher.add(glob));
368
- watcher.on("add", async (filepath) => {
369
- filepath = require_server.normalizePath(filepath);
370
- this.emit("mock:update", filepath);
371
- require_server.debug("watcher:add", filepath);
372
- });
373
- watcher.on("change", async (filepath) => {
374
- filepath = require_server.normalizePath(filepath);
375
- this.emit("mock:update", filepath);
376
- require_server.debug("watcher:change", filepath);
377
- });
378
- watcher.on("unlink", async (filepath) => {
379
- filepath = require_server.normalizePath(filepath);
380
- this.emit("mock:unlink", filepath);
381
- require_server.debug("watcher:unlink", filepath);
382
- });
383
- }
384
- /**
385
- * 监听 mock文件依赖的本地文件变动,
386
- * mock依赖文件更新,mock文件也一并更新
387
- */
388
- watchDeps() {
389
- const oldDeps = [];
390
- this.depsWatcher = chokidar.default.watch([], {
391
- ignoreInitial: true,
392
- cwd: this.cwd
393
- });
394
- this.depsWatcher.on("change", (filepath) => {
395
- filepath = require_server.normalizePath(filepath);
396
- const mockFiles = this.moduleDeps.get(filepath);
397
- mockFiles?.forEach((file) => {
398
- this.emit("mock:update", file);
399
- });
400
- });
401
- this.depsWatcher.on("unlink", (filepath) => {
402
- filepath = require_server.normalizePath(filepath);
403
- this.moduleDeps.delete(filepath);
404
- });
405
- this.on("update:deps", () => {
406
- const deps = [];
407
- for (const [dep] of this.moduleDeps.entries()) deps.push(dep);
408
- const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
409
- if (exactDeps.length > 0) this.depsWatcher.add(exactDeps);
410
- });
411
- }
412
- close() {
413
- this.mockWatcher?.close();
414
- this.depsWatcher?.close();
415
- }
416
- updateMockList() {
417
- this._mockData = require_server.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, require_server.transformRawData(raw, filepath));
451
- this.updateModuleDeps(filepath, deps);
452
- } catch (e) {
453
- console.error(e);
454
- }
455
- }
456
- };
457
-
458
- //#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();
467
- /**
468
- * 监听 mock 文件是否发生变更,如何配置了 reload 为 true,
469
- * 当发生变更时,通知当前页面进行重新加载
470
- */
471
- compiler.on("mock:update-end", () => {
472
- if (options.reload) ws?.send({ type: "full-reload" });
473
- });
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
- require_server.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
- require_server.baseMiddleware(compiler, options)
500
- );
501
- return middlewares.filter(Boolean);
502
- }
503
- function corsMiddleware(compiler, { proxies, cors: corsOptions }) {
504
- return !corsOptions ? void 0 : function(req, res, next) {
505
- const { pathname } = require_server.urlParse(req.url);
506
- if (!pathname || proxies.length === 0 || !proxies.some((context) => require_server.doesProxyContextMatchUrl(context, req.url))) return next();
507
- const mockData = compiler.mockData;
508
- const mockUrl = Object.keys(mockData).find((key) => (0, path_to_regexp.pathToRegexp)(key).test(pathname));
509
- if (!mockUrl) return next();
510
- (0, cors.default)(corsOptions)(req, res, next);
511
- };
512
- }
513
-
514
- //#endregion
515
- //#region src/core/define.ts
516
- function viteDefine(config) {
517
- const processNodeEnv = {};
518
- const nodeEnv = node_process.default.env.NODE_ENV || config.mode;
519
- Object.assign(processNodeEnv, {
520
- "process.env.NODE_ENV": JSON.stringify(nodeEnv),
521
- "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
522
- "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
523
- });
524
- const userDefine = {};
525
- const userDefineEnv = {};
526
- for (const key in config.define) {
527
- const val = config.define[key];
528
- const isMetaEnv = key.startsWith("import.meta.env.");
529
- if (typeof val === "string") {
530
- if (canJsonParse(val)) {
531
- userDefine[key] = val;
532
- if (isMetaEnv) userDefineEnv[key.slice(16)] = val;
533
- }
534
- } else {
535
- userDefine[key] = handleDefineValue(val);
536
- if (isMetaEnv) userDefineEnv[key.slice(16)] = val;
537
- }
538
- }
539
- const importMetaKeys = {};
540
- const importMetaEnvKeys = {};
541
- const importMetaFallbackKeys = {};
542
- importMetaKeys["import.meta.hot"] = `undefined`;
543
- for (const key in config.env) {
544
- const val = JSON.stringify(config.env[key]);
545
- importMetaKeys[`import.meta.env.${key}`] = val;
546
- importMetaEnvKeys[key] = val;
547
- }
548
- importMetaFallbackKeys["import.meta.env"] = `undefined`;
549
- const define = {
550
- ...processNodeEnv,
551
- ...importMetaKeys,
552
- ...userDefine,
553
- ...importMetaFallbackKeys
554
- };
555
- if ("import.meta.env" in define) define["import.meta.env"] = serializeDefine({
556
- ...importMetaEnvKeys,
557
- ...userDefineEnv
558
- });
559
- return define;
560
- }
561
- /**
562
- * Like `JSON.stringify` but keeps raw string values as a literal
563
- * in the generated code. For example: `"window"` would refer to
564
- * the global `window` object directly.
565
- */
566
- function serializeDefine(define) {
567
- let res = `{`;
568
- const keys = Object.keys(define);
569
- for (let i = 0; i < keys.length; i++) {
570
- const key = keys[i];
571
- const val = define[key];
572
- res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
573
- if (i !== keys.length - 1) res += `, `;
574
- }
575
- return `${res}}`;
576
- }
577
- function handleDefineValue(value) {
578
- if (typeof value === "undefined") return "undefined";
579
- if (typeof value === "string") return value;
580
- return JSON.stringify(value);
581
- }
582
- function canJsonParse(value) {
583
- try {
584
- JSON.parse(value);
585
- return true;
586
- } catch {
587
- return false;
588
- }
589
- }
590
-
591
- //#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$2 = true, formidableOptions = {}, build: build$1 = false, cookiesOptions = {}, bodyParserOptions = {}, priority = {} }, config) {
598
- const logger = require_server.createLogger("vite:mock", require_dist.isBoolean(log) ? log ? "info" : "error" : log);
599
- const { httpProxies } = require_server.ensureProxies(config.server.proxy || {});
600
- const proxies = require_dist.uniq([...require_dist.toArray(prefix), ...httpProxies]);
601
- const wsProxies = require_dist.toArray(wsPrefix);
602
- if (!proxies.length && !wsProxies.length) logger.warn(`No proxy was configured, mock server will not work. See ${picocolors.default.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
603
- const enabled = cors$2 === false ? false : config.server.cors !== false;
604
- let corsOptions = {};
605
- if (enabled && config.server.cors !== false) corsOptions = {
606
- ...corsOptions,
607
- ...typeof config.server.cors === "boolean" ? {} : config.server.cors
608
- };
609
- if (enabled && cors$2 !== false) corsOptions = {
610
- ...corsOptions,
611
- ...typeof cors$2 === "boolean" ? {} : cors$2
612
- };
613
- const alias = [];
614
- const aliasConfig = config.resolve.alias || [];
615
- if (require_dist.isArray(aliasConfig)) alias.push(...aliasConfig);
616
- else Object.entries(aliasConfig).forEach(([find, replacement]) => {
617
- alias.push({
618
- find,
619
- replacement
620
- });
621
- });
622
- return {
623
- cwd: cwd || node_process.default.cwd(),
624
- include,
625
- exclude,
626
- context: config.root,
627
- reload,
628
- cors: enabled ? corsOptions : false,
629
- cookiesOptions,
630
- log,
631
- formidableOptions: {
632
- multiples: true,
633
- ...formidableOptions
634
- },
635
- bodyParserOptions,
636
- priority,
637
- build: build$1 ? Object.assign({
638
- serverPort: 8080,
639
- dist: "mockServer",
640
- log: "error"
641
- }, typeof build$1 === "object" ? build$1 : {}) : false,
642
- proxies,
643
- wsProxies,
644
- logger,
645
- alias,
646
- define: viteDefine(config)
647
- };
648
- }
649
-
650
- //#endregion
651
- //#region src/plugin.ts
652
- function mockDevServerPlugin(options = {}) {
653
- const plugins = [serverPlugin(options)];
654
- if (options.build) plugins.push(buildPlugin(options));
655
- return plugins;
656
- }
657
- function buildPlugin(options) {
658
- let viteConfig = {};
659
- let resolvedOptions;
660
- return {
661
- name: "vite-plugin-mock-dev-server-generator",
662
- enforce: "post",
663
- apply: "build",
664
- configResolved(config) {
665
- viteConfig = config;
666
- resolvedOptions = resolvePluginOptions(options, config);
667
- config.logger.warn("");
668
- },
669
- async buildEnd(error) {
670
- if (error || viteConfig.command !== "build") return;
671
- await generateMockServer(this, resolvedOptions);
672
- }
673
- };
674
- }
675
- function serverPlugin(options) {
676
- let resolvedOptions;
677
- return {
678
- name: "vite-plugin-mock-dev-server",
679
- enforce: "pre",
680
- apply: "serve",
681
- config(config) {
682
- const wsPrefix = require_dist.toArray(options.wsPrefix);
683
- if (wsPrefix.length && config.server?.proxy) {
684
- const proxy = {};
685
- Object.keys(config.server.proxy).forEach((key) => {
686
- if (!wsPrefix.includes(key)) proxy[key] = config.server.proxy[key];
687
- });
688
- config.server.proxy = proxy;
689
- }
690
- require_server.recoverRequest(config);
691
- },
692
- configResolved(config) {
693
- resolvedOptions = resolvePluginOptions(options, config);
694
- config.logger.warn("");
695
- },
696
- configureServer({ middlewares, httpServer, ws }) {
697
- const middlewareList = mockServerMiddleware(resolvedOptions, httpServer, ws);
698
- middlewareList.forEach((middleware) => middlewares.use(middleware));
699
- },
700
- configurePreviewServer({ middlewares, httpServer }) {
701
- const middlewareList = mockServerMiddleware(resolvedOptions, httpServer);
702
- middlewareList.forEach((middleware) => middlewares.use(middleware));
703
- }
704
- };
705
- }
706
-
707
- //#endregion
708
- //#region src/index.ts
709
- /**
710
- * @deprecated use named export instead
711
- */
712
- function mockDevServerPluginWithDefaultExportWasDeprecated(options = {}) {
713
- console.warn(`${picocolors.default.yellow("[vite-plugin-mock-dev-server]")} ${picocolors.default.yellow(picocolors.default.bold("WARNING:"))} The plugin default export is ${picocolors.default.bold("deprecated")}, it will be removed in next major version, use ${picocolors.default.bold("named export")} instead:\n\n ${picocolors.default.green("import { mockDevServerPlugin } from \"vite-plugin-mock-dev-server\"")}\n`);
714
- return mockDevServerPlugin(options);
715
- }
716
-
717
- //#endregion
718
- exports.baseMiddleware = require_server.baseMiddleware;
719
- exports.createDefineMock = require_helper.createDefineMock;
720
- exports.createLogger = require_server.createLogger;
721
- exports.createSSEStream = require_helper.createSSEStream;
722
- exports.default = mockDevServerPluginWithDefaultExportWasDeprecated;
723
- exports.defineMock = require_helper.defineMock;
724
- exports.defineMockData = require_helper.defineMockData;
725
- exports.logLevels = require_server.logLevels;
726
- exports.mockDevServerPlugin = mockDevServerPlugin;
727
- exports.mockWebSocket = require_server.mockWebSocket;
728
- exports.sortByValidator = require_server.sortByValidator;
729
- exports.transformMockData = require_server.transformMockData;
730
- exports.transformRawData = require_server.transformRawData;