rspack-plugin-mock 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/chunk-4HRWYJ3E.cjs +546 -0
- package/dist/{chunk-YSJVV4SH.js → chunk-EY46RSAC.js} +84 -604
- package/dist/{chunk-I54ZNZWL.cjs → chunk-ZEC4FWWY.cjs} +83 -603
- package/dist/chunk-ZYUUWKWW.js +546 -0
- package/dist/helper.cjs +16 -5
- package/dist/helper.d.cts +2 -2
- package/dist/helper.d.ts +2 -2
- package/dist/helper.js +15 -4
- package/dist/index.cjs +103 -34
- package/dist/index.d.cts +14 -69
- package/dist/index.d.ts +14 -69
- package/dist/index.js +93 -24
- package/dist/mockWebsocket-CPuTAvL0.d.ts +76 -0
- package/dist/mockWebsocket-Dc9CZBfv.d.cts +76 -0
- package/dist/rsbuild.cjs +11 -9
- package/dist/rsbuild.d.cts +1 -1
- package/dist/rsbuild.d.ts +1 -1
- package/dist/rsbuild.js +4 -2
- package/dist/server.cjs +18 -0
- package/dist/server.d.cts +31 -0
- package/dist/server.d.ts +31 -0
- package/dist/server.js +18 -0
- package/dist/{types-C770q3L0.d.cts → types-BgpcN3jm.d.cts} +1 -1
- package/dist/{types-C770q3L0.d.ts → types-BgpcN3jm.d.ts} +1 -1
- package/package.json +11 -6
- package/dist/chunk-HTOWPFQ7.js +0 -20
- package/dist/chunk-KE2LVHUP.cjs +0 -20
- package/dist/chunk-OYBMX3GQ.cjs +0 -97
- package/dist/chunk-P5FOCSCE.js +0 -97
- package/dist/rspack-BB-Jtq4f.d.cts +0 -32
- package/dist/rspack-h3uerEgg.d.ts +0 -32
- package/dist/rspack.cjs +0 -9
- package/dist/rspack.d.cts +0 -11
- package/dist/rspack.d.ts +0 -11
- package/dist/rspack.js +0 -9
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
import {
|
|
2
|
+
baseMiddleware,
|
|
3
|
+
createLogger,
|
|
4
|
+
doesProxyContextMatchUrl,
|
|
5
|
+
lookupFile,
|
|
6
|
+
normalizePath,
|
|
7
|
+
packageDir,
|
|
8
|
+
transformMockData,
|
|
9
|
+
transformRawData,
|
|
10
|
+
urlParse,
|
|
11
|
+
vfs
|
|
12
|
+
} from "./chunk-EY46RSAC.js";
|
|
13
|
+
|
|
14
|
+
// src/core/mockMiddleware.ts
|
|
15
|
+
import cors from "cors";
|
|
16
|
+
import { pathToRegexp } from "path-to-regexp";
|
|
17
|
+
function createMockMiddleware(compiler, options) {
|
|
18
|
+
function mockMiddleware(middlewares, reload) {
|
|
19
|
+
middlewares.unshift(baseMiddleware(compiler, options));
|
|
20
|
+
const corsMiddleware = createCorsMiddleware(compiler, options);
|
|
21
|
+
if (corsMiddleware) {
|
|
22
|
+
middlewares.unshift(corsMiddleware);
|
|
23
|
+
}
|
|
24
|
+
if (options.reload) {
|
|
25
|
+
compiler.on("update", () => reload?.());
|
|
26
|
+
}
|
|
27
|
+
return middlewares;
|
|
28
|
+
}
|
|
29
|
+
return mockMiddleware;
|
|
30
|
+
}
|
|
31
|
+
function createCorsMiddleware(compiler, options) {
|
|
32
|
+
let corsOptions = {};
|
|
33
|
+
const enabled = options.cors !== false;
|
|
34
|
+
if (enabled) {
|
|
35
|
+
corsOptions = {
|
|
36
|
+
...corsOptions,
|
|
37
|
+
...typeof options.cors === "boolean" ? {} : options.cors
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const proxies = options.proxies;
|
|
41
|
+
return !enabled ? void 0 : function(req, res, next) {
|
|
42
|
+
const { pathname } = urlParse(req.url);
|
|
43
|
+
if (!pathname || proxies.length === 0 || !proxies.some(
|
|
44
|
+
(context) => doesProxyContextMatchUrl(context, req.url, req)
|
|
45
|
+
)) {
|
|
46
|
+
return next();
|
|
47
|
+
}
|
|
48
|
+
const mockData = compiler.mockData;
|
|
49
|
+
const mockUrl = Object.keys(mockData).find(
|
|
50
|
+
(key) => pathToRegexp(key).test(pathname)
|
|
51
|
+
);
|
|
52
|
+
if (!mockUrl)
|
|
53
|
+
return next();
|
|
54
|
+
cors(corsOptions)(req, res, next);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/core/resolvePluginOptions.ts
|
|
59
|
+
import process from "process";
|
|
60
|
+
import { isBoolean, toArray } from "@pengzhanbo/utils";
|
|
61
|
+
function resolvePluginOptions({
|
|
62
|
+
prefix = [],
|
|
63
|
+
wsPrefix = [],
|
|
64
|
+
cwd,
|
|
65
|
+
include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
|
|
66
|
+
exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
|
|
67
|
+
reload = false,
|
|
68
|
+
log = "info",
|
|
69
|
+
cors: cors2 = true,
|
|
70
|
+
formidableOptions = {},
|
|
71
|
+
build = false,
|
|
72
|
+
cookiesOptions = {},
|
|
73
|
+
bodyParserOptions = {},
|
|
74
|
+
priority = {}
|
|
75
|
+
} = {}, { alias, context, plugins, proxies }) {
|
|
76
|
+
const logger = createLogger(
|
|
77
|
+
"rspack:mock",
|
|
78
|
+
isBoolean(log) ? log ? "info" : "error" : log
|
|
79
|
+
);
|
|
80
|
+
return {
|
|
81
|
+
prefix,
|
|
82
|
+
wsPrefix,
|
|
83
|
+
cwd: cwd || context || process.cwd(),
|
|
84
|
+
include,
|
|
85
|
+
exclude,
|
|
86
|
+
reload,
|
|
87
|
+
cors: cors2,
|
|
88
|
+
cookiesOptions,
|
|
89
|
+
log,
|
|
90
|
+
formidableOptions: {
|
|
91
|
+
multiples: true,
|
|
92
|
+
...formidableOptions
|
|
93
|
+
},
|
|
94
|
+
bodyParserOptions,
|
|
95
|
+
priority,
|
|
96
|
+
build: build ? Object.assign(
|
|
97
|
+
{
|
|
98
|
+
serverPort: 8080,
|
|
99
|
+
dist: "mockServer",
|
|
100
|
+
log: "error"
|
|
101
|
+
},
|
|
102
|
+
typeof build === "object" ? build : {}
|
|
103
|
+
) : false,
|
|
104
|
+
alias,
|
|
105
|
+
plugins,
|
|
106
|
+
proxies,
|
|
107
|
+
wsProxies: toArray(wsPrefix),
|
|
108
|
+
logger
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/core/build.ts
|
|
113
|
+
import fs from "fs";
|
|
114
|
+
import fsp from "fs/promises";
|
|
115
|
+
import path2 from "path";
|
|
116
|
+
import process2 from "process";
|
|
117
|
+
import fg from "fast-glob";
|
|
118
|
+
import { createFilter } from "@rollup/pluginutils";
|
|
119
|
+
import color2 from "picocolors";
|
|
120
|
+
import { toArray as toArray2 } from "@pengzhanbo/utils";
|
|
121
|
+
|
|
122
|
+
// src/core/createRspackCompiler.ts
|
|
123
|
+
import path from "path";
|
|
124
|
+
import * as rspackCore from "@rspack/core";
|
|
125
|
+
import color from "picocolors";
|
|
126
|
+
import isCore from "is-core-module";
|
|
127
|
+
function createCompiler(options, callback) {
|
|
128
|
+
const rspackOptions = resolveRspackOptions(options);
|
|
129
|
+
const isWatch = rspackOptions.watch === true;
|
|
130
|
+
async function handler(err, stats) {
|
|
131
|
+
const name = "[rspack:mock]";
|
|
132
|
+
const logError = stats?.compilation.getLogger(name).error || ((...args) => console.error(color.red(name), ...args));
|
|
133
|
+
if (err) {
|
|
134
|
+
logError(err.stack || err);
|
|
135
|
+
if ("details" in err) {
|
|
136
|
+
logError(err.details);
|
|
137
|
+
}
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (stats?.hasErrors()) {
|
|
141
|
+
const info = stats.toJson();
|
|
142
|
+
logError(info.errors);
|
|
143
|
+
}
|
|
144
|
+
const code = vfs.readFileSync("/output.js", "utf-8");
|
|
145
|
+
const externals = [];
|
|
146
|
+
if (!isWatch) {
|
|
147
|
+
const modules = stats?.toJson().modules || [];
|
|
148
|
+
const aliasList = Object.keys(options.alias || {}).map((key) => key.replace(/\$$/g, ""));
|
|
149
|
+
for (const { name: name2 } of modules) {
|
|
150
|
+
if (name2?.startsWith("external")) {
|
|
151
|
+
const packageName = normalizePackageName(name2);
|
|
152
|
+
if (!isCore(packageName) && !aliasList.includes(packageName))
|
|
153
|
+
externals.push(normalizePackageName(name2));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
await callback({ code, externals });
|
|
158
|
+
}
|
|
159
|
+
const compiler = rspackCore.rspack(rspackOptions, isWatch ? handler : void 0);
|
|
160
|
+
if (compiler)
|
|
161
|
+
compiler.outputFileSystem = vfs;
|
|
162
|
+
if (!isWatch) {
|
|
163
|
+
compiler?.run(async (...args) => {
|
|
164
|
+
await handler(...args);
|
|
165
|
+
compiler.close(() => {
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
return compiler;
|
|
170
|
+
}
|
|
171
|
+
function transformWithRspack(options) {
|
|
172
|
+
return new Promise((resolve) => {
|
|
173
|
+
createCompiler({ ...options, watch: false }, (result) => {
|
|
174
|
+
resolve(result);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
function normalizePackageName(name) {
|
|
179
|
+
const filepath = name.replace("external ", "").slice(1, -1);
|
|
180
|
+
const [scope, packageName] = filepath.split("/");
|
|
181
|
+
if (filepath[0] === "@") {
|
|
182
|
+
return `${scope}/${packageName}`;
|
|
183
|
+
}
|
|
184
|
+
return scope;
|
|
185
|
+
}
|
|
186
|
+
function resolveRspackOptions({
|
|
187
|
+
cwd,
|
|
188
|
+
isEsm = true,
|
|
189
|
+
entryFile,
|
|
190
|
+
plugins,
|
|
191
|
+
alias,
|
|
192
|
+
watch = false
|
|
193
|
+
}) {
|
|
194
|
+
const targets = ["node >= 18.0.0"];
|
|
195
|
+
return {
|
|
196
|
+
mode: "production",
|
|
197
|
+
context: cwd,
|
|
198
|
+
entry: entryFile,
|
|
199
|
+
watch,
|
|
200
|
+
target: "node18.0",
|
|
201
|
+
externalsType: isEsm ? "module" : "commonjs2",
|
|
202
|
+
externals: /^[^./].*/,
|
|
203
|
+
resolve: {
|
|
204
|
+
alias,
|
|
205
|
+
extensions: [".js", ".ts", ".cjs", ".mjs", ".json5", ".json"]
|
|
206
|
+
},
|
|
207
|
+
plugins,
|
|
208
|
+
output: {
|
|
209
|
+
library: { type: !isEsm ? "commonjs2" : "module" },
|
|
210
|
+
filename: "output.js",
|
|
211
|
+
path: "/"
|
|
212
|
+
},
|
|
213
|
+
experiments: { outputModule: isEsm },
|
|
214
|
+
optimization: { minimize: !watch },
|
|
215
|
+
module: {
|
|
216
|
+
rules: [
|
|
217
|
+
{
|
|
218
|
+
test: /\.json5?$/,
|
|
219
|
+
loader: path.join(packageDir, "json5-loader.cjs"),
|
|
220
|
+
type: "javascript/auto"
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
test: /\.[cm]?js$/,
|
|
224
|
+
use: [
|
|
225
|
+
{
|
|
226
|
+
loader: "builtin:swc-loader",
|
|
227
|
+
options: {
|
|
228
|
+
jsc: { parser: { syntax: "ecmascript" } },
|
|
229
|
+
env: { targets }
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
]
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
test: /\.[cm]?ts$/,
|
|
236
|
+
use: [
|
|
237
|
+
{
|
|
238
|
+
loader: "builtin:swc-loader",
|
|
239
|
+
options: {
|
|
240
|
+
jsc: { parser: { syntax: "typescript" } },
|
|
241
|
+
env: { targets }
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
]
|
|
245
|
+
}
|
|
246
|
+
]
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// src/core/build.ts
|
|
252
|
+
async function buildMockServer(options, outputDir) {
|
|
253
|
+
const entryFile = path2.resolve(process2.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
254
|
+
const mockFileList = await getMockFileList(options);
|
|
255
|
+
await writeMockEntryFile(entryFile, mockFileList, options.cwd);
|
|
256
|
+
const { code, externals } = await transformWithRspack({
|
|
257
|
+
entryFile,
|
|
258
|
+
cwd: options.cwd,
|
|
259
|
+
plugins: options.plugins,
|
|
260
|
+
alias: options.alias
|
|
261
|
+
});
|
|
262
|
+
await fsp.unlink(entryFile);
|
|
263
|
+
const outputList = [
|
|
264
|
+
{ filename: "mock-data.js", source: code },
|
|
265
|
+
{ filename: "index.js", source: generatorServerEntryCode(options) },
|
|
266
|
+
{ filename: "package.json", source: generatePackageJson(options, externals) }
|
|
267
|
+
];
|
|
268
|
+
const dist = path2.resolve(outputDir, options.build.dist);
|
|
269
|
+
options.logger.info(
|
|
270
|
+
`${color2.green("\u2713")} generate mock server in ${color2.cyan(path2.relative(process2.cwd(), dist))}`
|
|
271
|
+
);
|
|
272
|
+
if (!fs.existsSync(dist)) {
|
|
273
|
+
await fsp.mkdir(dist, { recursive: true });
|
|
274
|
+
}
|
|
275
|
+
for (const { filename, source } of outputList) {
|
|
276
|
+
await fsp.writeFile(path2.join(dist, filename), source, "utf8");
|
|
277
|
+
const sourceSize = (source.length / 1024).toFixed(2);
|
|
278
|
+
const space = filename.length < 24 ? " ".repeat(24 - filename.length) : "";
|
|
279
|
+
options.logger.info(` ${color2.green(filename)}${space}${color2.bold(color2.dim(`${sourceSize} kB`))}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
function generatePackageJson(options, externals) {
|
|
283
|
+
const deps = getHostDependencies(options.cwd);
|
|
284
|
+
const { name, version } = getPluginPackageInfo();
|
|
285
|
+
const exclude = [name, "connect", "cors"];
|
|
286
|
+
const mockPkg = {
|
|
287
|
+
name: "mock-server",
|
|
288
|
+
type: "module",
|
|
289
|
+
scripts: {
|
|
290
|
+
start: "node index.js"
|
|
291
|
+
},
|
|
292
|
+
dependencies: {
|
|
293
|
+
connect: "^3.7.0",
|
|
294
|
+
[name]: `^${version}`,
|
|
295
|
+
cors: "^2.8.5"
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
externals.filter((dep) => !exclude.includes(dep)).forEach((dep) => {
|
|
299
|
+
mockPkg.dependencies[dep] = deps[dep] || "latest";
|
|
300
|
+
});
|
|
301
|
+
return JSON.stringify(mockPkg, null, 2);
|
|
302
|
+
}
|
|
303
|
+
function generatorServerEntryCode({
|
|
304
|
+
proxies,
|
|
305
|
+
wsPrefix,
|
|
306
|
+
cookiesOptions,
|
|
307
|
+
bodyParserOptions,
|
|
308
|
+
priority,
|
|
309
|
+
build
|
|
310
|
+
}) {
|
|
311
|
+
const { serverPort, log } = build;
|
|
312
|
+
return `import { createServer } from 'node:http';
|
|
313
|
+
import connect from 'connect';
|
|
314
|
+
import corsMiddleware from 'cors';
|
|
315
|
+
import {
|
|
316
|
+
baseMiddleware,
|
|
317
|
+
createLogger,
|
|
318
|
+
mockWebSocket,
|
|
319
|
+
transformMockData,
|
|
320
|
+
transformRawData
|
|
321
|
+
} from 'rspack-plugin-mock/server';
|
|
322
|
+
import rawData from './mock-data.js';
|
|
323
|
+
|
|
324
|
+
const app = connect();
|
|
325
|
+
const server = createServer(app);
|
|
326
|
+
const logger = createLogger('mock-server', '${log}');
|
|
327
|
+
const proxies = ${JSON.stringify(proxies)};
|
|
328
|
+
const wsProxies = ${JSON.stringify(toArray2(wsPrefix))};
|
|
329
|
+
const cookiesOptions = ${JSON.stringify(cookiesOptions)};
|
|
330
|
+
const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
|
|
331
|
+
const priority = ${JSON.stringify(priority)};
|
|
332
|
+
const mockConfig = {
|
|
333
|
+
mockData: transformMockData(transformRawData(rawData)),
|
|
334
|
+
on: () => {},
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
mockWebSocket(mockConfig, server, { wsProxies, cookiesOptions, logger });
|
|
338
|
+
|
|
339
|
+
app.use(corsMiddleware());
|
|
340
|
+
app.use(baseMiddleware(mockConfig, {
|
|
341
|
+
formidableOptions: { multiples: true },
|
|
342
|
+
proxies,
|
|
343
|
+
priority,
|
|
344
|
+
cookiesOptions,
|
|
345
|
+
bodyParserOptions,
|
|
346
|
+
logger,
|
|
347
|
+
}));
|
|
348
|
+
|
|
349
|
+
server.listen(${serverPort});
|
|
350
|
+
|
|
351
|
+
console.log('listen: http://localhost:${serverPort}');
|
|
352
|
+
`;
|
|
353
|
+
}
|
|
354
|
+
async function getMockFileList({ cwd, include, exclude }) {
|
|
355
|
+
const filter = createFilter(include, exclude, { resolve: false });
|
|
356
|
+
return await fg(include, { cwd }).then((files) => files.filter(filter));
|
|
357
|
+
}
|
|
358
|
+
async function writeMockEntryFile(entryFile, files, cwd) {
|
|
359
|
+
const importers = [];
|
|
360
|
+
const exporters = [];
|
|
361
|
+
for (const [index, filepath] of files.entries()) {
|
|
362
|
+
const file = normalizePath(path2.join(cwd, filepath));
|
|
363
|
+
importers.push(`import * as m${index} from '${file}'`);
|
|
364
|
+
exporters.push(`[m${index}, '${filepath}']`);
|
|
365
|
+
}
|
|
366
|
+
const code = `${importers.join("\n")}
|
|
367
|
+
|
|
368
|
+
export default [
|
|
369
|
+
${exporters.join(",\n ")}
|
|
370
|
+
]`;
|
|
371
|
+
const dirname = path2.dirname(entryFile);
|
|
372
|
+
if (!fs.existsSync(dirname)) {
|
|
373
|
+
await fsp.mkdir(dirname, { recursive: true });
|
|
374
|
+
}
|
|
375
|
+
await fsp.writeFile(entryFile, code, "utf8");
|
|
376
|
+
}
|
|
377
|
+
function getPluginPackageInfo() {
|
|
378
|
+
let pkg = {};
|
|
379
|
+
try {
|
|
380
|
+
const filepath = path2.join(packageDir, "../package.json");
|
|
381
|
+
if (fs.existsSync(filepath)) {
|
|
382
|
+
pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
|
|
383
|
+
}
|
|
384
|
+
} catch {
|
|
385
|
+
}
|
|
386
|
+
return {
|
|
387
|
+
name: pkg.name || "rspack-plugin-mock",
|
|
388
|
+
version: pkg.version || "latest"
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
function getHostDependencies(context) {
|
|
392
|
+
let pkg = {};
|
|
393
|
+
try {
|
|
394
|
+
const content = lookupFile(context, ["package.json"]);
|
|
395
|
+
if (content)
|
|
396
|
+
pkg = JSON.parse(content);
|
|
397
|
+
} catch {
|
|
398
|
+
}
|
|
399
|
+
return { ...pkg.dependencies, ...pkg.devDependencies };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/core/mockCompiler.ts
|
|
403
|
+
import EventEmitter from "events";
|
|
404
|
+
import process3 from "process";
|
|
405
|
+
import path4 from "path";
|
|
406
|
+
import fastGlob from "fast-glob";
|
|
407
|
+
import chokidar from "chokidar";
|
|
408
|
+
import { createFilter as createFilter2 } from "@rollup/pluginutils";
|
|
409
|
+
import { toArray as toArray3 } from "@pengzhanbo/utils";
|
|
410
|
+
|
|
411
|
+
// src/core/loadFromCode.ts
|
|
412
|
+
import path3 from "path";
|
|
413
|
+
import fs2, { promises as fsp2 } from "fs";
|
|
414
|
+
async function loadFromCode({
|
|
415
|
+
filepath,
|
|
416
|
+
code,
|
|
417
|
+
isESM,
|
|
418
|
+
cwd
|
|
419
|
+
}) {
|
|
420
|
+
filepath = path3.resolve(cwd, filepath);
|
|
421
|
+
const fileBase = `${filepath}.timestamp-${Date.now()}`;
|
|
422
|
+
const ext = isESM ? ".mjs" : ".cjs";
|
|
423
|
+
const fileNameTmp = `${fileBase}${ext}`;
|
|
424
|
+
await fsp2.writeFile(fileNameTmp, code, "utf8");
|
|
425
|
+
try {
|
|
426
|
+
const result = await import(fileNameTmp);
|
|
427
|
+
return result.default || result;
|
|
428
|
+
} finally {
|
|
429
|
+
try {
|
|
430
|
+
fs2.unlinkSync(fileNameTmp);
|
|
431
|
+
} catch {
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// src/core/mockCompiler.ts
|
|
437
|
+
function createMockCompiler(options) {
|
|
438
|
+
return new MockCompiler(options);
|
|
439
|
+
}
|
|
440
|
+
var MockCompiler = class extends EventEmitter {
|
|
441
|
+
constructor(options) {
|
|
442
|
+
super();
|
|
443
|
+
this.options = options;
|
|
444
|
+
this.cwd = options.cwd || process3.cwd();
|
|
445
|
+
const { include, exclude } = this.options;
|
|
446
|
+
this.fileFilter = createFilter2(include, exclude, { resolve: false });
|
|
447
|
+
try {
|
|
448
|
+
const pkg = lookupFile(this.cwd, ["package.json"]);
|
|
449
|
+
this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
|
|
450
|
+
} catch {
|
|
451
|
+
}
|
|
452
|
+
this.entryFile = path4.resolve(process3.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
453
|
+
}
|
|
454
|
+
cwd;
|
|
455
|
+
mockWatcher;
|
|
456
|
+
moduleType = "cjs";
|
|
457
|
+
entryFile;
|
|
458
|
+
_mockData = {};
|
|
459
|
+
fileFilter;
|
|
460
|
+
watchInfo;
|
|
461
|
+
compiler;
|
|
462
|
+
get mockData() {
|
|
463
|
+
return this._mockData;
|
|
464
|
+
}
|
|
465
|
+
async run() {
|
|
466
|
+
await this.updateMockEntry();
|
|
467
|
+
this.watchMockFiles();
|
|
468
|
+
const { plugins, alias } = this.options;
|
|
469
|
+
const options = {
|
|
470
|
+
isEsm: this.moduleType === "esm",
|
|
471
|
+
cwd: this.cwd,
|
|
472
|
+
plugins,
|
|
473
|
+
entryFile: this.entryFile,
|
|
474
|
+
alias,
|
|
475
|
+
watch: true
|
|
476
|
+
};
|
|
477
|
+
this.compiler = createCompiler(options, async ({ code }) => {
|
|
478
|
+
try {
|
|
479
|
+
const result = await loadFromCode({
|
|
480
|
+
filepath: "mock.bundle.js",
|
|
481
|
+
code,
|
|
482
|
+
isESM: this.moduleType === "esm",
|
|
483
|
+
cwd: this.cwd
|
|
484
|
+
});
|
|
485
|
+
this._mockData = transformMockData(transformRawData(result));
|
|
486
|
+
this.emit("update", this.watchInfo || {});
|
|
487
|
+
} catch (e) {
|
|
488
|
+
this.options.logger.error(e.stack || e.message);
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
close() {
|
|
493
|
+
this.mockWatcher.close();
|
|
494
|
+
this.compiler?.close(() => {
|
|
495
|
+
});
|
|
496
|
+
this.emit("close");
|
|
497
|
+
}
|
|
498
|
+
updateAlias(alias) {
|
|
499
|
+
this.options.alias = {
|
|
500
|
+
...this.options.alias,
|
|
501
|
+
...alias
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
async updateMockEntry() {
|
|
505
|
+
const files = await this.getMockFiles();
|
|
506
|
+
await writeMockEntryFile(this.entryFile, files, this.cwd);
|
|
507
|
+
}
|
|
508
|
+
async getMockFiles() {
|
|
509
|
+
const { include } = this.options;
|
|
510
|
+
const files = await fastGlob(include, { cwd: this.cwd });
|
|
511
|
+
return files.filter(this.fileFilter);
|
|
512
|
+
}
|
|
513
|
+
watchMockFiles() {
|
|
514
|
+
const { include } = this.options;
|
|
515
|
+
const [firstGlob, ...otherGlob] = toArray3(include);
|
|
516
|
+
const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
|
|
517
|
+
ignoreInitial: true,
|
|
518
|
+
cwd: this.cwd
|
|
519
|
+
});
|
|
520
|
+
if (otherGlob.length > 0)
|
|
521
|
+
otherGlob.forEach((glob) => watcher.add(glob));
|
|
522
|
+
watcher.on("add", (filepath) => {
|
|
523
|
+
if (this.fileFilter(filepath)) {
|
|
524
|
+
this.watchInfo = { filepath, type: "add" };
|
|
525
|
+
this.updateMockEntry();
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
watcher.on("change", (filepath) => {
|
|
529
|
+
if (this.fileFilter(filepath)) {
|
|
530
|
+
this.watchInfo = { filepath, type: "change" };
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
watcher.on("unlink", async (filepath) => {
|
|
534
|
+
this.watchInfo = { filepath, type: "unlink" };
|
|
535
|
+
this.updateMockEntry();
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
export {
|
|
541
|
+
createMockMiddleware,
|
|
542
|
+
resolvePluginOptions,
|
|
543
|
+
buildMockServer,
|
|
544
|
+
createMockCompiler,
|
|
545
|
+
MockCompiler
|
|
546
|
+
};
|
package/dist/helper.cjs
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true})
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/core/defineMock.ts
|
|
2
|
+
var _utils = require('@pengzhanbo/utils');
|
|
3
|
+
function defineMock(config) {
|
|
4
|
+
return config;
|
|
5
|
+
}
|
|
6
|
+
function createDefineMock(transformer) {
|
|
7
|
+
const define = (config) => {
|
|
8
|
+
if (_utils.isArray.call(void 0, config))
|
|
9
|
+
config = config.map((item) => transformer(item) || item);
|
|
10
|
+
else
|
|
11
|
+
config = transformer(config) || config;
|
|
12
|
+
return config;
|
|
13
|
+
};
|
|
14
|
+
return define;
|
|
15
|
+
}
|
|
2
16
|
|
|
3
17
|
|
|
4
|
-
var _chunkKE2LVHUPcjs = require('./chunk-KE2LVHUP.cjs');
|
|
5
18
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
exports.createDefineMock = _chunkKE2LVHUPcjs.createDefineMock; exports.defineMock = _chunkKE2LVHUPcjs.defineMock;
|
|
19
|
+
exports.createDefineMock = createDefineMock; exports.defineMock = defineMock;
|
package/dist/helper.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile,
|
|
1
|
+
import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-BgpcN3jm.cjs';
|
|
2
|
+
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-BgpcN3jm.cjs';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
5
|
import 'node:stream';
|
package/dist/helper.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile,
|
|
1
|
+
import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-BgpcN3jm.js';
|
|
2
|
+
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-BgpcN3jm.js';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
5
|
import 'node:stream';
|
package/dist/helper.js
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
// src/core/defineMock.ts
|
|
2
|
+
import { isArray } from "@pengzhanbo/utils";
|
|
3
|
+
function defineMock(config) {
|
|
4
|
+
return config;
|
|
5
|
+
}
|
|
6
|
+
function createDefineMock(transformer) {
|
|
7
|
+
const define = (config) => {
|
|
8
|
+
if (isArray(config))
|
|
9
|
+
config = config.map((item) => transformer(item) || item);
|
|
10
|
+
else
|
|
11
|
+
config = transformer(config) || config;
|
|
12
|
+
return config;
|
|
13
|
+
};
|
|
14
|
+
return define;
|
|
15
|
+
}
|
|
5
16
|
export {
|
|
6
17
|
createDefineMock,
|
|
7
18
|
defineMock
|