vite-plugin-automock 1.1.5 → 1.1.6

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.
Files changed (2) hide show
  1. package/README.md +250 -232
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -6,13 +6,14 @@ Effortless API mock auto-generation for legacy projects. No manual files, just a
6
6
 
7
7
  ## Features
8
8
 
9
- - 🚀 Automatically captures API requests and generates local mock data
10
- - 🏆 Perfect for legacy projects, easily backfill missing mocks
11
- - 🛠️ Supports manual mock file creation with a simple format
12
- - Zero-config, plug-and-play
13
- - 🧩 Fully compatible with the Vite plugin ecosystem
14
- - 📦 Production-ready with client-side interceptor
15
- - 🎛️ Visual mock inspector panel
9
+ - Automatically captures API requests and generates local mock data
10
+ - Perfect for legacy projects, easily backfill missing mocks
11
+ - Supports manual mock file creation with a simple format
12
+ - Fine-grained control: enable/disable mock, proxy, and capture independently
13
+ - Visual mock inspector panel for managing mock files
14
+ - Production-ready with client-side interceptor (Axios / PureHttp)
15
+ - Fully compatible with the Vite plugin ecosystem
16
+ - Zero-config, plug-and-play
16
17
 
17
18
  ## Installation
18
19
 
@@ -26,8 +27,6 @@ yarn add -D vite-plugin-automock
26
27
 
27
28
  ## Quick Start
28
29
 
29
- ### 1. Configure Vite Plugin
30
-
31
30
  ```typescript
32
31
  // vite.config.ts
33
32
  import { automock } from 'vite-plugin-automock'
@@ -35,36 +34,150 @@ import { automock } from 'vite-plugin-automock'
35
34
  export default defineConfig({
36
35
  plugins: [
37
36
  automock({
37
+ proxyBaseUrl: 'https://api.example.com', // Required: your API server URL
38
+ })
39
+ ]
40
+ })
41
+ ```
42
+
43
+ That's it! The plugin will:
44
+
45
+ 1. Intercept requests matching `apiPrefix` (default `/api`)
46
+ 2. Return mock data if a mock file exists
47
+ 3. Proxy to `proxyBaseUrl` and auto-save the response as a mock file
48
+
49
+ ## Configuration Options
50
+
51
+ ### Plugin Options
52
+
53
+ | Option | Type | Required | Default | Description |
54
+ | ------ | ---- | -------- | ------- | ----------- |
55
+ | `proxyBaseUrl` | `string` | Yes | - | Base URL of your API server |
56
+ | `mockDir` | `string` | No | `'mock'` | Directory to store mock files |
57
+ | `apiPrefix` | `string` | No | `'/api'` | API path prefix to intercept |
58
+ | `pathRewrite` | `(path: string) => string` | No | `(path) => path` | Function to rewrite request paths |
59
+ | `enabled` | `boolean` | No | `true` | Global switch. When `false`, all requests pass through without mock handling |
60
+ | `proxy` | `boolean` | No | `true` | Whether to proxy unmatched requests to `proxyBaseUrl` |
61
+ | `capture` | `boolean` | No | `true` | Whether to auto-capture proxy responses and save as mock files |
62
+ | `productionMock` | `boolean \| 'auto'` | No | `false` | Enable mock in production mode |
63
+ | `inspector` | `boolean \| InspectorOptions` | No | `false` | Enable visual mock inspector UI |
64
+
65
+ ### Bundle Options
66
+
67
+ These options are available when using the `automock()` function (which includes bundle support):
68
+
69
+ | Option | Type | Default | Description |
70
+ | ------ | ---- | ------- | ----------- |
71
+ | `bundleMockData` | `boolean` | `true` | Whether to bundle mock data for production |
72
+ | `bundleOutputPath` | `string` | `'public/mock-data.json'` | Output path for the mock bundle file |
73
+
74
+ ### Inspector Options
75
+
76
+ When `inspector` is an object:
77
+
78
+ | Option | Type | Default | Description |
79
+ | ------ | ---- | ------- | ----------- |
80
+ | `route` | `string` | `'/__mock/'` | Route path for the inspector UI |
81
+ | `enableToggle` | `boolean` | `true` | Allow toggling mock enable/disable in the UI |
82
+
83
+ ### Full Configuration Example
84
+
85
+ ```typescript
86
+ import { automock } from 'vite-plugin-automock'
87
+
88
+ export default defineConfig({
89
+ plugins: [
90
+ automock({
91
+ // Basic
92
+ proxyBaseUrl: 'https://api.example.com',
38
93
  mockDir: 'mock',
39
94
  apiPrefix: '/api',
40
- bundleMockData: true, // Bundle mock data for production
41
- productionMock: true, // Enable mock in production
42
- proxyBaseUrl: 'https://api.example.com'
95
+ pathRewrite: (path) => path.replace(/^\/api/, ''),
96
+
97
+ // Fine-grained control
98
+ enabled: true,
99
+ proxy: true,
100
+ capture: true,
101
+
102
+ // Production
103
+ productionMock: 'auto',
104
+ bundleMockData: true,
105
+ bundleOutputPath: 'public/mock-data.json',
106
+
107
+ // Inspector
108
+ inspector: {
109
+ route: '/__mock/',
110
+ enableToggle: true,
111
+ },
43
112
  })
44
113
  ]
45
114
  })
46
115
  ```
47
116
 
48
- ### 2. Create Mock Files
117
+ ## Fine-grained Control
118
+
119
+ The `enabled`, `proxy`, and `capture` options provide independent control over the plugin's behavior:
120
+
121
+ ### Record-only Mode
122
+
123
+ Proxy to the backend and capture responses, but don't intercept requests with existing mocks:
49
124
 
50
125
  ```typescript
51
- // mock/users.ts
52
- import { MockFileConfig } from 'vite-plugin-automock'
126
+ automock({
127
+ proxyBaseUrl: 'https://api.example.com',
128
+ enabled: false, // Don't intercept
129
+ proxy: true, // Proxy to backend
130
+ capture: true, // Save responses as mock files
131
+ })
132
+ ```
53
133
 
54
- export default {
55
- enable: true,
56
- data: { users: [{ id: 1, name: 'Alice' }] },
57
- delay: 100,
58
- status: 200
59
- } as MockFileConfig
134
+ ### Mock-only Mode
135
+
136
+ Only return mock data, never proxy to backend. Useful when you want strict offline development:
137
+
138
+ ```typescript
139
+ automock({
140
+ proxyBaseUrl: 'https://api.example.com',
141
+ enabled: true, // Intercept requests
142
+ proxy: false, // Don't proxy to backend
143
+ capture: false, // Don't save new mocks
144
+ })
60
145
  ```
61
146
 
62
- ### 3. Initialize Client Interceptor
147
+ ### Pure Proxy Mode
63
148
 
64
- For PureHttp wrapper:
149
+ Bypass all mock handling, just proxy to backend:
65
150
 
66
151
  ```typescript
67
- // src/main.ts or src/api/index.ts
152
+ automock({
153
+ proxyBaseUrl: 'https://api.example.com',
154
+ enabled: false, // Don't intercept
155
+ proxy: true, // Proxy to backend
156
+ capture: false, // Don't save mocks
157
+ })
158
+ ```
159
+
160
+ ### Default Mode (Recommended)
161
+
162
+ All features enabled - mock first, proxy fallback, auto-capture:
163
+
164
+ ```typescript
165
+ automock({
166
+ proxyBaseUrl: 'https://api.example.com',
167
+ // enabled: true (default)
168
+ // proxy: true (default)
169
+ // capture: true (default)
170
+ })
171
+ ```
172
+
173
+ ## Client API Reference
174
+
175
+ The client-side interceptor is used for **production mode** mock support. Import from `vite-plugin-automock/client`.
176
+
177
+ ### For PureHttp Wrapper
178
+
179
+ ```typescript
180
+ // src/main.ts
68
181
  import {
69
182
  initMockInterceptorForPureHttp,
70
183
  setMockEnabled,
@@ -77,12 +190,8 @@ registerHttpInstance(http)
77
190
 
78
191
  // Initialize mock interceptor
79
192
  initMockInterceptorForPureHttp()
80
- .then(() => {
81
- console.log('[MockInterceptor] Initialized successfully')
82
- })
83
- .catch(error => {
84
- console.error('[MockInterceptor] Failed to initialize:', error)
85
- })
193
+ .then(() => console.log('[MockInterceptor] Initialized'))
194
+ .catch(error => console.error('[MockInterceptor] Failed:', error))
86
195
 
87
196
  // Enable mock in development
88
197
  if (import.meta.env.DEV) {
@@ -90,167 +199,94 @@ if (import.meta.env.DEV) {
90
199
  }
91
200
  ```
92
201
 
93
- For plain Axios:
202
+ ### For Plain Axios
94
203
 
95
204
  ```typescript
96
205
  // src/main.ts
97
206
  import { initMockInterceptor, setMockEnabled } from 'vite-plugin-automock/client'
98
207
  import axios from 'axios'
99
208
 
100
- // Initialize with axios instance
101
209
  initMockInterceptor(axios)
102
- .then(() => {
103
- console.log('[MockInterceptor] Initialized successfully')
104
- })
105
- .catch(error => {
106
- console.error('[MockInterceptor] Failed to initialize:', error)
107
- })
210
+ .then(() => console.log('[MockInterceptor] Initialized'))
211
+ .catch(error => console.error('[MockInterceptor] Failed:', error))
108
212
 
109
- // Enable mock in development
110
213
  if (import.meta.env.DEV) {
111
214
  setMockEnabled(true)
112
215
  }
113
216
  ```
114
217
 
115
- ## Documentation
116
-
117
- For detailed usage instructions, configuration options, and examples, see:
118
-
119
- **[📚 Complete Usage Guide](./docs/USAGE_GUIDE.md)**
120
-
121
- Topics covered:
122
- - Development vs Production modes
123
- - Client interceptor configuration
124
- - Runtime mock toggle
125
- - Visual inspector
126
- - API reference
127
- - Common scenarios
128
-
129
- ---
130
-
131
- ## Basic Usage (Development Mode)
132
-
133
- Import and register the plugin in your `vite.config.ts`:
218
+ ### Client Exports
134
219
 
135
- ```js
136
- import { automock } from "vite-plugin-automock";
220
+ | Export | Type | Description |
221
+ | ------ | ---- | ----------- |
222
+ | `initMockInterceptor` | `(axios: AxiosInstance) => Promise<void>` | Initialize interceptor with an Axios instance |
223
+ | `initMockInterceptorForPureHttp` | `() => Promise<void>` | Initialize interceptor for PureHttp (call `registerHttpInstance` first) |
224
+ | `registerHttpInstance` | `(http: { constructor: { axiosInstance: AxiosInstance } }) => void` | Register a PureHttp instance |
225
+ | `setMockEnabled` | `(enabled: boolean) => void` | Enable/disable mock at runtime |
226
+ | `isMockEnabled` | `() => boolean` | Check if mock is currently enabled |
227
+ | `loadMockData` | `() => Promise<Record<string, MockBundleData>>` | Load mock data from the bundled JSON file |
228
+ | `createMockInterceptor` | `(options: MockInterceptorOptions) => MockInterceptor` | Create a custom interceptor instance |
137
229
 
138
- export default {
139
- plugins: [
140
- automock({
141
- proxyBaseUrl: "http://localhost:8888", // Required: Your API server URL
142
- mockDir: "mock", // Optional: Directory for mock files (default: 'mock')
143
- apiPrefix: "/api", // Optional: API prefix to intercept (default: '/api')
144
- pathRewrite: (path) => path, // Optional: Path rewrite function
145
- inspector: true, // Optional: Enable visual inspector (default: false)
146
- }),
147
- ],
148
- };
149
- ```
230
+ ### MockInterceptorOptions
150
231
 
151
- ### With Custom Inspector Configuration
232
+ ```typescript
233
+ interface MockInterceptorOptions {
234
+ mockData: Record<string, MockBundleData>
235
+ enabled?: boolean | (() => boolean)
236
+ onMockHit?: (url: string, method: string, mock: MockBundleData) => void
237
+ onBypass?: (url: string, method: string, reason: string) => void
238
+ }
152
239
 
153
- ```js
154
- automock({
155
- proxyBaseUrl: "http://localhost:8888",
156
- inspector: {
157
- route: "/__inspector/", // Custom route for inspector UI
158
- enableToggle: true, // Allow toggling enable/disable
159
- },
160
- });
240
+ interface MockBundleData {
241
+ enable: boolean
242
+ data: unknown
243
+ delay?: number
244
+ status?: number
245
+ isBinary?: boolean
246
+ }
161
247
  ```
162
248
 
163
- ## Configuration Options
164
-
165
- | Option | Type | Required | Default | Description |
166
- | -------------- | ----------------- | -------- | ---------------- | --------------------------------- |
167
- | `proxyBaseUrl` | string | ✅ | - | Base URL of your API server |
168
- | `mockDir` | string | ❌ | `'mock'` | Directory to store mock files |
169
- | `apiPrefix` | string | ❌ | `'/api'` | API path prefix to intercept |
170
- | `pathRewrite` | function | ❌ | `(path) => path` | Function to rewrite request paths |
171
- | `inspector` | boolean \| object | ❌ | `false` | Enable visual mock inspector UI |
172
-
173
- ## Common Pitfalls
174
-
175
- ### ⚠️ Dual Proxy Configuration
249
+ ## Production Mode
176
250
 
177
- **Do NOT** configure both Vite's `server.proxy` and automock's `proxyBaseUrl` for the same API prefix. This will cause conflicts and requests may hang.
251
+ To use mock data in production builds:
178
252
 
179
- **❌ Wrong:**
180
- ```typescript
181
- export default defineConfig({
182
- plugins: [
183
- automock({
184
- proxyBaseUrl: "http://localhost:8888",
185
- apiPrefix: "/api",
186
- })
187
- ],
188
- server: {
189
- proxy: {
190
- "/api": { // ❌ CONFLICTS with automock
191
- target: "http://localhost:8888",
192
- changeOrigin: true,
193
- }
194
- }
195
- }
196
- })
197
- ```
253
+ 1. Enable `productionMock` and `bundleMockData`:
198
254
 
199
- **✅ Correct:**
200
255
  ```typescript
