rspack-plugin-mock 1.2.0 → 1.3.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/README.md +10 -2
- package/README.zh-CN.md +13 -5
- package/dist/{helper.d.cts → helper.d.mts} +60 -44
- package/dist/helper.mjs +4 -0
- package/dist/index.d.mts +13 -0
- package/dist/index.mjs +1 -0
- package/dist/json5-loader.cjs +1 -32
- package/dist/options-BUfaThYe.mjs +43 -0
- package/dist/rsbuild.d.mts +7 -0
- package/dist/rsbuild.mjs +1 -0
- package/dist/{mockWebsocket-DkVHpZCx.d.cts → server-4ETytB7L.d.mts} +44 -40
- package/dist/server.d.mts +3 -0
- package/dist/server.mjs +1 -0
- package/dist/{types-6lajtJPx.d.cts → types-Bt_OTa7I.d.mts} +139 -10
- package/dist/ws-BM06pHhL.mjs +1 -0
- package/package.json +40 -51
- package/dist/chunk-CUT6urMc.cjs +0 -30
- package/dist/helper.cjs +0 -140
- package/dist/helper.d.ts +0 -110
- package/dist/helper.js +0 -136
- package/dist/index.cjs +0 -86
- package/dist/index.d.cts +0 -13
- package/dist/index.d.ts +0 -13
- package/dist/index.js +0 -80
- package/dist/logger-C0V8Cvvd.cjs +0 -800
- package/dist/logger-C48_LmdS.js +0 -710
- package/dist/mockWebsocket-qLVAe-RI.d.ts +0 -85
- package/dist/resolvePluginOptions-Da5uqlBx.cjs +0 -506
- package/dist/resolvePluginOptions-DlkIkykz.js +0 -476
- package/dist/rsbuild.cjs +0 -176
- package/dist/rsbuild.d.cts +0 -7
- package/dist/rsbuild.d.ts +0 -7
- package/dist/rsbuild.js +0 -175
- package/dist/server.cjs +0 -9
- package/dist/server.d.cts +0 -27
- package/dist/server.d.ts +0 -27
- package/dist/server.js +0 -3
- package/dist/types-DPzh7nJq.d.ts +0 -572
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import { LogLevel, MockOptions, MockServerPluginOptions, ServerBuildOption } from "./types-DPzh7nJq.js";
|
|
2
|
-
import EventEmitter from "node:events";
|
|
3
|
-
import { FSWatcher } from "node:fs";
|
|
4
|
-
import { Compiler, RspackOptionsNormalized, RspackPluginInstance } from "@rspack/core";
|
|
5
|
-
import { Server } from "node:http";
|
|
6
|
-
import { Http2SecureServer } from "node:http2";
|
|
7
|
-
|
|
8
|
-
//#region src/core/logger.d.ts
|
|
9
|
-
interface Logger {
|
|
10
|
-
debug: (msg: string, level?: boolean | LogLevel) => void;
|
|
11
|
-
info: (msg: string, level?: boolean | LogLevel) => void;
|
|
12
|
-
warn: (msg: string, level?: boolean | LogLevel) => void;
|
|
13
|
-
error: (msg: string, level?: boolean | LogLevel) => void;
|
|
14
|
-
}
|
|
15
|
-
declare const logLevels: Record<LogLevel, number>;
|
|
16
|
-
declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
|
|
17
|
-
//#endregion
|
|
18
|
-
//#region src/core/mockCompiler.d.ts
|
|
19
|
-
interface MockCompilerOptions {
|
|
20
|
-
alias?: Record<string, false | string | (string | false)[]>;
|
|
21
|
-
plugins: RspackPluginInstance[];
|
|
22
|
-
cwd?: string;
|
|
23
|
-
include: string | string[];
|
|
24
|
-
exclude: string | string[];
|
|
25
|
-
logger: Logger;
|
|
26
|
-
}
|
|
27
|
-
declare function createMockCompiler(options: MockCompilerOptions): MockCompiler;
|
|
28
|
-
declare class MockCompiler extends EventEmitter {
|
|
29
|
-
options: MockCompilerOptions;
|
|
30
|
-
cwd: string;
|
|
31
|
-
mockWatcher: FSWatcher;
|
|
32
|
-
moduleType: "cjs" | "esm";
|
|
33
|
-
entryFile: string;
|
|
34
|
-
private _mockData;
|
|
35
|
-
private fileFilter;
|
|
36
|
-
private watchInfo?;
|
|
37
|
-
compiler?: Compiler | null;
|
|
38
|
-
constructor(options: MockCompilerOptions);
|
|
39
|
-
get mockData(): Record<string, MockOptions>;
|
|
40
|
-
run(): Promise<void>;
|
|
41
|
-
close(): void;
|
|
42
|
-
updateAlias(alias: Record<string, false | string | (string | false)[]>): void;
|
|
43
|
-
updateMockEntry(): Promise<void>;
|
|
44
|
-
getMockFiles(): Promise<string[]>;
|
|
45
|
-
watchMockFiles(): void;
|
|
46
|
-
}
|
|
47
|
-
//#endregion
|
|
48
|
-
//#region src/core/resolvePluginOptions.d.ts
|
|
49
|
-
interface ResolvedCompilerOptions {
|
|
50
|
-
alias: Record<string, false | string | (string | false)[]>;
|
|
51
|
-
proxies: (string | ((pathname: string, req: any) => boolean))[];
|
|
52
|
-
wsProxies: (string | ((pathname: string, req: any) => boolean))[];
|
|
53
|
-
plugins: RspackPluginInstance[];
|
|
54
|
-
context?: string;
|
|
55
|
-
}
|
|
56
|
-
type ResolvePluginOptions = Required<Omit<MockServerPluginOptions, "build">> & ResolvedCompilerOptions & {
|
|
57
|
-
logger: Logger;
|
|
58
|
-
build: false | ServerBuildOption;
|
|
59
|
-
};
|
|
60
|
-
//#endregion
|
|
61
|
-
//#region src/core/mockMiddleware.d.ts
|
|
62
|
-
interface MiddlewareOptions {
|
|
63
|
-
alias: Record<string, false | string | (string | false)[]>;
|
|
64
|
-
proxies: (string | ((pathname: string, req: any) => boolean))[];
|
|
65
|
-
context?: string;
|
|
66
|
-
plugins: RspackPluginInstance[];
|
|
67
|
-
}
|
|
68
|
-
declare function createMockMiddleware(compiler: MockCompiler, options: ResolvePluginOptions): (middlewares: Middleware[], reload?: () => void) => Middleware[];
|
|
69
|
-
type SetupMiddlewaresFn = NonNullable<NonNullable<RspackOptionsNormalized["devServer"]>["setupMiddlewares"]>;
|
|
70
|
-
type Middleware = SetupMiddlewaresFn extends ((middlewares: (infer T)[], devServer: any) => void) ? T : never;
|
|
71
|
-
type Server$1 = SetupMiddlewaresFn extends ((middlewares: any, devServer: infer T) => void) ? T : never;
|
|
72
|
-
//#endregion
|
|
73
|
-
//#region src/core/mockWebsocket.d.ts
|
|
74
|
-
interface MockSocketOptions {
|
|
75
|
-
wsProxies: (string | ((pathname: string, req: any) => boolean))[];
|
|
76
|
-
cookiesOptions: MockServerPluginOptions["cookiesOptions"];
|
|
77
|
-
logger: Logger;
|
|
78
|
-
}
|
|
79
|
-
declare function mockWebSocket(compiler: MockCompiler, httpServer: Server | Http2SecureServer, {
|
|
80
|
-
wsProxies: proxies,
|
|
81
|
-
cookiesOptions,
|
|
82
|
-
logger
|
|
83
|
-
}: MockSocketOptions): void;
|
|
84
|
-
//#endregion
|
|
85
|
-
export { Logger, Middleware, MiddlewareOptions, MockCompiler, MockCompilerOptions, MockSocketOptions, ResolvePluginOptions, Server$1 as Server, createLogger, createMockCompiler, createMockMiddleware, logLevels, mockWebSocket };
|
|
@@ -1,506 +0,0 @@
|
|
|
1
|
-
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
2
|
-
const require_logger = require('./logger-C0V8Cvvd.cjs');
|
|
3
|
-
const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
|
|
4
|
-
const node_events = require_chunk.__toESM(require("node:events"));
|
|
5
|
-
const node_path = require_chunk.__toESM(require("node:path"));
|
|
6
|
-
const node_process = require_chunk.__toESM(require("node:process"));
|
|
7
|
-
const __rollup_pluginutils = require_chunk.__toESM(require("@rollup/pluginutils"));
|
|
8
|
-
const chokidar = require_chunk.__toESM(require("chokidar"));
|
|
9
|
-
const fast_glob = require_chunk.__toESM(require("fast-glob"));
|
|
10
|
-
const node_fs = require_chunk.__toESM(require("node:fs"));
|
|
11
|
-
const node_fs_promises = require_chunk.__toESM(require("node:fs/promises"));
|
|
12
|
-
const picocolors = require_chunk.__toESM(require("picocolors"));
|
|
13
|
-
const node_module = require_chunk.__toESM(require("node:module"));
|
|
14
|
-
const __rspack_core = require_chunk.__toESM(require("@rspack/core"));
|
|
15
|
-
const is_core_module = require_chunk.__toESM(require("is-core-module"));
|
|
16
|
-
const node_url = require_chunk.__toESM(require("node:url"));
|
|
17
|
-
const path_to_regexp = require_chunk.__toESM(require("path-to-regexp"));
|
|
18
|
-
const cors = require_chunk.__toESM(require("cors"));
|
|
19
|
-
|
|
20
|
-
//#region src/core/createRspackCompiler.ts
|
|
21
|
-
const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
22
|
-
function createCompiler(options, callback) {
|
|
23
|
-
const rspackOptions = resolveRspackOptions(options);
|
|
24
|
-
const isWatch = rspackOptions.watch === true;
|
|
25
|
-
async function handler(err, stats) {
|
|
26
|
-
const name = "[rspack:mock]";
|
|
27
|
-
const logError = (...args) => {
|
|
28
|
-
if (stats) stats.compilation.getLogger(name).error(...args);
|
|
29
|
-
else console.error(picocolors.default.red(name), ...args);
|
|
30
|
-
};
|
|
31
|
-
if (err) {
|
|
32
|
-
logError(err.stack || err);
|
|
33
|
-
if ("details" in err) logError(err.details);
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
if (stats?.hasErrors()) {
|
|
37
|
-
const info = stats.toJson();
|
|
38
|
-
logError(info.errors);
|
|
39
|
-
}
|
|
40
|
-
const code = require_logger.vfs.readFileSync("/output.js", "utf-8");
|
|
41
|
-
const externals = [];
|
|
42
|
-
if (!isWatch) {
|
|
43
|
-
const modules = stats?.toJson().modules || [];
|
|
44
|
-
const aliasList = Object.keys(options.alias || {}).map((key) => key.replace(/\$$/g, ""));
|
|
45
|
-
for (const { name: name$1 } of modules) if (name$1?.startsWith("external")) {
|
|
46
|
-
const packageName = normalizePackageName(name$1);
|
|
47
|
-
if (!(0, is_core_module.default)(packageName) && !aliasList.includes(packageName)) externals.push(normalizePackageName(name$1));
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
await callback({
|
|
51
|
-
code,
|
|
52
|
-
externals
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
const compiler = __rspack_core.rspack(rspackOptions, isWatch ? handler : void 0);
|
|
56
|
-
if (compiler) compiler.outputFileSystem = require_logger.vfs;
|
|
57
|
-
if (!isWatch) compiler?.run(async (...args) => {
|
|
58
|
-
await handler(...args);
|
|
59
|
-
compiler.close(() => {});
|
|
60
|
-
});
|
|
61
|
-
return compiler;
|
|
62
|
-
}
|
|
63
|
-
function transformWithRspack(options) {
|
|
64
|
-
return new Promise((resolve) => {
|
|
65
|
-
createCompiler({
|
|
66
|
-
...options,
|
|
67
|
-
watch: false
|
|
68
|
-
}, (result) => {
|
|
69
|
-
resolve(result);
|
|
70
|
-
});
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
function normalizePackageName(name) {
|
|
74
|
-
const filepath = name.replace("external ", "").slice(1, -1);
|
|
75
|
-
const [scope, packageName] = filepath.split("/");
|
|
76
|
-
if (filepath[0] === "@") return `${scope}/${packageName}`;
|
|
77
|
-
return scope;
|
|
78
|
-
}
|
|
79
|
-
function resolveRspackOptions({ cwd, isEsm = true, entryFile, plugins, alias, watch = false }) {
|
|
80
|
-
const targets = ["node >= 18.0.0"];
|
|
81
|
-
if (alias && "@swc/helpers" in alias) delete alias["@swc/helpers"];
|
|
82
|
-
return {
|
|
83
|
-
mode: "production",
|
|
84
|
-
context: cwd,
|
|
85
|
-
entry: entryFile,
|
|
86
|
-
watch,
|
|
87
|
-
target: "node18.0",
|
|
88
|
-
externalsType: isEsm ? "module" : "commonjs2",
|
|
89
|
-
resolve: {
|
|
90
|
-
alias,
|
|
91
|
-
extensions: [
|
|
92
|
-
".js",
|
|
93
|
-
".ts",
|
|
94
|
-
".cjs",
|
|
95
|
-
".mjs",
|
|
96
|
-
".json5",
|
|
97
|
-
".json"
|
|
98
|
-
]
|
|
99
|
-
},
|
|
100
|
-
plugins,
|
|
101
|
-
output: {
|
|
102
|
-
library: { type: !isEsm ? "commonjs2" : "module" },
|
|
103
|
-
filename: "output.js",
|
|
104
|
-
path: "/"
|
|
105
|
-
},
|
|
106
|
-
experiments: { outputModule: isEsm },
|
|
107
|
-
optimization: { minimize: !watch },
|
|
108
|
-
module: { rules: [
|
|
109
|
-
{
|
|
110
|
-
test: /\.json5?$/,
|
|
111
|
-
loader: require$1.resolve("#json5-loader"),
|
|
112
|
-
type: "javascript/auto"
|
|
113
|
-
},
|
|
114
|
-
{
|
|
115
|
-
test: /\.[cm]?js$/,
|
|
116
|
-
use: [{
|
|
117
|
-
loader: "builtin:swc-loader",
|
|
118
|
-
options: {
|
|
119
|
-
jsc: { parser: { syntax: "ecmascript" } },
|
|
120
|
-
env: { targets }
|
|
121
|
-
}
|
|
122
|
-
}]
|
|
123
|
-
},
|
|
124
|
-
{
|
|
125
|
-
test: /\.[cm]?ts$/,
|
|
126
|
-
use: [{
|
|
127
|
-
loader: "builtin:swc-loader",
|
|
128
|
-
options: {
|
|
129
|
-
jsc: { parser: { syntax: "typescript" } },
|
|
130
|
-
env: { targets }
|
|
131
|
-
}
|
|
132
|
-
}]
|
|
133
|
-
}
|
|
134
|
-
] }
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
//#endregion
|
|
139
|
-
//#region src/core/build.ts
|
|
140
|
-
async function buildMockServer(options, outputDir) {
|
|
141
|
-
const entryFile = node_path.default.resolve(node_process.default.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
142
|
-
const mockFileList = await getMockFileList(options);
|
|
143
|
-
await writeMockEntryFile(entryFile, mockFileList, options.cwd);
|
|
144
|
-
const { code, externals } = await transformWithRspack({
|
|
145
|
-
entryFile,
|
|
146
|
-
cwd: options.cwd,
|
|
147
|
-
plugins: options.plugins,
|
|
148
|
-
alias: options.alias
|
|
149
|
-
});
|
|
150
|
-
await node_fs_promises.default.unlink(entryFile);
|
|
151
|
-
const outputList = [
|
|
152
|
-
{
|
|
153
|
-
filename: "mock-data.js",
|
|
154
|
-
source: code
|
|
155
|
-
},
|
|
156
|
-
{
|
|
157
|
-
filename: "index.js",
|
|
158
|
-
source: generatorServerEntryCode(options)
|
|
159
|
-
},
|
|
160
|
-
{
|
|
161
|
-
filename: "package.json",
|
|
162
|
-
source: generatePackageJson(options, externals)
|
|
163
|
-
}
|
|
164
|
-
];
|
|
165
|
-
const dist = node_path.default.resolve(outputDir, options.build.dist);
|
|
166
|
-
options.logger.info(`${picocolors.default.green("✓")} generate mock server in ${picocolors.default.cyan(node_path.default.relative(node_process.default.cwd(), dist))}`);
|
|
167
|
-
if (!node_fs.default.existsSync(dist)) await node_fs_promises.default.mkdir(dist, { recursive: true });
|
|
168
|
-
for (const { filename, source } of outputList) {
|
|
169
|
-
await node_fs_promises.default.writeFile(node_path.default.join(dist, filename), source, "utf8");
|
|
170
|
-
const sourceSize = (source.length / 1024).toFixed(2);
|
|
171
|
-
const space = filename.length < 24 ? " ".repeat(24 - filename.length) : "";
|
|
172
|
-
options.logger.info(` ${picocolors.default.green(filename)}${space}${picocolors.default.bold(picocolors.default.dim(`${sourceSize} kB`))}`);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
function generatePackageJson(options, externals) {
|
|
176
|
-
const deps = getHostDependencies(options.cwd);
|
|
177
|
-
const { name, version } = getPluginPackageInfo();
|
|
178
|
-
const exclude = [
|
|
179
|
-
name,
|
|
180
|
-
"connect",
|
|
181
|
-
"cors"
|
|
182
|
-
];
|
|
183
|
-
const mockPkg = {
|
|
184
|
-
name: "mock-server",
|
|
185
|
-
type: "module",
|
|
186
|
-
scripts: { start: "node index.js" },
|
|
187
|
-
dependencies: {
|
|
188
|
-
connect: "^3.7.0",
|
|
189
|
-
[name]: `^${version}`,
|
|
190
|
-
cors: "^2.8.5"
|
|
191
|
-
}
|
|
192
|
-
};
|
|
193
|
-
externals.filter((dep) => !exclude.includes(dep)).forEach((dep) => {
|
|
194
|
-
mockPkg.dependencies[dep] = deps[dep] || "latest";
|
|
195
|
-
});
|
|
196
|
-
return JSON.stringify(mockPkg, null, 2);
|
|
197
|
-
}
|
|
198
|
-
function generatorServerEntryCode({ proxies, wsPrefix, cookiesOptions, bodyParserOptions, priority, build }) {
|
|
199
|
-
const { serverPort, log } = build;
|
|
200
|
-
return `import { createServer } from 'node:http';
|
|
201
|
-
import connect from 'connect';
|
|
202
|
-
import corsMiddleware from 'cors';
|
|
203
|
-
import {
|
|
204
|
-
baseMiddleware,
|
|
205
|
-
createLogger,
|
|
206
|
-
mockWebSocket,
|
|
207
|
-
transformMockData,
|
|
208
|
-
transformRawData
|
|
209
|
-
} from 'rspack-plugin-mock/server';
|
|
210
|
-
import rawData from './mock-data.js';
|
|
211
|
-
|
|
212
|
-
const app = connect();
|
|
213
|
-
const server = createServer(app);
|
|
214
|
-
const logger = createLogger('mock-server', '${log}');
|
|
215
|
-
const proxies = ${JSON.stringify(proxies)};
|
|
216
|
-
const wsProxies = ${JSON.stringify((0, __pengzhanbo_utils.toArray)(wsPrefix))};
|
|
217
|
-
const cookiesOptions = ${JSON.stringify(cookiesOptions)};
|
|
218
|
-
const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
|
|
219
|
-
const priority = ${JSON.stringify(priority)};
|
|
220
|
-
const mockConfig = {
|
|
221
|
-
mockData: transformMockData(transformRawData(rawData)),
|
|
222
|
-
on: () => {},
|
|
223
|
-
};
|
|
224
|
-
|
|
225
|
-
mockWebSocket(mockConfig, server, { wsProxies, cookiesOptions, logger });
|
|
226
|
-
|
|
227
|
-
app.use(corsMiddleware());
|
|
228
|
-
app.use(baseMiddleware(mockConfig, {
|
|
229
|
-
formidableOptions: { multiples: true },
|
|
230
|
-
proxies,
|
|
231
|
-
priority,
|
|
232
|
-
cookiesOptions,
|
|
233
|
-
bodyParserOptions,
|
|
234
|
-
logger,
|
|
235
|
-
}));
|
|
236
|
-
|
|
237
|
-
server.listen(${serverPort});
|
|
238
|
-
|
|
239
|
-
console.log('listen: http://localhost:${serverPort}');
|
|
240
|
-
`;
|
|
241
|
-
}
|
|
242
|
-
async function getMockFileList({ cwd, include, exclude }) {
|
|
243
|
-
const filter = (0, __rollup_pluginutils.createFilter)(include, exclude, { resolve: false });
|
|
244
|
-
return await (0, fast_glob.default)(include, { cwd }).then((files) => files.filter(filter));
|
|
245
|
-
}
|
|
246
|
-
async function writeMockEntryFile(entryFile, files, cwd) {
|
|
247
|
-
const importers = [];
|
|
248
|
-
const exporters = [];
|
|
249
|
-
for (const [index, filepath] of files.entries()) {
|
|
250
|
-
const file = require_logger.normalizePath(node_path.default.join(cwd, filepath));
|
|
251
|
-
importers.push(`import * as m${index} from '${file}'`);
|
|
252
|
-
exporters.push(`[m${index}, '${filepath}']`);
|
|
253
|
-
}
|
|
254
|
-
const code = `${importers.join("\n")}\n\nexport default [\n ${exporters.join(",\n ")}\n]`;
|
|
255
|
-
const dirname = node_path.default.dirname(entryFile);
|
|
256
|
-
if (!node_fs.default.existsSync(dirname)) await node_fs_promises.default.mkdir(dirname, { recursive: true });
|
|
257
|
-
await node_fs_promises.default.writeFile(entryFile, code, "utf8");
|
|
258
|
-
}
|
|
259
|
-
function getPluginPackageInfo() {
|
|
260
|
-
let pkg = {};
|
|
261
|
-
try {
|
|
262
|
-
const filepath = node_path.default.join(require_logger.packageDir, "../package.json");
|
|
263
|
-
if (node_fs.default.existsSync(filepath)) pkg = JSON.parse(node_fs.default.readFileSync(filepath, "utf8"));
|
|
264
|
-
} catch {}
|
|
265
|
-
return {
|
|
266
|
-
name: pkg.name || "rspack-plugin-mock",
|
|
267
|
-
version: pkg.version || "latest"
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
function getHostDependencies(context) {
|
|
271
|
-
let pkg = {};
|
|
272
|
-
try {
|
|
273
|
-
const content = require_logger.lookupFile(context, ["package.json"]);
|
|
274
|
-
if (content) pkg = JSON.parse(content);
|
|
275
|
-
} catch {}
|
|
276
|
-
return {
|
|
277
|
-
...pkg.dependencies,
|
|
278
|
-
...pkg.devDependencies
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
//#endregion
|
|
283
|
-
//#region src/core/loadFromCode.ts
|
|
284
|
-
async function loadFromCode({ filepath, code, isESM, cwd }) {
|
|
285
|
-
filepath = node_path.default.resolve(cwd, filepath);
|
|
286
|
-
const ext = isESM ? ".mjs" : ".cjs";
|
|
287
|
-
const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
|
|
288
|
-
const file = (0, node_url.pathToFileURL)(filepathTmp).toString();
|
|
289
|
-
await node_fs.promises.writeFile(filepathTmp, code, "utf8");
|
|
290
|
-
try {
|
|
291
|
-
const mod = await import(file);
|
|
292
|
-
return mod.default || mod;
|
|
293
|
-
} finally {
|
|
294
|
-
try {
|
|
295
|
-
node_fs.default.unlinkSync(filepathTmp);
|
|
296
|
-
} catch {}
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
//#endregion
|
|
301
|
-
//#region src/core/mockCompiler.ts
|
|
302
|
-
function createMockCompiler(options) {
|
|
303
|
-
return new MockCompiler(options);
|
|
304
|
-
}
|
|
305
|
-
var MockCompiler = class extends node_events.default {
|
|
306
|
-
cwd;
|
|
307
|
-
mockWatcher;
|
|
308
|
-
moduleType = "cjs";
|
|
309
|
-
entryFile;
|
|
310
|
-
_mockData = {};
|
|
311
|
-
fileFilter;
|
|
312
|
-
watchInfo;
|
|
313
|
-
compiler;
|
|
314
|
-
constructor(options) {
|
|
315
|
-
super();
|
|
316
|
-
this.options = options;
|
|
317
|
-
this.cwd = options.cwd || node_process.default.cwd();
|
|
318
|
-
const { include, exclude } = this.options;
|
|
319
|
-
this.fileFilter = (0, __rollup_pluginutils.createFilter)(include, exclude, { resolve: false });
|
|
320
|
-
try {
|
|
321
|
-
const pkg = require_logger.lookupFile(this.cwd, ["package.json"]);
|
|
322
|
-
this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
|
|
323
|
-
} catch {}
|
|
324
|
-
this.entryFile = node_path.default.resolve(node_process.default.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
325
|
-
}
|
|
326
|
-
get mockData() {
|
|
327
|
-
return this._mockData;
|
|
328
|
-
}
|
|
329
|
-
async run() {
|
|
330
|
-
await this.updateMockEntry();
|
|
331
|
-
this.watchMockFiles();
|
|
332
|
-
const { plugins, alias } = this.options;
|
|
333
|
-
const options = {
|
|
334
|
-
isEsm: this.moduleType === "esm",
|
|
335
|
-
cwd: this.cwd,
|
|
336
|
-
plugins,
|
|
337
|
-
entryFile: this.entryFile,
|
|
338
|
-
alias,
|
|
339
|
-
watch: true
|
|
340
|
-
};
|
|
341
|
-
this.compiler = createCompiler(options, async ({ code }) => {
|
|
342
|
-
try {
|
|
343
|
-
const result = await loadFromCode({
|
|
344
|
-
filepath: "mock.bundle.js",
|
|
345
|
-
code,
|
|
346
|
-
isESM: this.moduleType === "esm",
|
|
347
|
-
cwd: this.cwd
|
|
348
|
-
});
|
|
349
|
-
this._mockData = require_logger.transformMockData(require_logger.transformRawData(result));
|
|
350
|
-
this.emit("update", this.watchInfo || {});
|
|
351
|
-
} catch (e) {
|
|
352
|
-
this.options.logger.error(e.stack || e.message);
|
|
353
|
-
}
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
close() {
|
|
357
|
-
this.mockWatcher.close();
|
|
358
|
-
this.compiler?.close(() => {});
|
|
359
|
-
this.emit("close");
|
|
360
|
-
}
|
|
361
|
-
updateAlias(alias) {
|
|
362
|
-
this.options.alias = {
|
|
363
|
-
...this.options.alias,
|
|
364
|
-
...alias
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
async updateMockEntry() {
|
|
368
|
-
const files = await this.getMockFiles();
|
|
369
|
-
await writeMockEntryFile(this.entryFile, files, this.cwd);
|
|
370
|
-
}
|
|
371
|
-
async getMockFiles() {
|
|
372
|
-
const { include } = this.options;
|
|
373
|
-
const files = await (0, fast_glob.default)(include, { cwd: this.cwd });
|
|
374
|
-
return files.filter(this.fileFilter);
|
|
375
|
-
}
|
|
376
|
-
watchMockFiles() {
|
|
377
|
-
const { include } = this.options;
|
|
378
|
-
const [firstGlob, ...otherGlob] = (0, __pengzhanbo_utils.toArray)(include);
|
|
379
|
-
const watcher = this.mockWatcher = chokidar.default.watch(firstGlob, {
|
|
380
|
-
ignoreInitial: true,
|
|
381
|
-
cwd: this.cwd
|
|
382
|
-
});
|
|
383
|
-
if (otherGlob.length > 0) otherGlob.forEach((glob) => watcher.add(glob));
|
|
384
|
-
watcher.on("add", (filepath) => {
|
|
385
|
-
if (this.fileFilter(filepath)) {
|
|
386
|
-
this.watchInfo = {
|
|
387
|
-
filepath,
|
|
388
|
-
type: "add"
|
|
389
|
-
};
|
|
390
|
-
this.updateMockEntry();
|
|
391
|
-
}
|
|
392
|
-
});
|
|
393
|
-
watcher.on("change", (filepath) => {
|
|
394
|
-
if (this.fileFilter(filepath)) this.watchInfo = {
|
|
395
|
-
filepath,
|
|
396
|
-
type: "change"
|
|
397
|
-
};
|
|
398
|
-
});
|
|
399
|
-
watcher.on("unlink", async (filepath) => {
|
|
400
|
-
this.watchInfo = {
|
|
401
|
-
filepath,
|
|
402
|
-
type: "unlink"
|
|
403
|
-
};
|
|
404
|
-
this.updateMockEntry();
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
};
|
|
408
|
-
|
|
409
|
-
//#endregion
|
|
410
|
-
//#region src/core/mockMiddleware.ts
|
|
411
|
-
function createMockMiddleware(compiler, options) {
|
|
412
|
-
return function mockMiddleware(middlewares, reload) {
|
|
413
|
-
middlewares.unshift(require_logger.baseMiddleware(compiler, options));
|
|
414
|
-
const corsMiddleware = createCorsMiddleware(compiler, options);
|
|
415
|
-
if (corsMiddleware) middlewares.unshift(corsMiddleware);
|
|
416
|
-
if (options.reload) compiler.on("update", () => reload?.());
|
|
417
|
-
return middlewares;
|
|
418
|
-
};
|
|
419
|
-
}
|
|
420
|
-
function createCorsMiddleware(compiler, options) {
|
|
421
|
-
let corsOptions = {};
|
|
422
|
-
const enabled = options.cors !== false;
|
|
423
|
-
if (enabled) corsOptions = {
|
|
424
|
-
...corsOptions,
|
|
425
|
-
...typeof options.cors === "boolean" ? {} : options.cors
|
|
426
|
-
};
|
|
427
|
-
const proxies = options.proxies;
|
|
428
|
-
return !enabled ? void 0 : function(req, res, next) {
|
|
429
|
-
const { pathname } = require_logger.urlParse(req.url);
|
|
430
|
-
if (!pathname || proxies.length === 0 || !proxies.some((context) => require_logger.doesProxyContextMatchUrl(context, req.url, req))) return next();
|
|
431
|
-
const mockData = compiler.mockData;
|
|
432
|
-
const mockUrl = Object.keys(mockData).find((key) => (0, path_to_regexp.pathToRegexp)(key).test(pathname));
|
|
433
|
-
if (!mockUrl) return next();
|
|
434
|
-
(0, cors.default)(corsOptions)(req, res, next);
|
|
435
|
-
};
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
//#endregion
|
|
439
|
-
//#region src/core/resolvePluginOptions.ts
|
|
440
|
-
function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"], exclude = [
|
|
441
|
-
"**/node_modules/**",
|
|
442
|
-
"**/.vscode/**",
|
|
443
|
-
"**/.git/**"
|
|
444
|
-
], reload = false, log = "info", cors: cors$2 = true, formidableOptions = {}, build = false, cookiesOptions = {}, bodyParserOptions = {}, priority = {} }, { alias, context, plugins, proxies }) {
|
|
445
|
-
const logger = require_logger.createLogger("rspack:mock", (0, __pengzhanbo_utils.isBoolean)(log) ? log ? "info" : "error" : log);
|
|
446
|
-
prefix = (0, __pengzhanbo_utils.toArray)(prefix);
|
|
447
|
-
return {
|
|
448
|
-
prefix,
|
|
449
|
-
wsPrefix,
|
|
450
|
-
cwd: cwd || context || node_process.default.cwd(),
|
|
451
|
-
include,
|
|
452
|
-
exclude,
|
|
453
|
-
reload,
|
|
454
|
-
cors: cors$2,
|
|
455
|
-
cookiesOptions,
|
|
456
|
-
log,
|
|
457
|
-
formidableOptions: {
|
|
458
|
-
multiples: true,
|
|
459
|
-
...formidableOptions
|
|
460
|
-
},
|
|
461
|
-
bodyParserOptions,
|
|
462
|
-
priority,
|
|
463
|
-
build: build ? Object.assign({
|
|
464
|
-
serverPort: 8080,
|
|
465
|
-
dist: "mockServer",
|
|
466
|
-
log: "error"
|
|
467
|
-
}, typeof build === "object" ? build : {}) : false,
|
|
468
|
-
alias,
|
|
469
|
-
plugins,
|
|
470
|
-
proxies: [...proxies, ...prefix],
|
|
471
|
-
wsProxies: (0, __pengzhanbo_utils.toArray)(wsPrefix),
|
|
472
|
-
logger
|
|
473
|
-
};
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
//#endregion
|
|
477
|
-
Object.defineProperty(exports, 'MockCompiler', {
|
|
478
|
-
enumerable: true,
|
|
479
|
-
get: function () {
|
|
480
|
-
return MockCompiler;
|
|
481
|
-
}
|
|
482
|
-
});
|
|
483
|
-
Object.defineProperty(exports, 'buildMockServer', {
|
|
484
|
-
enumerable: true,
|
|
485
|
-
get: function () {
|
|
486
|
-
return buildMockServer;
|
|
487
|
-
}
|
|
488
|
-
});
|
|
489
|
-
Object.defineProperty(exports, 'createMockCompiler', {
|
|
490
|
-
enumerable: true,
|
|
491
|
-
get: function () {
|
|
492
|
-
return createMockCompiler;
|
|
493
|
-
}
|
|
494
|
-
});
|
|
495
|
-
Object.defineProperty(exports, 'createMockMiddleware', {
|
|
496
|
-
enumerable: true,
|
|
497
|
-
get: function () {
|
|
498
|
-
return createMockMiddleware;
|
|
499
|
-
}
|
|
500
|
-
});
|
|
501
|
-
Object.defineProperty(exports, 'resolvePluginOptions', {
|
|
502
|
-
enumerable: true,
|
|
503
|
-
get: function () {
|
|
504
|
-
return resolvePluginOptions;
|
|
505
|
-
}
|
|
506
|
-
});
|