rspack-plugin-mock 1.1.0 → 1.2.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/helper.d.ts CHANGED
@@ -1,122 +1,110 @@
1
- import { M as MockHttpItem, a as MockWebsocketItem, b as MockOptions } from './types-Aw0AciTG.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, c as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-Aw0AciTG.js';
3
- import { OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http';
4
- import { Transform } from 'node:stream';
5
- import 'co-body';
6
- import 'cookies';
7
- import 'cors';
8
- import 'formidable';
9
- import 'node:buffer';
10
- import 'ws';
1
+ import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-DPzh7nJq.js";
2
+ import { Transform } from "node:stream";
3
+ import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
4
+
5
+ //#region src/core/defineMock.d.ts
11
6
 
12
7
  /**
13
- * mock config Type helper
14
- *
15
- * mock配置 类型帮助函数
16
- * @param config see config docs:
17
- * {@link https://vite-plugin-mock-dev-server.netlify.app/en/guide/mock-config en-US DOC} |
18
- * {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
19
- *
20
- * @example
21
- * Mock Http Request
22
- * ```ts
23
- * export default defineMock({
24
- * url: '/api/example',
25
- * method: ['GET', 'POST'],
26
- * body: { a: 1 },
27
- * })
28
- * ```
29
- * ```ts
30
- * export default defineMock({
31
- * url: '/api/example',
32
- * method: 'GET',
33
- * body: ({ query }) => ({ a: 1, b: query.b }),
34
- * })
35
- * ```
36
- * @example
37
- * Mock WebSocket
38
- * ```ts
39
- * export default defineMock({
40
- * url: '/socket.io',
41
- * ws: true,
42
- * setup(wss) {
43
- * wss.on('connection', (ws) => {
44
- * ws.on('message', (rawData) => console.log(rawData))
45
- * ws.send('data')
46
- * })
47
- * },
48
- * })
49
- * ```
50
- */
8
+ * mock config Type helper
9
+ *
10
+ * mock配置 类型帮助函数
11
+ * @param config see config docs:
12
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/en/guide/mock-config en-US DOC} |
13
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
14
+ *
15
+ * @example
16
+ * Mock Http Request
17
+ * ```ts
18
+ * export default defineMock({
19
+ * url: '/api/example',
20
+ * method: ['GET', 'POST'],
21
+ * body: { a: 1 },
22
+ * })
23
+ * ```
24
+ * ```ts
25
+ * export default defineMock({
26
+ * url: '/api/example',
27
+ * method: 'GET',
28
+ * body: ({ query }) => ({ a: 1, b: query.b }),
29
+ * })
30
+ * ```
31
+ * @example
32
+ * Mock WebSocket
33
+ * ```ts
34
+ * export default defineMock({
35
+ * url: '/socket.io',
36
+ * ws: true,
37
+ * setup(wss) {
38
+ * wss.on('connection', (ws) => {
39
+ * ws.on('message', (rawData) => console.log(rawData))
40
+ * ws.send('data')
41
+ * })
42
+ * },
43
+ * })
44
+ * ```
45
+ */
51
46
  declare function defineMock(config: MockHttpItem): MockHttpItem;
52
47
  declare function defineMock(config: MockWebsocketItem): MockWebsocketItem;
53
48
  declare function defineMock(config: MockOptions): MockOptions;
54
49
  /**
55
- * Return a custom defineMock function to support preprocessing of mock config.
56
- *
57
- * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
58
- * @param transformer preprocessing function
59
- * @example
60
- * ```ts
61
- * const definePostMock = createDefineMock((mock) => {
62
- * mock.url = '/api/post/' + mock.url
63
- * })
64
- * export default definePostMock({
65
- * url: 'list',
66
- * body: [{ title: '1' }, { title: '2' }],
67
- * })
68
- * ```
69
- */
50
+ * Return a custom defineMock function to support preprocessing of mock config.
51
+ *
52
+ * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
53
+ * @param transformer preprocessing function
54
+ * @example
55
+ * ```ts
56
+ * const definePostMock = createDefineMock((mock) => {
57
+ * mock.url = '/api/post/' + mock.url
58
+ * })
59
+ * export default definePostMock({
60
+ * url: 'list',
61
+ * body: [{ title: '1' }, { title: '2' }],
62
+ * })
63
+ * ```
64
+ */
70
65
  declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;
