rspack-plugin-mock 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rsbuild.cjs DELETED
@@ -1,176 +0,0 @@
1
- const require_chunk = require('./chunk-CUT6urMc.cjs');
2
- const require_logger = require('./logger-C0V8Cvvd.cjs');
3
- const require_resolvePluginOptions = require('./resolvePluginOptions-Da5uqlBx.cjs');
4
- const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
5
- const node_path = require_chunk.__toESM(require("node:path"));
6
- const node_process = require_chunk.__toESM(require("node:process"));
7
- const picocolors = require_chunk.__toESM(require("picocolors"));
8
- const __rspack_core = require_chunk.__toESM(require("@rspack/core"));
9
- const node_http = require_chunk.__toESM(require("node:http"));
10
- const portfinder = require_chunk.__toESM(require("portfinder"));
11
-
12
- //#region src/rsbuild.ts
13
- function pluginMockServer(options = {}) {
14
- return {
15
- name: "plugin-mock-server",
16
- setup(api) {
17
- const rsbuildConfig = api.getRsbuildConfig();
18
- const resolvedOptions = require_resolvePluginOptions.resolvePluginOptions(options, {
19
- proxies: resolveConfigProxies(rsbuildConfig),
20
- alias: {},
21
- context: api.context.rootPath,
22
- plugins: [new __rspack_core.default.DefinePlugin(rsbuildConfig.source?.define || {})]
23
- });
24
- if (node_process.default.env.NODE_ENV === "production") {
25
- if (resolvedOptions.build) api.onAfterBuild(async () => {
26
- const config = api.getNormalizedConfig();
27
- await require_resolvePluginOptions.buildMockServer(resolvedOptions, node_path.default.resolve(node_process.default.cwd(), config.output.distPath.root || "dist"));
28
- });
29
- return;
30
- }
31
- const mockCompiler = require_resolvePluginOptions.createMockCompiler(resolvedOptions);
32
- api.modifyRsbuildConfig((config) => {
33
- updateServerProxyConfigByHttpMock(config);
34
- const mockMiddleware = require_resolvePluginOptions.createMockMiddleware(mockCompiler, resolvedOptions);
35
- config.dev ??= {};
36
- config.dev.setupMiddlewares ??= [];
37
- config.dev.setupMiddlewares.push((middlewares, server$1) => {
38
- mockMiddleware(middlewares, () => server$1.sockWrite("static-changed"));
39
- });
40
- });
41
- let port = 3079;
42
- const shouldMockWs = (0, __pengzhanbo_utils.toArray)(resolvedOptions.wsPrefix).length > 0;
43
- if (shouldMockWs) api.modifyRsbuildConfig(async (config) => {
44
- const defaultPort = (config.server?.port || port) + 1;
45
- port = await (0, portfinder.getPortPromise)({ port: defaultPort });
46
- updateServerProxyConfigByWSMock(config, options.wsPrefix || [], port);
47
- });
48
- let server;
49
- function startMockServer() {
50
- mockCompiler.run();
51
- if (shouldMockWs) {
52
- server = (0, node_http.createServer)();
53
- require_logger.mockWebSocket(mockCompiler, server, resolvedOptions);
54
- server.listen(port);
55
- }
56
- }
57
- function close() {
58
- mockCompiler.close();
59
- server?.close();
60
- }
61
- api.onAfterCreateCompiler(({ compiler }) => {
62
- if ("compilers" in compiler) compiler.compilers.forEach((compiler$1) => {
63
- mockCompiler.updateAlias(compiler$1.options.resolve?.alias || {});
64
- });
65
- else mockCompiler.updateAlias(compiler.options.resolve?.alias || {});
66
- });
67
- api.onAfterStartDevServer(startMockServer);
68
- api.onAfterStartProdServer(startMockServer);
69
- api.onExit(close);
70
- }
71
- };
72
- }
73
- function onProxyError(err, _req, res) {
74
- console.error(picocolors.default.red(err?.stack || err.message));
75
- res.statusCode = 500;
76
- res.end();
77
- }
78
- function updateServerProxyConfigByHttpMock(config) {
79
- if (!config.server?.proxy) return;
80
- if ((0, __pengzhanbo_utils.isArray)(config.server.proxy)) config.server.proxy = config.server.proxy.map((item) => {
81
- if (typeof item !== "function" && !item.ws) {
82
- const onProxyReq = item.onProxyReq;
83
- const onError = item.onError;
84
- return {
85
- ...item,
86
- onError: onError || onProxyError,
87
- onProxyReq: (proxyReq, req, ...args) => {
88
- onProxyReq?.(proxyReq, req, ...args);
89
- require_logger.rewriteRequest(proxyReq, req);
90
- }
91
- };
92
- }
93
- return item;
94
- });
95
- else if ("target" in config.server.proxy) {
96
- const onProxyReq = config.server.proxy.onProxyReq;
97
- config.server.proxy.onProxyReq = (proxyReq, req, ...args) => {
98
- onProxyReq?.(proxyReq, req, ...args);
99
- require_logger.rewriteRequest(proxyReq, req);
100
- };
101
- config.server.proxy.onError ??= onProxyError;
102
- } else if (config.server.proxy) {
103
- const proxy = config.server.proxy;
104
- Object.keys(proxy).forEach((key) => {
105
- const target = proxy[key];
106
- const options = typeof target === "string" ? { target } : target;
107
- if (options.ws) return;
108
- const { onProxyReq, onError,...rest } = options;
109
- proxy[key] = {
110
- ...rest,
111
- onProxyReq: (proxyReq, req, ...args) => {
112
- onProxyReq?.(proxyReq, req, ...args);
113
- require_logger.rewriteRequest(proxyReq, req);
114
- },
115
- onError: onError || onProxyError
116
- };
117
- });
118
- }
119
- }
120
- function updateServerProxyConfigByWSMock(config, wsPrefix, port) {
121
- config.server ??= {};
122
- const proxy = config.server.proxy ??= {};
123
- const wsTarget = `ws://localhost:${port}`;
124
- const prefix = (0, __pengzhanbo_utils.toArray)(wsPrefix);
125
- const has = (context) => typeof context === "string" && prefix.includes(context);
126
- const used = /* @__PURE__ */ new Set();
127
- function updateProxy(item) {
128
- if ((0, __pengzhanbo_utils.isArray)(item.context)) item.context = item.context.filter(has);
129
- else if (has(item.context)) {
130
- used.add(item.context);
131
- item.target = wsTarget;
132
- }
133
- }
134
- if ((0, __pengzhanbo_utils.isArray)(proxy)) {
135
- for (const item of proxy) if (typeof item !== "function" && item.context && item.ws) updateProxy(item);
136
- prefix.filter((context) => !used.has(context)).forEach((context) => proxy.push({
137
- context,
138
- target: wsTarget
139
- }));
140
- } else if ("target" in proxy) {
141
- if (proxy.ws) {
142
- updateProxy(proxy);
143
- const list = config.server.proxy = [proxy];
144
- prefix.filter((context) => !used.has(context)).forEach((context) => list.push({
145
- context,
146
- target: wsTarget
147
- }));
148
- }
149
- } else {
150
- Object.entries(proxy).forEach(([, opt]) => {
151
- if (typeof opt !== "string" && opt.ws) updateProxy(opt);
152
- });
153
- prefix.filter((context) => !used.has(context)).forEach((context) => {
154
- proxy[context] = {
155
- target: wsTarget,
156
- ws: true
157
- };
158
- });
159
- }
160
- }
161
- function resolveConfigProxies(config) {
162
- config.server ??= {};
163
- const proxy = config.server.proxy ??= {};
164
- const proxies = [];
165
- if ((0, __pengzhanbo_utils.isArray)(proxy)) {
166
- for (const item of proxy) if (typeof item !== "function" && item.context && !item.ws) proxies.push(...(0, __pengzhanbo_utils.toArray)(item.context));
167
- } else if ("target" in proxy) {
168
- if (!proxy.ws) proxies.push(...(0, __pengzhanbo_utils.toArray)(proxy.context));
169
- } else Object.entries(proxy).forEach(([context, opt]) => {
170
- if (typeof opt === "string" || !opt.ws) proxies.push(context);
171
- });
172
- return proxies;
173
- }
174
-
175
- //#endregion
176
- exports.pluginMockServer = pluginMockServer;
@@ -1,7 +0,0 @@
1
- import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-6lajtJPx.cjs";
2
- import { RsbuildPlugin } from "@rsbuild/core";
3
-
4
- //#region src/rsbuild.d.ts
5
- declare function pluginMockServer(options?: MockServerPluginOptions): RsbuildPlugin;
6
- //#endregion
7
- export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext, pluginMockServer };
package/dist/server.cjs DELETED
@@ -1,9 +0,0 @@
1
- const require_logger = require('./logger-C0V8Cvvd.cjs');
2
-
3
- exports.baseMiddleware = require_logger.baseMiddleware;
4
- exports.createLogger = require_logger.createLogger;
5
- exports.logLevels = require_logger.logLevels;
6
- exports.mockWebSocket = require_logger.mockWebSocket;
7
- exports.sortByValidator = require_logger.sortByValidator;
8
- exports.transformMockData = require_logger.transformMockData;
9
- exports.transformRawData = require_logger.transformRawData;
package/dist/server.d.cts DELETED
@@ -1,27 +0,0 @@
1
- import { MockHttpItem, MockOptions, MockServerPluginOptions, MockWebsocketItem } from "./types-6lajtJPx.cjs";
2
- import { Logger, Middleware, MockCompiler, MockSocketOptions, createLogger, logLevels, mockWebSocket } from "./mockWebsocket-DkVHpZCx.cjs";
3
-
4
- //#region src/core/baseMiddleware.d.ts
5
- interface BaseMiddlewareOptions {
6
- formidableOptions: MockServerPluginOptions["formidableOptions"];
7
- cookiesOptions: MockServerPluginOptions["cookiesOptions"];
8
- bodyParserOptions: MockServerPluginOptions["bodyParserOptions"];
9
- proxies: (string | ((pathname: string, req: any) => boolean))[];
10
- logger: Logger;
11
- priority: MockServerPluginOptions["priority"];
12
- }
13
- declare function baseMiddleware(compiler: MockCompiler, {
14
- formidableOptions,
15
- bodyParserOptions,
16
- proxies,
17
- cookiesOptions,
18
- logger,
19
- priority
20
- }: BaseMiddlewareOptions): Middleware;
21
- //#endregion
22
- //#region src/core/transform.d.ts
23
- declare function transformRawData(rawData: (readonly [any, string])[]): (MockHttpItem | MockWebsocketItem | MockOptions)[];
24
- declare function transformMockData(mockList: (MockHttpItem | MockWebsocketItem | MockOptions)[]): Record<string, MockOptions>;
25
- declare function sortByValidator(mocks: MockOptions): (MockHttpItem | MockWebsocketItem)[];
26
- //#endregion
27
- export { BaseMiddlewareOptions, Logger, MockSocketOptions, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData };