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