71
-
72
- type MockData<T = any> = readonly [
73
- /**
74
- * getter
75
- */
76
- () => T,
77
- /**
78
- * setter
79
- */
80
- (val: T | ((val: T) => T | void)) => void
81
- ] & {
82
- value: T;
66
+ //#endregion
67
+ //#region src/core/defineMockData.d.ts
68
+ type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) => void] & {
69
+ value: T;
83
70
  };
84
71
  declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
85
-
72
+ //#endregion
73
+ //#region src/core/sse.d.ts
86
74
  interface SSEMessage {
87
- data?: string | object;
88
- comment?: string;
89
- event?: string;
90
- id?: string;
91
- retry?: number;
75
+ data?: string | object;
76
+ comment?: string;
77
+ event?: string;
78
+ id?: string;
79
+ retry?: number;
92
80
  }
93
81
  interface WriteHeaders {
94
- writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
95
- flushHeaders?: () => void;
82
+ writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
83
+ flushHeaders?: () => void;
96
84
  }
97
85
  type HeaderStream = NodeJS.WritableStream & WriteHeaders;
98
86
  /**
99
- * Transforms "messages" to W3C event stream content.
100
- * See https://html.spec.whatwg.org/multipage/server-sent-events.html
101
- * A message is an object with one or more of the following properties:
102
- * - data (String or object, which gets turned into JSON)
103
- * - event
104
- * - id
105
- * - retry
106
- * - comment
107
- *
108
- * If constructed with a HTTP Request, it will optimise the socket for streaming.
109
- * If this stream is piped to an HTTP Response, it will set appropriate headers.
110
- */
87
+ * Transforms "messages" to W3C event stream content.
88
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
89
+ * A message is an object with one or more of the following properties:
90
+ * - data (String or object, which gets turned into JSON)
91
+ * - event
92
+ * - id
93
+ * - retry
94
+ * - comment
95
+ *
96
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
97
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
98
+ */
111
99
  declare class SSEStream extends Transform {
112
- constructor(req: IncomingMessage);
113
- pipe<T extends HeaderStream>(destination: T, options?: {
114
- end?: boolean;
115
- }): T;
116
- _transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
117
- write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
118
- write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
100
+ constructor(req: IncomingMessage);
101
+ pipe<T extends HeaderStream>(destination: T, options?: {
102
+ end?: boolean;
103
+ }): T;
104
+ _transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
105
+ write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
106
+ write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
119
107
  }
120
108
  declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
121
-
122
- export { type HeaderStream, type MockData, MockHttpItem, MockOptions, MockWebsocketItem, type SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
109
+ //#endregion
110
+ export { BodyParserOptions, ExtraRequest, FormidableFile, HeaderStream, LogLevel, LogType, Method, MockData, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, SSEMessage, ServerBuildOption, WebSocketSetupContext, createDefineMock, createSSEStream, defineMock, defineMockData };
package/dist/helper.js CHANGED
@@ -1,129 +1,136 @@
1
- // src/core/defineMock.ts
2
- import { isArray } from "@pengzhanbo/utils";
1
+ import { deepClone, deepEqual, isArray, isFunction } from "@pengzhanbo/utils";
2
+ import { Transform } from "node:stream";
3
+
4
+ //#region src/core/defineMock.ts
3
5
  function defineMock(config) {
4
- return config;
6
+ return config;
5
7
  }
8
+ /**
9
+ * Return a custom defineMock function to support preprocessing of mock config.
10
+ *
11
+ * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
12
+ * @param transformer preprocessing function
13
+ * @example
14
+ * ```ts
15
+ * const definePostMock = createDefineMock((mock) => {
16
+ * mock.url = '/api/post/' + mock.url
17
+ * })
18
+ * export default definePostMock({
19
+ * url: 'list',
20
+ * body: [{ title: '1' }, { title: '2' }],
21
+ * })
22
+ * ```
23
+ */
6
24
  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;
25
+ const define = (config) => {
26
+ if (isArray(config)) config = config.map((item) => transformer(item) || item);
27
+ else config = transformer(config) || config;
28
+ return config;
29
+ };
30
+ return define;
15
31
  }
16
32
 