201
- export default defineConfig({
202
- plugins: [
203
- automock({
204
- proxyBaseUrl: "http://localhost:8888",
205
- apiPrefix: "/api",
206
- })
207
- ],
208
- // ✅ Remove server.proxy or use a different prefix
256
+ automock({
257
+ proxyBaseUrl: 'https://api.example.com',
258
+ productionMock: true, // or 'auto'
259
+ bundleMockData: true, // default
260
+ bundleOutputPath: 'public/mock-data.json',
209
261
  })
210
262
  ```
211
263
 
212
- The plugin will automatically warn you if a conflicting proxy configuration is detected.
213
-
214
- ### Inspector Options
264
+ 2. The plugin will generate `public/mock-data.json` at build time containing all mock data.
215
265
 
216
- When `inspector` is an object, you can customize:
266
+ 3. Initialize the client interceptor in your app (see [Client API Reference](#client-api-reference)).
217
267
 
218
- | Option | Type | Default | Description |
219
- | -------------- | ------- | ------------ | ---------------------------------- |
220
- | `route` | string | `'/__mock/'` | Route path for the inspector UI |
221
- | `enableToggle` | boolean | `true` | Allow toggling mock enable/disable |
268
+ 4. The `productionMock: 'auto'` option automatically enables mock based on the environment.
222
269
 
223
- ## Mock Inspector 🎨
270
+ ## Mock Inspector
224
271
 
225
- **NEW!** Visual interface to manage your mock files:
272
+ The visual inspector provides a web UI to manage mock files:
226
273
 
227
- ```js
274
+ ```typescript
228
275
  automock({
229
- proxyBaseUrl: "http://localhost:8888",
230
- inspector: true, // Enable inspector UI
231
- });
276
+ proxyBaseUrl: 'https://api.example.com',
277
+ inspector: true, // or { route: '/__mock/', enableToggle: true }
278
+ })
232
279
  ```
233
280
 
234
281
  Then visit `http://localhost:5173/__mock/` to:
235
282
 
236
- - 📋 **Browse** all mock files organized by URL
237
- - 🎛️ **Toggle** mock enable/disable status
238
- - ⏱️ **Adjust** response delay and status codes
239
- - ✏️ **Edit** JSON response data directly
240
- - 💾 **Save** changes with a single click
241
-
242
- ![Inspector Demo](https://via.placeholder.com/800x400?text=Mock+Inspector+UI)
243
-
244
- ## How It Works
245
-
246
- 1. **Request Interception**: The plugin intercepts all requests matching the `apiPrefix`
247
- 2. **Mock Check**: Checks if a corresponding mock file exists
248
- 3. **Conditional Response**:
249
- - If mock exists → Returns mock data
250
- - If mock doesn't exist → Proxies to real API and saves response as mock
251
- 4. **Auto-Generation**: Real API responses are automatically saved as mock files
252
- 5. **Hot Reloading**: Changes to mock files are automatically detected and reloaded
253
- 6. **Visual Inspector**: Manage and edit mocks through the web UI
283
+ - **Browse** all mock files organized by URL
284
+ - **Toggle** mock enable/disable status
285
+ - **Adjust** response delay and status codes
286
+ - **Edit** JSON response data directly
287
+ - **Create** new mock files
288
+ - **Delete** existing mock files
289
+ - **Batch update** multiple mocks at once
254
290
 
255
291
  ## Mock File Structure
256
292
 
@@ -267,7 +303,7 @@ mock/
267
303
  │ └── post.js # POST /api/items
268
304
  ```
269
305
 
270
- Each mock file exports an object with this structure:
306
+ Each mock file exports an object:
271
307
 
272
308
  ```javascript
273
309
  /**
@@ -275,9 +311,8 @@ Each mock file exports an object with this structure:
275
311
  * Generated at 2025-01-11T10:30:00.000Z
276
312
  */
277
313
  export default {
278
- enable: false, // Whether to use this mock (default: false)
314
+ enable: false, // Whether to use this mock
279
315
  data: {
280
- // Response data
281
316
  code: 0,
282
317
  message: "success",
283
318
  data: [
@@ -285,55 +320,77 @@ export default {
285
320
  { id: 2, name: "User 2" },
286
321
  ],
287
322
  },
288
- delay: 0, // Artificial delay in milliseconds
323
+ delay: 0, // Artificial delay in milliseconds
289
324
  status: 200, // HTTP status code
290
- };
325
+ }
291
326
  ```
292
327
 
293
- ## Quick Start
328
+ ### Dynamic Mock Data
294
329
 
295
- 1. **Try the Example**:
330
+ ```javascript
331
+ export default {
332
+ enable: true,
333
+ data: () => ({
334
+ timestamp: new Date().toISOString(),
335
+ randomId: Math.floor(Math.random() * 1000),
336
+ }),
337
+ }
338
+ ```
296
339
 
297
- ```bash
298
- pnpm run example
299
- ```
340
+ ## Common Pitfalls
300
341
 
301
- This starts the playground with a demo API server.
342
+ ### Dual Proxy Configuration
302
343
 
303
- 2. **Manual Setup**:
344
+ **Do NOT** configure both Vite's `server.proxy` and automock's `proxyBaseUrl` for the same API prefix:
304
345
 
305
- ```bash
306
- # Install the plugin
307
- pnpm add -D vite-plugin-automock
346
+ ```typescript
347
+ // Wrong - will cause request conflicts
348
+ export default defineConfig({
349
+ plugins: [
350
+ automock({ proxyBaseUrl: 'http://localhost:8888', apiPrefix: '/api' })
351
+ ],
352
+ server: {
353
+ proxy: {
354
+ '/api': { target: 'http://localhost:8888', changeOrigin: true } // CONFLICTS
355
+ }
356
+ }
357
+ })
358
+
359
+ // ✅ Correct - use automock for /api, remove server.proxy
360
+ export default defineConfig({
361
+ plugins: [
362
+ automock({ proxyBaseUrl: 'http://localhost:8888', apiPrefix: '/api' })
363
+ ]
364
+ })
365
+ ```
308
366
 
309
- # Add to your vite.config.js
310
- import { automock } from "vite-plugin-automock";
367
+ The plugin will automatically warn you if a conflicting proxy is detected.
311
368
 
312
- export default {
313
- plugins: [
314
- automock({
315
- proxyBaseUrl: "http://localhost:8888"
316
- })
317
- ]
318
- };
319
- ```
369
+ ## How It Works
320
370
 
321
- 3. **Start Development**:
322
- - Start your API server
323
- - Start Vite dev server
324
- - Make API calls from your frontend
325
- - Check the mock directory for generated files
371
+ 1. **Request Interception**: The plugin intercepts all requests matching `apiPrefix`
372
+ 2. **Mock Check**: Checks if a corresponding mock file exists and is enabled
373
+ 3. **Conditional Response**:
374
+ - Mock exists and enabled -> Returns mock data
375
+ - Mock exists but disabled -> Skips to proxy or next middleware
376
+ - Mock doesn't exist -> Proxies to real API (if `proxy: true`)
377
+ 4. **Auto-Capture**: Real API responses are automatically saved as mock files (if `capture: true`)
378
+ 5. **Hot Reloading**: Changes to mock files are automatically detected and reloaded
379
+ 6. **Bundle**: Mock data is bundled into JSON for production use
326
380
 
327
381
  ## Comparison with Traditional Mock Plugins
328
382
 
329
- | Feature | Traditional Mock Plugins | vite-plugin-automock |
330
- | ---------------------- | ------------------------ | -------------------- |
331
- | Auto backfill | | |
332
- | Legacy project support | | |
333
- | Manual mock files | | |
334
- | Config complexity | High | Very low |
335
- | Zero setup | | |
336
- | Real API integration | | |
383
+ | Feature | Traditional Mock Plugins | vite-plugin-automock |
384
+ | ------- | ----------------------- | -------------------- |
385
+ | Auto backfill | - | Yes |
386
+ | Legacy project support | - | Yes |
387
+ | Manual mock files | Yes | Yes |
388
+ | Config complexity | High | Very low |
389
+ | Zero setup | - | Yes |
390
+ | Real API integration | - | Yes |
391
+ | Fine-grained control | - | Yes |
392
+ | Visual inspector | - | Yes |
393
+ | Production mock | - | Yes |
337
394
 
338
395
  ## When to Use
339
396
 
@@ -343,45 +400,6 @@ export default {
343
400
  - **Testing**: Consistent test data without external dependencies
344
401
  - **Demo/Presentation**: Reliable demo data that doesn't change
345
402
 
346
- ## Advanced Usage
347
-
348
- ### Custom Path Rewriting
349
-
350
- ```javascript
351
- automock({
352
- proxyBaseUrl: "http://api.example.com",
353
- pathRewrite: (path) => {
354
- // Remove /api prefix when proxying
355
- return path.replace(/^\/api/, "");
356
- },
357
- });
358
- ```
359
-
360
- ### Conditional Mock Enabling
361
-
362
- ```javascript
363
- // In your mock file
364
- export default {
365
- enable: process.env.NODE_ENV === "development",
366
- data: {
367
- /* mock data */
368
- },
369
- };
370
- ```
371
-
372
- ### Dynamic Mock Data
373
-
374
- ```javascript
375
- // In your mock file
376
- export default {
377
- enable: true,
378
- data: () => ({
379
- timestamp: new Date().toISOString(),
380
- randomId: Math.floor(Math.random() * 1000),
381
- }),
382
- };
383
- ```
384
-
385
403
  ## Contributing
386
404
 
387
405
  We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-automock",
3
- "version": "1.1.5",
3
+ "version": "1.1.6",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "exports": {