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/README.md CHANGED
@@ -10,18 +10,23 @@ Implement a mock-dev-server in `rspack` and `rsbuild` that is fully consistent w
10
10
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/rspack-plugin-mock/peer/@rspack/core?style=flat-square&colorA=564341&colorB=EDED91&label=rspack">
11
11
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/rspack-plugin-mock/peer/@rsbuild/core?style=flat-square&colorA=564341&colorB=EDED91&label=rsbuild">
12
12
  <img alt="npm" src="https://img.shields.io/npm/dm/rspack-plugin-mock?style=flat-square&colorA=564341&colorB=EDED91">
13
- <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/rspack-plugin-mock/lint.yml?style=flat-square&colorA=564341&colorB=EDED91">
13
+ <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/rspack-plugin-mock/release.yaml?style=flat-square&colorA=564341&colorB=EDED91">
14
14
  </p>
15
15
 
16
16
  <p align="center">
17
17
  <span>English</span> | <a href="./README.zh-CN.md">简体中文</a>
18
18
  </p>
19
19
 
20
+ > [!IMPORTANT]
21
+ > Starting from version 2.0 of the plugin, only `rspack@2.x` and `rsbuild@2.x` versions are supported.
22
+ >
23
+ > If you are using `rspack@1.x` or `rsbuild@1.x`, please use version `rspack-plugin-mock@1.x`.
24
+
20
25
  ## Features
21
26
 
22
27
  - ⚡️ Lightweight, Flexible, Fast.
23
28
  - 🧲 Not injection-based, non-intrusive to client code.
24
- - 💡 ESModule/commonjs.
29
+ - 💡 Pure ESModule
25
30
  - 🦾 Typescript.
26
31
  - 🔥 HMR
27
32
  - 🏷 Support `.[cm]?js`/ `.ts` /`.json` / `.json5`.