17
- // src/core/defineMockData.ts
18
- import { deepClone, deepEqual, isFunction } from "@pengzhanbo/utils";
19
- var mockDataCache = /* @__PURE__ */ new Map();
20
- var responseCache = /* @__PURE__ */ new WeakMap();
21
- var staleInterval = 70;
33
+ //#endregion
34
+ //#region src/core/defineMockData.ts
35
+ const mockDataCache = /* @__PURE__ */ new Map();
36
+ const responseCache = /* @__PURE__ */ new WeakMap();
37
+ const staleInterval = 70;
22
38
  var CacheImpl = class {
23
- value;
24
- // 初始化数据的备份,用于 判断 传入的初始化数据是否发生变更
25
- #initialValue;
26
- #lastUpdate;
27
- constructor(value) {
28
- this.value = value;
29
- this.#initialValue = deepClone(value);
30
- this.#lastUpdate = Date.now();
31
- }
32
- hotUpdate(value) {
33
- if (Date.now() - this.#lastUpdate < staleInterval)
34
- return;
35
- if (!deepEqual(value, this.#initialValue)) {
36
- this.value = value;
37
- this.#initialValue = deepClone(value);
38
- this.#lastUpdate = Date.now();
39
- }
40
- }
39
+ value;
40
+ #initialValue;
41
+ #lastUpdate;
42
+ constructor(value) {
43
+ this.value = value;
44
+ this.#initialValue = deepClone(value);
45
+ this.#lastUpdate = Date.now();
46
+ }
47
+ hotUpdate(value) {
48
+ if (Date.now() - this.#lastUpdate < staleInterval) return;
49
+ if (!deepEqual(value, this.#initialValue)) {
50
+ this.value = value;
51
+ this.#initialValue = deepClone(value);
52
+ this.#lastUpdate = Date.now();
53
+ }
54
+ }
41
55
  };
42
56
  function defineMockData(key, initialData) {
43
- if (!mockDataCache.has(key))
44
- mockDataCache.set(key, new CacheImpl(initialData));
45
- const cache = mockDataCache.get(key);
46
- cache.hotUpdate(initialData);
47
- if (responseCache.has(cache))
48
- return responseCache.get(cache);
49
- const res = [
50
- () => cache.value,
51
- (val) => {
52
- if (isFunction(val))
53
- val = val(cache.value) ?? cache.value;
54
- cache.value = val;
55
- }
56
- ];
57
- Object.defineProperty(res, "value", {
58
- get() {
59
- return cache.value;
60
- },
61
- set(val) {
62
- cache.value = val;
63
- }
64
- });
65
- responseCache.set(cache, res);
66
- return res;
57
+ if (!mockDataCache.has(key)) mockDataCache.set(key, new CacheImpl(initialData));
58
+ const cache = mockDataCache.get(key);
59
+ cache.hotUpdate(initialData);
60
+ if (responseCache.has(cache)) return responseCache.get(cache);
61
+ const res = [() => cache.value, (val) => {
62
+ if (isFunction(val)) val = val(cache.value) ?? cache.value;
63
+ cache.value = val;
64
+ }];
65
+ Object.defineProperty(res, "value", {
66
+ get() {
67
+ return cache.value;
68
+ },
69
+ set(val) {
70
+ cache.value = val;
71
+ }
72
+ });
73
+ responseCache.set(cache, res);
74
+ return res;
67
75
  }
68
76
 
69
- // src/core/sse.ts
70
- import { Transform } from "node:stream";
77
+ //#endregion
78
+ //#region src/core/sse.ts
79
+ /**
80
+ * Transforms "messages" to W3C event stream content.
81
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
82
+ * A message is an object with one or more of the following properties:
83
+ * - data (String or object, which gets turned into JSON)
84
+ * - event
85
+ * - id
86
+ * - retry
87
+ * - comment
88
+ *
89
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
90
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
91
+ */
71
92
  var SSEStream = class extends Transform {
72
- constructor(req) {
73
- super({ objectMode: true });
74
- req.socket.setKeepAlive(true);
75
- req.socket.setNoDelay(true);
76
- req.socket.setTimeout(0);
77
- }
78
- pipe(destination, options) {
79
- if (destination.writeHead) {
80
- destination.writeHead(200, {
81
- "Content-Type": "text/event-stream; charset=utf-8",
82
- "Transfer-Encoding": "identity",
83
- "Cache-Control": "no-cache",
84
- "Connection": "keep-alive"
85
- });
86
- destination.flushHeaders?.();
87
- }
88
- destination.write(":ok\n\n");
89
- return super.pipe(destination, options);
90
- }
91
- _transform(message, encoding, callback) {
92
- if (message.comment)
93
- this.push(`: ${message.comment}
94
- `);
95
- if (message.event)
96
- this.push(`event: ${message.event}
97
- `);
98
- if (message.id)
99
- this.push(`id: ${message.id}
100
- `);
101
- if (message.retry)
102
- this.push(`retry: ${message.retry}
103
- `);
104
- if (message.data)
105
- this.push(dataString(message.data));
106
- this.push("\n");
107
- callback();
108
- }
109
- write(message, ...args) {
110
- return super.write(message, ...args);
111
- }
93
+ constructor(req) {
94
+ super({ objectMode: true });
95
+ req.socket.setKeepAlive(true);
96
+ req.socket.setNoDelay(true);
97
+ req.socket.setTimeout(0);
98
+ }
99
+ pipe(destination, options) {
100
+ if (destination.writeHead) {
101
+ destination.writeHead(200, {
102
+ "Content-Type": "text/event-stream; charset=utf-8",
103
+ "Transfer-Encoding": "identity",
104
+ "Cache-Control": "no-cache",
105
+ "Connection": "keep-alive"
106
+ });
107
+ destination.flushHeaders?.();
108
+ }
109
+ destination.write(":ok\n\n");
110
+ return super.pipe(destination, options);
111
+ }
112
+ _transform(message, encoding, callback) {
113
+ if (message.comment) this.push(`: ${message.comment}\n`);
114
+ if (message.event) this.push(`event: ${message.event}\n`);
115
+ if (message.id) this.push(`id: ${message.id}\n`);
116
+ if (message.retry) this.push(`retry: ${message.retry}\n`);
117
+ if (message.data) this.push(dataString(message.data));
118
+ this.push("\n");
119
+ callback();
120
+ }
121
+ write(message, ...args) {
122
+ return super.write(message, ...args);
123
+ }
112
124
  };
113
125
  function dataString(data) {
114
- if (typeof data === "object")
115
- return dataString(JSON.stringify(data));
116
- return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}
117
- `).join("");
126
+ if (typeof data === "object") return dataString(JSON.stringify(data));
127
+ return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}\n`).join("");
118
128
  }
119
129
  function createSSEStream(req, res) {
120
- const sse = new SSEStream(req);
121
- sse.pipe(res);
122
- return sse;
130
+ const sse = new SSEStream(req);
131
+ sse.pipe(res);
132
+ return sse;
123
133
  }
124
- export {
125
- createDefineMock,
126
- createSSEStream,
127
- defineMock,
128
- defineMockData
129
- };
134
+
135
+ //#endregion
136
+ export { createDefineMock, createSSEStream, defineMock, defineMockData };
package/dist/index.cjs CHANGED
@@ -1,103 +1,86 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
-
4
-
5
-
6
-
7
- var _chunkM7F5AAOFcjs = require('./chunk-M7F5AAOF.cjs');
8
-
9
-
10
-
11
-
12
- var _chunkHTVJXQRMcjs = require('./chunk-HTVJXQRM.cjs');
13
-
14
- // src/rspack.ts
15
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
16
- var _process = require('process'); var _process2 = _interopRequireDefault(_process);
17
- var _utils = require('@pengzhanbo/utils');
18
- var _core = require('@rspack/core'); var _core2 = _interopRequireDefault(_core);
19
- var PLUGIN_NAME = "rspack-plugin-mock";
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 __rspack_core = require_chunk.__toESM(require("@rspack/core"));
8
+
9
+ //#region src/rspack.ts
10
+ const PLUGIN_NAME = "rspack-plugin-mock";
20
11
  var MockServerPlugin = class {
21
- constructor(options = {}) {
22
- this.options = options;
23
- }
24
- apply(compiler) {
25
- const compilerOptions = compiler.options;
26
- const options = resolvePluginOptions2(compiler, this.options);
27
- if (_process2.default.env.NODE_ENV !== "production") {
28
- const mockCompiler = _chunkM7F5AAOFcjs.createMockCompiler.call(void 0, options);
29
- const mockMiddleware = _chunkM7F5AAOFcjs.createMockMiddleware.call(void 0, mockCompiler, options);
30
- const setupMiddlewares = _optionalChain([compilerOptions, 'access', _ => _.devServer, 'optionalAccess', _2 => _2.setupMiddlewares]);
31
- const waitServerForMockWebSocket = _chunkHTVJXQRMcjs.waitingFor.call(void 0, (server) => {
32
- _chunkHTVJXQRMcjs.mockWebSocket.call(void 0, mockCompiler, server, options);
33
- });
34
- compilerOptions.devServer = {
35
- ...compilerOptions.devServer,
36
- setupMiddlewares: (middlewares, devServer) => {
37
- middlewares = _optionalChain([setupMiddlewares, 'optionalCall', _3 => _3(middlewares, devServer)]) || middlewares;
38
- const reload = () => {
39
- if (_optionalChain([devServer, 'access', _4 => _4.webSocketServer, 'optionalAccess', _5 => _5.clients]))
40
- devServer.sendMessage(devServer.webSocketServer.clients, "static-changed");
41
- };
42
- middlewares = mockMiddleware(middlewares, reload) || middlewares;
43
- waitServerForMockWebSocket(() => devServer.server);
44
- return middlewares;
45
- }
46
- };
47
- const wsPrefix = _utils.toArray.call(void 0, options.wsPrefix);
48
- if (_optionalChain([compilerOptions, 'access', _6 => _6.devServer, 'optionalAccess', _7 => _7.proxy, 'optionalAccess', _8 => _8.length])) {
49
- const proxy = compilerOptions.devServer.proxy;
50
- compilerOptions.devServer.proxy = proxy.filter((item) => {
51
- if (typeof item !== "function" && item.ws === true && wsPrefix.length) {
52
- return !_utils.toArray.call(void 0, item.context).filter(_utils.isString).some((context) => wsPrefix.includes(context));
53
- }
54
- return true;
55
- }).map((item) => {
56
- if (typeof item !== "function" && !item.ws) {
57
- const onProxyReq = item.onProxyReq;
58
- item.onProxyReq = (proxyReq, req, ...args) => {
59
- _optionalChain([onProxyReq, 'optionalCall', _9 => _9(proxyReq, req, ...args)]);
60
- _chunkHTVJXQRMcjs.rewriteRequest.call(void 0, proxyReq, req);
61
- };
62
- }
63
- return item;
64
- });
65
- }
66
- compiler.hooks.watchRun.tap(PLUGIN_NAME, () => mockCompiler.run());
67
- compiler.hooks.watchClose.tap(PLUGIN_NAME, () => mockCompiler.close());
68
- } else if (options.build !== false) {
69
- compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => _chunkM7F5AAOFcjs.buildMockServer.call(void 0,
70
- options,
71
- compilerOptions.output.path || _path2.default.resolve(_process2.default.cwd(), "dist")
72
- ));
73
- }
74
- }
12
+ constructor(options = {}) {
13
+ this.options = options;
14
+ }
15
+ apply(compiler) {
16
+ const compilerOptions = compiler.options;
17
+ const options = resolvePluginOptions$1(compiler, this.options);
18
+ if (node_process.default.env.NODE_ENV !== "production") {
19
+ const mockCompiler = require_resolvePluginOptions.createMockCompiler(options);
20
+ const mockMiddleware = require_resolvePluginOptions.createMockMiddleware(mockCompiler, options);
21
+ const setupMiddlewares = compilerOptions.devServer?.setupMiddlewares;
22
+ const waitServerForMockWebSocket = require_logger.waitingFor((server) => {
23
+ require_logger.mockWebSocket(mockCompiler, server, options);
24
+ });
25
+ compilerOptions.devServer = {
26
+ ...compilerOptions.devServer,
27
+ setupMiddlewares: (middlewares, devServer) => {
28
+ middlewares = setupMiddlewares?.(middlewares, devServer) || middlewares;
29
+ const reload = () => {
30
+ if (devServer.webSocketServer?.clients) devServer.sendMessage(devServer.webSocketServer.clients, "static-changed");
31
+ };
32
+ middlewares = mockMiddleware(middlewares, reload) || middlewares;
33
+ /**
34
+ * @rspack/dev-server -> webpack-dev-server 中, setupMiddlewares 优先于 createServer
35
+ * 执行,需要等待 server 启动后再注入 mock websocket
36
+ */
37
+ waitServerForMockWebSocket(() => devServer.server);
38
+ return middlewares;
39
+ }
40
+ };
41
+ const wsPrefix = (0, __pengzhanbo_utils.toArray)(options.wsPrefix);
42
+ if (compilerOptions.devServer?.proxy?.length) {
43
+ const proxy = compilerOptions.devServer.proxy;
44
+ compilerOptions.devServer.proxy = proxy.filter((item) => {
45
+ if (typeof item !== "function" && item.ws === true && wsPrefix.length) return !(0, __pengzhanbo_utils.toArray)(item.context).filter(__pengzhanbo_utils.isString).some((context) => wsPrefix.includes(context));
46
+ return true;
47
+ }).map((item) => {
48
+ if (typeof item !== "function" && !item.ws) {
49
+ const onProxyReq = item.onProxyReq;
50
+ item.onProxyReq = (proxyReq, req, ...args) => {
51
+ onProxyReq?.(proxyReq, req, ...args);
52
+ require_logger.rewriteRequest(proxyReq, req);
53
+ };
54
+ }
55
+ return item;
56
+ });
57
+ }
58
+ compiler.hooks.watchRun.tap(PLUGIN_NAME, () => mockCompiler.run());
59
+ compiler.hooks.watchClose.tap(PLUGIN_NAME, () => mockCompiler.close());
60
+ } else if (options.build !== false) compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => require_resolvePluginOptions.buildMockServer(options, compilerOptions.output.path || node_path.default.resolve(node_process.default.cwd(), "dist")));
61
+ }
75
62
  };
76
- function resolvePluginOptions2(compiler, options) {
77
- const compilerOptions = compiler.options;
78
- const alias = _optionalChain([compilerOptions, 'access', _10 => _10.resolve, 'optionalAccess', _11 => _11.alias]) || {};
79
- const context = compilerOptions.context;
80
- const definePluginInstance = _optionalChain([compilerOptions, 'access', _12 => _12.plugins, 'optionalAccess', _13 => _13.find, 'call', _14 => _14(
81
- (plugin) => plugin instanceof _core2.default.DefinePlugin
82
- )]);
83
- const proxies = (_optionalChain([compilerOptions, 'access', _15 => _15.devServer, 'optionalAccess', _16 => _16.proxy]) || []).flatMap((item) => {
84
- if (typeof item !== "function" && item.context && !item.ws) {
85
- return item.context;
86
- }
87
- return [];
88
- });
89
- return _chunkM7F5AAOFcjs.resolvePluginOptions.call(void 0, options, {
90
- alias,
91
- context,
92
- plugins: _utils.toArray.call(void 0, definePluginInstance),
93
- proxies
94
- });
63
+ function resolvePluginOptions$1(compiler, options = {}) {
64
+ const compilerOptions = compiler.options;
65
+ const alias = compilerOptions.resolve?.alias || {};
66
+ const context = compilerOptions.context;
67
+ const definePluginInstance = compilerOptions.plugins?.find((plugin) => plugin instanceof __rspack_core.default.DefinePlugin);
68
+ const proxies = (compilerOptions.devServer?.proxy || []).flatMap((item) => {
69
+ if (typeof item !== "function" && item.context && !item.ws) return item.context;
70
+ return [];
71
+ });
72
+ return require_resolvePluginOptions.resolvePluginOptions(options, {
73
+ alias,
74
+ context,
75
+ plugins: (0, __pengzhanbo_utils.toArray)(definePluginInstance),
76
+ proxies
77
+ });
95
78
  }
96
79
 
97
-
98
-
99
-
100
-
101
-
102
-
103
- exports.MockCompiler = _chunkM7F5AAOFcjs.MockCompiler; exports.MockServerPlugin = MockServerPlugin; exports.createMockCompiler = _chunkM7F5AAOFcjs.createMockCompiler; exports.createMockMiddleware = _chunkM7F5AAOFcjs.createMockMiddleware; exports.mockWebSocket = _chunkHTVJXQRMcjs.mockWebSocket; exports.resolvePluginOptions = resolvePluginOptions2;
80
+ //#endregion
81
+ exports.MockCompiler = require_resolvePluginOptions.MockCompiler;
82
+ exports.MockServerPlugin = MockServerPlugin;
83
+ exports.createMockCompiler = require_resolvePluginOptions.createMockCompiler;
84
+ exports.createMockMiddleware = require_resolvePluginOptions.createMockMiddleware;
85
+ exports.mockWebSocket = require_logger.mockWebSocket;
86
+ exports.resolvePluginOptions = resolvePluginOptions$1;