@@ -235,10 +240,18 @@ export default defineMock({
235
240
 
236
241
  Configure the matching context for `include` and `exclude`.
237
242
 
243
+ ### options.dir
244
+
245
+ - **Type:** `string`
246
+ - **Default:** `mock` (relative to [`options.cwd`](#optionscwd))
247
+ - **Details:**
248
+
249
+ Configure the directory where mock files are located
250
+
238
251
  ### options.include
239
252
 
240
253
  - **Type:** `string | string[]`
241
- - **Default:** `['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']`
254
+ - **Default:** `['**/*.mock.{js,ts,cjs,mjs,json,json5}']` (relative to [`options.dir`](#optionsdir))
242
255
  - **Details:**
243
256
 
244
257
  glob string matching mock includes files. see [picomatch](https://github.com/micromatch/picomatch#globbing-features)
@@ -246,7 +259,7 @@ export default defineMock({
246
259
  ### options.exclude
247
260
 
248
261
  - **Type:** `string | string[]`
249
- - **Default:** `['**/node_modules/**', '**/.vscode/**', '**/.git/**']`
262
+ - **Default:** `[]` (relative to [`options.dir`](#optionsdir))
250
263
  - **Details:**
251
264
 
252
265
  glob string matching mock excluded files. see [picomatch](https://github.com/micromatch/picomatch#globbing-features)
package/README.zh-CN.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  在 [Rspack](https://rspack.dev) and [Rsbuild](https://rsbuild.dev) 中注入 API mock 服务。
4
4
 
5
- 在 `rspack` 和 `rsbuild` 中实现一个与 [vite-plugin-mock-dev-server](https://github.com/pengzhanbo/vite-plugin-mock-dev-server) 完全一致的模拟开发服务器。
5
+ 在 `rspack` 和 `rsbuild` 中实现与 [vite-plugin-mock-dev-server](https://github.com/pengzhanbo/vite-plugin-mock-dev-server) 完全一致的模拟开发服务。
6
6
 
7
7
  <p align="center">
8
8
  <a href="https://www.npmjs.com/package/rspack-plugin-mock"><img alt="npm" src="https://img.shields.io/npm/v/rspack-plugin-mock?style=flat-square&colorA=564341&colorB=EDED91"></a>
@@ -10,18 +10,23 @@
10
10
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/rspack-plugin-mock/peer/@rspack/core?style=flat-square&colorA=564341&colorB=EDED91&label=rspack">
11
11
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/rspack-plugin-mock/peer/@rsbuild/core?style=flat-square&colorA=564341&colorB=EDED91&label=rsbuild">
12
12
  <img alt="npm" src="https://img.shields.io/npm/dm/rspack-plugin-mock?style=flat-square&colorA=564341&colorB=EDED91">
13
- <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/rspack-plugin-mock/lint.yml?style=flat-square&colorA=564341&colorB=EDED91">
13
+ <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/rspack-plugin-mock/release.yaml?style=flat-square&colorA=564341&colorB=EDED91">
14
14
  </p>
15
15
 
16
16
  <p align="center">
17
17
  <a href="./README.md">English</a> | <span>简体中文</span>
18
18
  </p>
19
19
 
20
+ > [!IMPORTANT]
21
+ > 从插件 2.0 版本开始,仅支持 `rspack@2.x` 版本 和 `rsbuild@2.x` 版本.
22
+ >
23
+ > 如果您使用的是 `rspack@1.x` 或 `rsbuild@1.x` 版本,请使用 `rspack-plugin-mock@1.x` 版本.
24
+
20
25
  ## 特性
21
26
 
22
27
  - ⚡️ 轻量,灵活,快速
23
28
  - 🧲 非注入式,对客户端代码无侵入
24
- - 💡 ESModule/commonjs
29
+ - 💡 ESModule
25
30
  - 🦾 Typescript
26
31
  - 🔥 热更新
27
32
  - 🏷 支持 `.[cm]?js`/ `.ts` / `json` / `json5` 编写 mock 数据
@@ -31,8 +36,8 @@
31
36
  - ⚙️ 随意开启或关闭对某个接口的 mock配置
32
37
  - 📀 支持多种响应体数据类型,包括 `text/json/buffer/stream`.
33
38
  - ⚖️ rspack 中使用 `devServer.proxy` 配置, rsbuild 中使用 `server.proxy` 配置
34
- - 🍕 支持在 mock文件中使用 `define`配置
35
- - ⚓️ 支持在 mock文件中使用 `resolve.alias` 路径别名
39
+ - 🍕 支持在 mock 文件中使用 `define`配置
40
+ - ⚓️ 支持在 mock 文件中使用 `resolve.alias` 路径别名
36
41
  - 📤 支持 multipart 类型,模拟文件上传
37
42
  - 📥 支持模拟文件下载
38
43
  - ⚜️ 支持模拟 `WebSocket` 和 `Server-Sent Events`
@@ -232,10 +237,18 @@ export default defineMock({
232
237
 
233
238
  配置 `include` 和 `exclude` 的匹配上下文。
234
239
 
240
+ ### options.dir
241
+
242
+ - **类型:** `string`
243
+ - **默认值:** `mock` (相对于 [`options.cwd`](#optionscwd))
244
+ - **详情:**
245
+
246
+ 配置 mock 包的输出目录,相对于 [`options.cwd`](#optionscwd)
247
+
235
248
  ### options.include
236
249
 
237
250
  - **类型:** `string | string[]`
238
- - **默认值:** `['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']`
251
+ - **默认值:** `[**/*.mock.{js,ts,cjs,mjs,json,json5}']` (相对于 [`options.dir`](#optionsdir))
239
252
  - **详情:**
240
253
 
241
254
  glob 字符串匹配 mock 包含的文件。 查看 [picomatch](https://github.com/micromatch/picomatch#globbing-features)
@@ -243,7 +256,7 @@ export default defineMock({
243
256
  ### options.exclude
244
257
 
245
258
  - **类型:** `string | string[]`
246
- - **默认值:** `['**/node_modules/**', '**/.vscode/**', '**/.git/**']`
259
+ - **默认值:** `[]` (相对于 [`options.dir`](#optionsdir))
247
260
  - **详情:**
248
261
 
249
262
  glob 字符串匹配 mock 排除的文件。 查看 [picomatch](https://github.com/micromatch/picomatch#globbing-features)
package/dist/helper.d.ts CHANGED
@@ -1,16 +1,69 @@
1
- import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-DPzh7nJq.js";
1
+ import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-GT6M6WuI.js";
2
2
  import { Transform } from "node:stream";
3
3
  import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
4
4
 
5
- //#region src/core/defineMock.d.ts
6
-
5
+ //#region src/helper/createSSEStream.d.ts
6
+ interface SSEMessage {
7
+ data?: string | object;
8
+ comment?: string;
9
+ event?: string;
10
+ id?: string;
11
+ retry?: number;
12
+ }
13
+ interface WriteHeaders {
14
+ writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
15
+ flushHeaders?: () => void;
16
+ }
17
+ type HeaderStream = NodeJS.WritableStream & WriteHeaders;
18
+ /**
19
+ * Transforms "messages" to W3C event stream content.
20
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
21
+ * A message is an object with one or more of the following properties:
22
+ * - data (String or object, which gets turned into JSON)
23
+ * - event
24
+ * - id
25
+ * - retry
26
+ * - comment
27
+ *
28
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
29
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
30
+ */
31
+ declare class SSEStream extends Transform {
32
+ constructor(req: IncomingMessage);
33
+ pipe<T extends HeaderStream>(destination: T, options?: {
34
+ end?: boolean;
35
+ }): T;
36
+ _transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
37
+ write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
38
+ write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
39
+ destroy(error?: Error): this;
40
+ }
41
+ /**
42
+ * 创建一个 Server-sent events 写入流,用于支持模拟 EventSource
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
47
+ *
48
+ * export default defineMock({
49
+ * url: '/api',
50
+ * response: (req, res) => {
51
+ * const sse = createSSEStream(req, res)
52
+ * sse.write({ event: 'message', data: { message: 'hello world' } })
53
+ * }
54
+ * })
55
+ * ```
56
+ */
57
+ declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
58
+ //#endregion
59
+ //#region src/helper/defineMock.d.ts
7
60
  /**
8
61
  * mock config Type helper
9
62
  *
10
63
  * mock配置 类型帮助函数
11
64
  * @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}
65
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config en-US DOC} |
66
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/zh/guide/mock-config zh-CN DOC}
14
67
  *
15
68
  * @example
16
69
  * Mock Http Request
@@ -64,47 +117,10 @@ declare function defineMock(config: MockOptions): MockOptions;
64
117
  */
65
118
  declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;
66
119
  //#endregion
67
- //#region src/core/defineMockData.d.ts
120
+ //#region src/helper/defineMockData.d.ts
68
121
  type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) => void] & {
69
122
  value: T;
70
123
  };
71
124
  declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
72
125
  //#endregion
73
- //#region src/core/sse.d.ts
74
- interface SSEMessage {
75
- data?: string | object;
76
- comment?: string;
77
- event?: string;
78
- id?: string;
79
- retry?: number;
80
- }
81
- interface WriteHeaders {
82
- writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
83
- flushHeaders?: () => void;
84
- }
85
- type HeaderStream = NodeJS.WritableStream & WriteHeaders;
86
- /**
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
- */
99
- declare class SSEStream extends Transform {
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;
107
- }
108
- declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
109
- //#endregion
110
126
  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,7 +1,87 @@
1
- import { deepClone, deepEqual, isArray, isFunction } from "@pengzhanbo/utils";
2
1
  import { Transform } from "node:stream";
3
-
4
- //#region src/core/defineMock.ts
2
+ import { deepClone, deepEqual, isArray, isFunction } from "@pengzhanbo/utils";
3
+ //#region src/helper/createSSEStream.ts
4
+ /**
5
+ * Transforms "messages" to W3C event stream content.
6
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
7
+ * A message is an object with one or more of the following properties:
8
+ * - data (String or object, which gets turned into JSON)
9
+ * - event
10
+ * - id
11
+ * - retry
12
+ * - comment
13
+ *
14
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
15
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
16
+ */
17
+ var SSEStream = class extends Transform {
18
+ constructor(req) {
19
+ super({ objectMode: true });
20
+ req.socket.setKeepAlive(true);
21
+ req.socket.setNoDelay(true);
22
+ req.socket.setTimeout(0);
23
+ }
24
+ pipe(destination, options) {
25
+ if (destination.writeHead) {
26
+ destination.writeHead(200, {
27
+ "Content-Type": "text/event-stream; charset=utf-8",
28
+ "Transfer-Encoding": "identity",
29
+ "Cache-Control": "no-cache",
30
+ "Connection": "keep-alive"
31
+ });
32
+ destination.flushHeaders?.();
33
+ }
34
+ destination.write(":ok\n\n");
35
+ return super.pipe(destination, options);
36
+ }
37
+ _transform(message, encoding, callback) {
38
+ if (message.comment) this.push(`: ${message.comment}\n`);
39
+ if (message.event) this.push(`event: ${message.event}\n`);
40
+ if (message.id) this.push(`id: ${message.id}\n`);
41
+ if (message.retry) this.push(`retry: ${message.retry}\n`);
42
+ if (message.data) this.push(dataString(message.data));
43
+ this.push("\n");
44
+ callback();
45
+ }
46
+ write(message, ...args) {
47
+ return super.write(message, ...args);
48
+ }
49
+ destroy(error) {
50
+ if (error) this.write({
51
+ event: "error",
52
+ data: error.message
53
+ });
54
+ this.end();
55
+ return this;
56
+ }
57
+ };
58
+ function dataString(data) {
59
+ if (typeof data === "object") return dataString(JSON.stringify(data));
60
+ return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}\n`).join("");
61
+ }
62
+ /**
63
+ * 创建一个 Server-sent events 写入流,用于支持模拟 EventSource
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
68
+ *
69
+ * export default defineMock({
70
+ * url: '/api',
71
+ * response: (req, res) => {
72
+ * const sse = createSSEStream(req, res)
73
+ * sse.write({ event: 'message', data: { message: 'hello world' } })
74
+ * }
75
+ * })
76
+ * ```
77
+ */
78
+ function createSSEStream(req, res) {
79
+ const sse = new SSEStream(req);
80
+ sse.pipe(res);
81
+ return sse;
82
+ }
83
+ //#endregion
84
+ //#region src/helper/defineMock.ts
5
85
  function defineMock(config) {
6
86
  return config;
7
87
  }
@@ -29,9 +109,16 @@ function createDefineMock(transformer) {
29
109
  };
30
110
  return define;
31
111
  }
32
-
33
112
  //#endregion
34
- //#region src/core/defineMockData.ts
113
+ //#region src/helper/defineMockData.ts
114
+ /**
115
+ * 由于插件是 分别独立对 `*.mock.*` 等文件作为单独入口进行编译的,
116
+ * 这导致了 mock 文件编译后的依赖关系不一致,每个 mock 文件拥有独立的作用域,
117
+ * 使得即使多个 `*.mock.*` 虽然引入了同一个 `data.ts` 文件,然而确是完全不同两份 `data`,
118
+ * 使得对 `data` 的操作,在不同的 `*.mock.*` 文件中并不能共享。
119
+ *
120
+ * 为此,插件提供了一种基于 memory 的数据共享机制。
121
+ */
35
122
  const mockDataCache = /* @__PURE__ */ new Map();
36
123
  const responseCache = /* @__PURE__ */ new WeakMap();
37
124
  const staleInterval = 70;
@@ -54,8 +141,16 @@ var CacheImpl = class {
54
141
  }
55
142
  };
56
143
  function defineMockData(key, initialData) {
57
- if (!mockDataCache.has(key)) mockDataCache.set(key, new CacheImpl(initialData));
58
- const cache = mockDataCache.get(key);
144
+ let cache = mockDataCache.get(key);
145
+ if (!cache) {
146
+ const newCache = new CacheImpl(initialData);
147
+ const existing = mockDataCache.get(key);
148
+ if (existing) cache = existing;
149
+ else {
150
+ mockDataCache.set(key, newCache);
151
+ cache = newCache;
152
+ }
153
+ }
59
154
  cache.hotUpdate(initialData);
60
155
  if (responseCache.has(cache)) return responseCache.get(cache);
61
156
  const res = [() => cache.value, (val) => {
@@ -73,64 +168,5 @@ function defineMockData(key, initialData) {
73
168
  responseCache.set(cache, res);
74
169
  return res;
75
170
  }
76
-
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
- */
92
- var SSEStream = class extends Transform {
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
- }
124
- };
125
- function dataString(data) {
126
- if (typeof data === "object") return dataString(JSON.stringify(data));
127
- return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}\n`).join("");
128
- }
129
- function createSSEStream(req, res) {
130
- const sse = new SSEStream(req);
131
- sse.pipe(res);
132
- return sse;
133
- }
134
-
135
171
  //#endregion
136
- export { createDefineMock, createSSEStream, defineMock, defineMockData };
172
+ export { createDefineMock, createSSEStream, defineMock, defineMockData };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
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 { Middleware, MiddlewareOptions, MockCompiler, MockCompilerOptions, MockSocketOptions, ResolvePluginOptions, Server, createMockCompiler, createMockMiddleware, mockWebSocket } from "./mockWebsocket-qLVAe-RI.js";
1
+ import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-GT6M6WuI.js";
2
+ import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper.js";
3
+ import { a as processMockData, c as Logger, i as baseMiddleware, l as createLogger, n as mockWebSocket, o as processRawData, r as BaseMiddlewareOptions, s as sortByValidator, t as MockSocketOptions, u as logLevels } from "./server-_doRwsZm.js";
3
4
  import { Compiler, RspackPluginInstance } from "@rspack/core";
4
5
 
5
6
  //#region src/rspack.d.ts
@@ -8,6 +9,5 @@ declare class MockServerPlugin implements RspackPluginInstance {
8
9
  constructor(options?: MockServerPluginOptions);
9
10
  apply(compiler: Compiler): void;
10
11
  }
11
- declare function resolvePluginOptions(compiler: Compiler, options?: MockServerPluginOptions): ResolvePluginOptions;
12
12
  //#endregion
13
- export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, Middleware, MiddlewareOptions, MockCompiler, MockCompilerOptions, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPlugin, MockServerPluginOptions, MockSocketOptions, MockWebsocketItem, ResponseBody, Server, ServerBuildOption, WebSocketSetupContext, createMockCompiler, createMockMiddleware, mockWebSocket, resolvePluginOptions };
13
+ export { BaseMiddlewareOptions, BodyParserOptions, ExtraRequest, type FormidableFile, HeaderStream, LogLevel, LogType, Logger, Method, MockData, type MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, type MockOptions, type MockRequest, MockResponse, MockServerPlugin, type MockServerPluginOptions, MockSocketOptions, type MockWebsocketItem, ResponseBody, SSEMessage, ServerBuildOption, WebSocketSetupContext, baseMiddleware, createDefineMock, createLogger, createSSEStream, defineMock, defineMockData, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
package/dist/index.js CHANGED
@@ -1,10 +1,11 @@
1
- import { mockWebSocket, rewriteRequest, waitingFor } from "./logger-C48_LmdS.js";
2
- import { MockCompiler, buildMockServer, createMockCompiler, createMockMiddleware, resolvePluginOptions } from "./resolvePluginOptions-DlkIkykz.js";
3
- import { isString, toArray } from "@pengzhanbo/utils";
1
+ import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper.js";
2
+ import { a as processRawData, d as logLevels, i as processMockData, n as baseMiddleware, o as sortByValidator, r as rewriteRequest, s as waitingFor, t as mockWebSocket, u as createLogger } from "./ws-BcLCWVaK.js";
3
+ import { n as buildMockServer, r as createMockCompiler, t as resolvePluginOptions$1 } from "./options-Bd0PSZeT.js";
4
+ import "./server.js";
5
+ import { isFunction, isString, toArray, toTruthy } from "@pengzhanbo/utils";
4
6
  import path from "node:path";
5
7
  import process from "node:process";
6
8
  import rspack from "@rspack/core";
7
-
8
9
  //#region src/rspack.ts
9
10
  const PLUGIN_NAME = "rspack-plugin-mock";
10
11
  var MockServerPlugin = class {
@@ -13,10 +14,13 @@ var MockServerPlugin = class {
13
14
  }
14
15
  apply(compiler) {
15
16
  const compilerOptions = compiler.options;
16
- const options = resolvePluginOptions$1(compiler, this.options);
17
+ const options = resolvePluginOptions(compiler, this.options);
17
18
  if (process.env.NODE_ENV !== "production") {
19
+ if (compilerOptions.devServer === false) {
20
+ options.logger.warn(`${PLUGIN_NAME} is disabled, because devServer is disabled`);
21
+ return;
22
+ }
18
23
  const mockCompiler = createMockCompiler(options);
19
- const mockMiddleware = createMockMiddleware(mockCompiler, options);
20
24
  const setupMiddlewares = compilerOptions.devServer?.setupMiddlewares;
21
25
  const waitServerForMockWebSocket = waitingFor((server) => {
22
26
  mockWebSocket(mockCompiler, server, options);
@@ -25,12 +29,12 @@ var MockServerPlugin = class {
25
29
  ...compilerOptions.devServer,
26
30
  setupMiddlewares: (middlewares, devServer) => {
27
31
  middlewares = setupMiddlewares?.(middlewares, devServer) || middlewares;
28
- const reload = () => {
32
+ middlewares.unshift(baseMiddleware(mockCompiler, options));
33
+ if (options.reload) mockCompiler.on("update", () => {
29
34
  if (devServer.webSocketServer?.clients) devServer.sendMessage(devServer.webSocketServer.clients, "static-changed");
30
- };
31
- middlewares = mockMiddleware(middlewares, reload) || middlewares;
35
+ });
32
36
  /**
33
- * 在 @rspack/dev-server -> webpack-dev-server 中, setupMiddlewares 优先于 createServer
37
+ * 在 @rspack/dev-server 中, setupMiddlewares 优先于 createServer
34
38
  * 执行,需要等待 server 启动后再注入 mock websocket
35
39
  */
36
40
  waitServerForMockWebSocket(() => devServer.server);
@@ -41,12 +45,13 @@ var MockServerPlugin = class {
41
45
  if (compilerOptions.devServer?.proxy?.length) {
42
46
  const proxy = compilerOptions.devServer.proxy;
43
47
  compilerOptions.devServer.proxy = proxy.filter((item) => {
44
- if (typeof item !== "function" && item.ws === true && wsPrefix.length) return !toArray(item.context).filter(isString).some((context) => wsPrefix.includes(context));
48
+ if (!isFunction(item) && item.ws === true && wsPrefix.length) return !toArray(item.pathFilter || item.context).filter(isString).some((context) => wsPrefix.includes(context));
45
49
  return true;
46
50
  }).map((item) => {
47
- if (typeof item !== "function" && !item.ws) {
48
- const onProxyReq = item.onProxyReq;
49
- item.onProxyReq = (proxyReq, req, ...args) => {
51
+ if (!isFunction(item) && !item.ws) {
52
+ const on = item.on ??= {};
53
+ const onProxyReq = on.proxyReq;
54
+ on.proxyReq = (proxyReq, req, ...args) => {
50
55
  onProxyReq?.(proxyReq, req, ...args);
51
56
  rewriteRequest(proxyReq, req);
52
57
  };
@@ -59,22 +64,21 @@ var MockServerPlugin = class {
59
64
  } else if (options.build !== false) compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => buildMockServer(options, compilerOptions.output.path || path.resolve(process.cwd(), "dist")));
60
65
  }
61
66
  };
62
- function resolvePluginOptions$1(compiler, options = {}) {
67
+ function resolvePluginOptions(compiler, options = {}) {
63
68
  const compilerOptions = compiler.options;
64
69
  const alias = compilerOptions.resolve?.alias || {};
65
70
  const context = compilerOptions.context;
66
71
  const definePluginInstance = compilerOptions.plugins?.find((plugin) => plugin instanceof rspack.DefinePlugin);
67
- const proxies = (compilerOptions.devServer?.proxy || []).flatMap((item) => {
68
- if (typeof item !== "function" && item.context && !item.ws) return item.context;
72
+ const proxies = ((compilerOptions.devServer || {}).proxy || []).flatMap((item) => {
73
+ if (!isFunction(item) && !item.ws) return item.pathFilter || item.context;
69
74
  return [];
70
- });
71
- return resolvePluginOptions(options, {
75
+ }).filter(toTruthy);
76
+ return resolvePluginOptions$1(options, {
72
77
  alias,
73
78
  context,
74
79
  plugins: toArray(definePluginInstance),
75
80
  proxies
76
81
  });
77
82
  }
78
-
79
83
  //#endregion
80
- export { MockCompiler, MockServerPlugin, createMockCompiler, createMockMiddleware, mockWebSocket, resolvePluginOptions$1 as resolvePluginOptions };
84
+ export { MockServerPlugin, baseMiddleware, createDefineMock, createLogger, createSSEStream, defineMock, defineMockData, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
@@ -0,0 +1,8 @@
1
+ import JSON5 from "json5";
2
+ //#region src/json5-loader.ts
3
+ function json5_loader_default(content) {
4
+ if (!content) return "export default {}";
5
+ return `export default ${JSON.stringify(JSON5.parse(content))}`;
6
+ }
7
+ //#endregion
8
+ export { json5_loader_default as default };