vite-plugin-automock 1.0.2 → 1.1.1
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 +41 -0
- package/dist/{chunk-NWIN2A3G.mjs → chunk-DJWYFFPU.mjs} +14 -31
- package/dist/chunk-DJWYFFPU.mjs.map +1 -0
- package/dist/client/index.d.mts +0 -22
- package/dist/client/index.d.ts +0 -22
- package/dist/client/index.js +13 -31
- package/dist/client/index.js.map +1 -1
- package/dist/client/index.mjs +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +843 -2823
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +854 -2468
- package/dist/index.mjs.map +1 -1
- package/dist/inspector-template.html +1951 -0
- package/package.json +19 -12
- package/dist/chunk-NWIN2A3G.mjs.map +0 -1
- package/dist/chunk-PS6HLNJZ.mjs +0 -339
- package/dist/chunk-PS6HLNJZ.mjs.map +0 -1
- package/dist/mockFileUtils-MO32XIKQ.mjs +0 -17
- package/dist/mockFileUtils-MO32XIKQ.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -170,6 +170,47 @@ automock({
|
|
|
170
170
|
| `pathRewrite` | function | ❌ | `(path) => path` | Function to rewrite request paths |
|
|
171
171
|
| `inspector` | boolean \| object | ❌ | `false` | Enable visual mock inspector UI |
|
|
172
172
|
|
|
173
|
+
## Common Pitfalls
|
|
174
|
+
|
|
175
|
+
### ⚠️ Dual Proxy Configuration
|
|
176
|
+
|
|
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.
|
|
178
|
+
|
|
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
|
+
```
|
|
198
|
+
|
|
199
|
+
**✅ Correct:**
|
|
200
|
+
```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
|
|
209
|
+
})
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
The plugin will automatically warn you if a conflicting proxy configuration is detected.
|
|
213
|
+
|
|
173
214
|
### Inspector Options
|
|
174
215
|
|
|
175
216
|
When `inspector` is an object, you can customize:
|
|
@@ -1,13 +1,4 @@
|
|
|
1
1
|
// src/client/interceptor.ts
|
|
2
|
-
function getEnvVar(name) {
|
|
3
|
-
if (typeof import.meta !== "undefined" && import.meta.env) {
|
|
4
|
-
return import.meta.env[name];
|
|
5
|
-
}
|
|
6
|
-
if (typeof process !== "undefined" && process.env) {
|
|
7
|
-
return process.env[name];
|
|
8
|
-
}
|
|
9
|
-
return void 0;
|
|
10
|
-
}
|
|
11
2
|
var MockInterceptor = class {
|
|
12
3
|
options;
|
|
13
4
|
constructor(options) {
|
|
@@ -117,17 +108,12 @@ async function loadMockData() {
|
|
|
117
108
|
return {};
|
|
118
109
|
}
|
|
119
110
|
}
|
|
120
|
-
async function
|
|
111
|
+
async function createInterceptorFromBundle() {
|
|
121
112
|
const mockData = await loadMockData();
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
"[MockInterceptor] axiosInstance is required. Please provide an axios instance."
|
|
125
|
-
);
|
|
126
|
-
}
|
|
127
|
-
const isEnvEnabled = getEnvVar("VITE_USE_MOCK") === "true";
|
|
128
|
-
const interceptor = createMockInterceptor({
|
|
113
|
+
const isEnabled = typeof __AUTOMOCK_ENABLED__ !== "undefined" && __AUTOMOCK_ENABLED__;
|
|
114
|
+
return new MockInterceptor({
|
|
129
115
|
mockData,
|
|
130
|
-
enabled:
|
|
116
|
+
enabled: isEnabled,
|
|
131
117
|
onMockHit: (url, method) => {
|
|
132
118
|
console.log(`[MOCK HIT] ${method} ${url}`);
|
|
133
119
|
},
|
|
@@ -135,6 +121,14 @@ async function initMockInterceptor(axiosInstance) {
|
|
|
135
121
|
console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);
|
|
136
122
|
}
|
|
137
123
|
});
|
|
124
|
+
}
|
|
125
|
+
async function initMockInterceptor(axiosInstance) {
|
|
126
|
+
if (!axiosInstance) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
"[MockInterceptor] axiosInstance is required. Please provide an axios instance."
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
const interceptor = await createInterceptorFromBundle();
|
|
138
132
|
interceptor.setupAxios(axiosInstance);
|
|
139
133
|
}
|
|
140
134
|
function setMockEnabled(enabled) {
|
|
@@ -153,18 +147,7 @@ async function initMockInterceptorForPureHttp() {
|
|
|
153
147
|
"[MockInterceptor] http instance not registered. Call registerHttpInstance(http) first."
|
|
154
148
|
);
|
|
155
149
|
}
|
|
156
|
-
const
|
|
157
|
-
const isEnvEnabled = getEnvVar("VITE_USE_MOCK") === "true";
|
|
158
|
-
const interceptor = createMockInterceptor({
|
|
159
|
-
mockData,
|
|
160
|
-
enabled: isEnvEnabled,
|
|
161
|
-
onMockHit: (url, method) => {
|
|
162
|
-
console.log(`[MOCK HIT] ${method} ${url}`);
|
|
163
|
-
},
|
|
164
|
-
onBypass: (url, method, reason) => {
|
|
165
|
-
console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);
|
|
166
|
-
}
|
|
167
|
-
});
|
|
150
|
+
const interceptor = await createInterceptorFromBundle();
|
|
168
151
|
interceptor.setupAxios(httpInstanceRef.constructor.axiosInstance);
|
|
169
152
|
}
|
|
170
153
|
|
|
@@ -177,4 +160,4 @@ export {
|
|
|
177
160
|
registerHttpInstance,
|
|
178
161
|
initMockInterceptorForPureHttp
|
|
179
162
|
};
|
|
180
|
-
//# sourceMappingURL=chunk-
|
|
163
|
+
//# sourceMappingURL=chunk-DJWYFFPU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/interceptor.ts"],"sourcesContent":["import type {\n AxiosInstance,\n AxiosResponse,\n InternalAxiosRequestConfig,\n} from \"axios\";\n\ndeclare const __AUTOMOCK_ENABLED__: boolean;\n\nexport type MockBundleData = {\n enable: boolean;\n data: unknown;\n delay?: number;\n status?: number;\n isBinary?: boolean;\n};\n\nexport type MockInterceptorOptions = {\n mockData: Record<string, MockBundleData>;\n enabled?: boolean | (() => boolean);\n onMockHit?: (url: string, method: string, mock: MockBundleData) => void;\n onBypass?: (url: string, method: string, reason: string) => void;\n};\n\ntype MockEnabledState = boolean | undefined;\n\ndeclare global {\n interface Window {\n __MOCK_ENABLED__?: MockEnabledState;\n }\n}\n\nclass MockInterceptor {\n private options: MockInterceptorOptions;\n\n constructor(options: MockInterceptorOptions) {\n this.options = options;\n }\n\n /**\n * Check if mock is enabled\n */\n isEnabled(): boolean {\n // Check runtime flag first\n if (window.__MOCK_ENABLED__ !== undefined) {\n return window.__MOCK_ENABLED__;\n }\n // Check environment variable\n if (typeof this.options.enabled === \"function\") {\n return this.options.enabled();\n }\n return this.options.enabled ?? false;\n }\n\n /**\n * Find matching mock data for the request\n * Supports both formats:\n * - \"GET /api/v1/asset/xxx\" (HTTP method + URL)\n * - \"/api/v1/asset/xxx/get.js\" (File path format from automock plugin)\n */\n private findMock(url: string, method: string): MockBundleData | null {\n const methodUpper = method.toUpperCase();\n const methodLower = method.toLowerCase();\n\n // Try HTTP method + URL format first (for compatibility)\n const httpMethodKey = `${methodUpper} ${url}`;\n if (this.options.mockData[httpMethodKey]) {\n return this.options.mockData[httpMethodKey];\n }\n\n // Try file path format from automock plugin: /api/v1/asset/xxx/get.js\n const filePathKey = `${url}/${methodLower}.js`;\n if (this.options.mockData[filePathKey]) {\n return this.options.mockData[filePathKey];\n }\n\n return null;\n }\n\n /**\n * Determine if request should be mocked\n */\n shouldMock(url: string, method: string): boolean {\n if (!this.isEnabled()) {\n return false;\n }\n\n const mock = this.findMock(url, method);\n return mock !== null && mock.enable;\n }\n\n /**\n * Get mock data for request\n */\n getMock(url: string, method: string): MockBundleData | null {\n if (!this.shouldMock(url, method)) {\n return null;\n }\n return this.findMock(url, method);\n }\n\n /**\n * Setup axios interceptor\n */\n setupAxios(axiosInstance: AxiosInstance): void {\n axiosInstance.interceptors.request.use(\n async (config: InternalAxiosRequestConfig) => {\n const url = config.url || \"\";\n const method = config.method?.toUpperCase() || \"GET\";\n\n const mock = this.getMock(url, method);\n\n if (mock) {\n // Trigger mock hit callback\n this.options.onMockHit?.(url, method, mock);\n\n // Set adapter to return mock data\n (config as InternalAxiosRequestConfig & { adapter: () => Promise<AxiosResponse> }).adapter = async () => {\n const { data, delay = 0, status = 200 } = mock;\n\n // Simulate delay\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n return {\n data,\n status,\n statusText: \"OK\",\n headers: {},\n config,\n };\n };\n } else {\n // Trigger bypass callback\n const reason = !this.isEnabled()\n ? \"Mock disabled globally\"\n : \"No matching mock found or mock disabled\";\n this.options.onBypass?.(url, method, reason);\n }\n\n return config;\n },\n (error: unknown) => Promise.reject(error),\n );\n }\n}\n\n/**\n * Create mock interceptor instance\n */\nexport function createMockInterceptor(\n options: MockInterceptorOptions,\n): MockInterceptor {\n return new MockInterceptor(options);\n}\n\n/**\n * Load mock data from bundled JSON file\n */\nexport async function loadMockData(): Promise<Record<string, MockBundleData>> {\n try {\n // In production, mock-data.json is generated by automock plugin\n // Use absolute path to load it from dist directory\n const response = await fetch(\"/mock-data.json\");\n if (!response.ok) {\n console.warn(\n \"[MockInterceptor] Failed to load mock-data.json:\",\n response.statusText,\n );\n return {};\n }\n const data = (await response.json()) as Record<string, MockBundleData>;\n return data;\n } catch (error) {\n console.warn(\"[MockInterceptor] Failed to load mock-data.json:\", error);\n return {};\n }\n}\n\nasync function createInterceptorFromBundle(): Promise<MockInterceptor> {\n const mockData = await loadMockData();\n const isEnabled = typeof __AUTOMOCK_ENABLED__ !== \"undefined\" && __AUTOMOCK_ENABLED__;\n\n return new MockInterceptor({\n mockData,\n enabled: isEnabled,\n onMockHit: (url: string, method: string) => {\n console.log(`[MOCK HIT] ${method} ${url}`);\n },\n onBypass: (url: string, method: string, reason: string) => {\n console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);\n },\n });\n}\n\nexport async function initMockInterceptor(\n axiosInstance?: AxiosInstance,\n): Promise<void> {\n if (!axiosInstance) {\n throw new Error(\n \"[MockInterceptor] axiosInstance is required. Please provide an axios instance.\",\n );\n }\n\n const interceptor = await createInterceptorFromBundle();\n interceptor.setupAxios(axiosInstance);\n}\n\nexport function setMockEnabled(enabled: boolean): void {\n window.__MOCK_ENABLED__ = enabled;\n}\n\nexport function isMockEnabled(): boolean {\n return !!window.__MOCK_ENABLED__;\n}\n\ntype HttpInstance = {\n constructor: { axiosInstance: AxiosInstance };\n};\n\nlet httpInstanceRef: HttpInstance | undefined;\n\nexport function registerHttpInstance(http: HttpInstance): void {\n httpInstanceRef = http;\n}\n\nexport async function initMockInterceptorForPureHttp(): Promise<void> {\n if (!httpInstanceRef) {\n throw new Error(\n \"[MockInterceptor] http instance not registered. Call registerHttpInstance(http) first.\",\n );\n }\n\n const interceptor = await createInterceptorFromBundle();\n interceptor.setupAxios(httpInstanceRef.constructor.axiosInstance);\n}\n"],"mappings":";AA+BA,IAAM,kBAAN,MAAsB;AAAA,EACZ;AAAA,EAER,YAAY,SAAiC;AAC3C,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAqB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D,cAAQ,IAAI,iBAAiB,MAAM,IAAI,GAAG,MAAM,MAAM,EAAE;AAAA,IAC1D;AAAA,EACF,CAAC;AACH;AAEA,eAAsB,oBACpB,eACe;AACf,MAAI,CAAC,eAAe;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,cAAc,MAAM,4BAA4B;AACtD,cAAY,WAAW,aAAa;AACtC;AAEO,SAAS,eAAe,SAAwB;AACrD,SAAO,mBAAmB;AAC5B;AAEO,SAAS,gBAAyB;AACvC,SAAO,CAAC,CAAC,OAAO;AAClB;AAMA,IAAI;AAEG,SAAS,qBAAqB,MAA0B;AAC7D,oBAAkB;AACpB;AAEA,eAAsB,iCAAgD;AACpE,MAAI,CAAC,iBAAiB;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,cAAc,MAAM,4BAA4B;AACtD,cAAY,WAAW,gBAAgB,YAAY,aAAa;AAClE;","names":[]}
|
package/dist/client/index.d.mts
CHANGED
|
@@ -54,37 +54,15 @@ declare function createMockInterceptor(options: MockInterceptorOptions): MockInt
|
|
|
54
54
|
* Load mock data from bundled JSON file
|
|
55
55
|
*/
|
|
56
56
|
declare function loadMockData(): Promise<Record<string, MockBundleData>>;
|
|
57
|
-
/**
|
|
58
|
-
* Initialize mock interceptor with default settings
|
|
59
|
-
*/
|
|
60
57
|
declare function initMockInterceptor(axiosInstance?: AxiosInstance): Promise<void>;
|
|
61
|
-
/**
|
|
62
|
-
* Set mock enabled state at runtime
|
|
63
|
-
*/
|
|
64
58
|
declare function setMockEnabled(enabled: boolean): void;
|
|
65
|
-
/**
|
|
66
|
-
* Get current mock enabled state
|
|
67
|
-
*/
|
|
68
59
|
declare function isMockEnabled(): boolean;
|
|
69
|
-
/**
|
|
70
|
-
* Get the http instance (PureHttp wrapper)
|
|
71
|
-
* This is a placeholder - users should provide their own http instance
|
|
72
|
-
* or use initMockInterceptorForPureHttp with their specific setup
|
|
73
|
-
*/
|
|
74
60
|
type HttpInstance = {
|
|
75
61
|
constructor: {
|
|
76
62
|
axiosInstance: AxiosInstance;
|
|
77
63
|
};
|
|
78
64
|
};
|
|
79
|
-
/**
|
|
80
|
-
* Register the http instance for PureHttp compatibility
|
|
81
|
-
* Call this before initMockInterceptorForPureHttp
|
|
82
|
-
*/
|
|
83
65
|
declare function registerHttpInstance(http: HttpInstance): void;
|
|
84
|
-
/**
|
|
85
|
-
* Initialize mock interceptor for PureHttp
|
|
86
|
-
* Should be called after PureHttp is instantiated and registered
|
|
87
|
-
*/
|
|
88
66
|
declare function initMockInterceptorForPureHttp(): Promise<void>;
|
|
89
67
|
|
|
90
68
|
export { type MockBundleData, type MockInterceptorOptions, createMockInterceptor, initMockInterceptor, initMockInterceptorForPureHttp, isMockEnabled, loadMockData, registerHttpInstance, setMockEnabled };
|
package/dist/client/index.d.ts
CHANGED
|
@@ -54,37 +54,15 @@ declare function createMockInterceptor(options: MockInterceptorOptions): MockInt
|
|
|
54
54
|
* Load mock data from bundled JSON file
|
|
55
55
|
*/
|
|
56
56
|
declare function loadMockData(): Promise<Record<string, MockBundleData>>;
|
|
57
|
-
/**
|
|
58
|
-
* Initialize mock interceptor with default settings
|
|
59
|
-
*/
|
|
60
57
|
declare function initMockInterceptor(axiosInstance?: AxiosInstance): Promise<void>;
|
|
61
|
-
/**
|
|
62
|
-
* Set mock enabled state at runtime
|
|
63
|
-
*/
|
|
64
58
|
declare function setMockEnabled(enabled: boolean): void;
|
|
65
|
-
/**
|
|
66
|
-
* Get current mock enabled state
|
|
67
|
-
*/
|
|
68
59
|
declare function isMockEnabled(): boolean;
|
|
69
|
-
/**
|
|
70
|
-
* Get the http instance (PureHttp wrapper)
|
|
71
|
-
* This is a placeholder - users should provide their own http instance
|
|
72
|
-
* or use initMockInterceptorForPureHttp with their specific setup
|
|
73
|
-
*/
|
|
74
60
|
type HttpInstance = {
|
|
75
61
|
constructor: {
|
|
76
62
|
axiosInstance: AxiosInstance;
|
|
77
63
|
};
|
|
78
64
|
};
|
|
79
|
-
/**
|
|
80
|
-
* Register the http instance for PureHttp compatibility
|
|
81
|
-
* Call this before initMockInterceptorForPureHttp
|
|
82
|
-
*/
|
|
83
65
|
declare function registerHttpInstance(http: HttpInstance): void;
|
|
84
|
-
/**
|
|
85
|
-
* Initialize mock interceptor for PureHttp
|
|
86
|
-
* Should be called after PureHttp is instantiated and registered
|
|
87
|
-
*/
|
|
88
66
|
declare function initMockInterceptorForPureHttp(): Promise<void>;
|
|
89
67
|
|
|
90
68
|
export { type MockBundleData, type MockInterceptorOptions, createMockInterceptor, initMockInterceptor, initMockInterceptorForPureHttp, isMockEnabled, loadMockData, registerHttpInstance, setMockEnabled };
|
package/dist/client/index.js
CHANGED
|
@@ -31,16 +31,6 @@ __export(client_exports, {
|
|
|
31
31
|
module.exports = __toCommonJS(client_exports);
|
|
32
32
|
|
|
33
33
|
// src/client/interceptor.ts
|
|
34
|
-
var import_meta = {};
|
|
35
|
-
function getEnvVar(name) {
|
|
36
|
-
if (typeof import_meta !== "undefined" && import_meta.env) {
|
|
37
|
-
return import_meta.env[name];
|
|
38
|
-
}
|
|
39
|
-
if (typeof process !== "undefined" && process.env) {
|
|
40
|
-
return process.env[name];
|
|
41
|
-
}
|
|
42
|
-
return void 0;
|
|
43
|
-
}
|
|
44
34
|
var MockInterceptor = class {
|
|
45
35
|
options;
|
|
46
36
|
constructor(options) {
|
|
@@ -150,17 +140,12 @@ async function loadMockData() {
|
|
|
150
140
|
return {};
|
|
151
141
|
}
|
|
152
142
|
}
|
|
153
|
-
async function
|
|
143
|
+
async function createInterceptorFromBundle() {
|
|
154
144
|
const mockData = await loadMockData();
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
"[MockInterceptor] axiosInstance is required. Please provide an axios instance."
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
const isEnvEnabled = getEnvVar("VITE_USE_MOCK") === "true";
|
|
161
|
-
const interceptor = createMockInterceptor({
|
|
145
|
+
const isEnabled = typeof __AUTOMOCK_ENABLED__ !== "undefined" && __AUTOMOCK_ENABLED__;
|
|
146
|
+
return new MockInterceptor({
|
|
162
147
|
mockData,
|
|
163
|
-
enabled:
|
|
148
|
+
enabled: isEnabled,
|
|
164
149
|
onMockHit: (url, method) => {
|
|
165
150
|
console.log(`[MOCK HIT] ${method} ${url}`);
|
|
166
151
|
},
|
|
@@ -168,6 +153,14 @@ async function initMockInterceptor(axiosInstance) {
|
|
|
168
153
|
console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);
|
|
169
154
|
}
|
|
170
155
|
});
|
|
156
|
+
}
|
|
157
|
+
async function initMockInterceptor(axiosInstance) {
|
|
158
|
+
if (!axiosInstance) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
"[MockInterceptor] axiosInstance is required. Please provide an axios instance."
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
const interceptor = await createInterceptorFromBundle();
|
|
171
164
|
interceptor.setupAxios(axiosInstance);
|
|
172
165
|
}
|
|
173
166
|
function setMockEnabled(enabled) {
|
|
@@ -186,18 +179,7 @@ async function initMockInterceptorForPureHttp() {
|
|
|
186
179
|
"[MockInterceptor] http instance not registered. Call registerHttpInstance(http) first."
|
|
187
180
|
);
|
|
188
181
|
}
|
|
189
|
-
const
|
|
190
|
-
const isEnvEnabled = getEnvVar("VITE_USE_MOCK") === "true";
|
|
191
|
-
const interceptor = createMockInterceptor({
|
|
192
|
-
mockData,
|
|
193
|
-
enabled: isEnvEnabled,
|
|
194
|
-
onMockHit: (url, method) => {
|
|
195
|
-
console.log(`[MOCK HIT] ${method} ${url}`);
|
|
196
|
-
},
|
|
197
|
-
onBypass: (url, method, reason) => {
|
|
198
|
-
console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);
|
|
199
|
-
}
|
|
200
|
-
});
|
|
182
|
+
const interceptor = await createInterceptorFromBundle();
|
|
201
183
|
interceptor.setupAxios(httpInstanceRef.constructor.axiosInstance);
|
|
202
184
|
}
|
|
203
185
|
// Annotate the CommonJS export names for ESM import in node:
|
package/dist/client/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/index.ts","../../src/client/interceptor.ts"],"sourcesContent":["export {\n createMockInterceptor,\n initMockInterceptor,\n initMockInterceptorForPureHttp,\n setMockEnabled,\n isMockEnabled,\n loadMockData,\n registerHttpInstance\n} from './interceptor'\n\nexport type { MockInterceptorOptions, MockBundleData } from './interceptor'\n","import type {\n AxiosInstance,\n AxiosRequestConfig,\n InternalAxiosRequestConfig,\n} from \"axios\";\n\n/**\n * Helper function to safely get environment variables\n * Works in both ESM and CJS environments\n */\nfunction getEnvVar(name: string): string | undefined {\n // Try ESM environment (Vite)\n if (typeof import.meta !== \"undefined\" && import.meta.env) {\n return import.meta.env[name as keyof ImportMetaEnv];\n }\n // Fallback to CommonJS (Node.js)\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[name];\n }\n return undefined;\n}\n\nexport type MockBundleData = {\n enable: boolean;\n data: unknown;\n delay?: number;\n status?: number;\n isBinary?: boolean;\n};\n\nexport type MockInterceptorOptions = {\n mockData: Record<string, MockBundleData>;\n enabled?: boolean | (() => boolean);\n onMockHit?: (url: string, method: string, mock: MockBundleData) => void;\n onBypass?: (url: string, method: string, reason: string) => void;\n};\n\ntype MockEnabledState = boolean | undefined;\n\ndeclare global {\n interface Window {\n __MOCK_ENABLED__?: MockEnabledState;\n }\n}\n\nclass MockInterceptor {\n private options: MockInterceptorOptions;\n\n constructor(options: MockInterceptorOptions) {\n this.options = options;\n }\n\n /**\n * Check if mock is enabled\n */\n isEnabled(): boolean {\n // Check runtime flag first\n if (window.__MOCK_ENABLED__ !== undefined) {\n return window.__MOCK_ENABLED__;\n }\n // Check environment variable\n if (typeof this.options.enabled === \"function\") {\n return this.options.enabled();\n }\n return this.options.enabled ?? false;\n }\n\n /**\n * Find matching mock data for the request\n * Supports both formats:\n * - \"GET /api/v1/asset/xxx\" (HTTP method + URL)\n * - \"/api/v1/asset/xxx/get.js\" (File path format from automock plugin)\n */\n private findMock(url: string, method: string): MockBundleData | null {\n const methodUpper = method.toUpperCase();\n const methodLower = method.toLowerCase();\n\n // Try HTTP method + URL format first (for compatibility)\n const httpMethodKey = `${methodUpper} ${url}`;\n if (this.options.mockData[httpMethodKey]) {\n return this.options.mockData[httpMethodKey];\n }\n\n // Try file path format from automock plugin: /api/v1/asset/xxx/get.js\n const filePathKey = `${url}/${methodLower}.js`;\n if (this.options.mockData[filePathKey]) {\n return this.options.mockData[filePathKey];\n }\n\n return null;\n }\n\n /**\n * Determine if request should be mocked\n */\n shouldMock(url: string, method: string): boolean {\n if (!this.isEnabled()) {\n return false;\n }\n\n const mock = this.findMock(url, method);\n return mock !== null && mock.enable;\n }\n\n /**\n * Get mock data for request\n */\n getMock(url: string, method: string): MockBundleData | null {\n if (!this.shouldMock(url, method)) {\n return null;\n }\n return this.findMock(url, method);\n }\n\n /**\n * Setup axios interceptor\n */\n setupAxios(axiosInstance: AxiosInstance): void {\n axiosInstance.interceptors.request.use(\n async (config: InternalAxiosRequestConfig) => {\n const url = config.url || \"\";\n const method = config.method?.toUpperCase() || \"GET\";\n\n const mock = this.getMock(url, method);\n\n if (mock) {\n // Trigger mock hit callback\n this.options.onMockHit?.(url, method, mock);\n\n // Set adapter to return mock data\n (config as any).adapter = async () => {\n const { data, delay = 0, status = 200 } = mock;\n\n // Simulate delay\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n return {\n data,\n status,\n statusText: \"OK\",\n headers: {},\n config,\n };\n };\n } else {\n // Trigger bypass callback\n const reason = !this.isEnabled()\n ? \"Mock disabled globally\"\n : \"No matching mock found or mock disabled\";\n this.options.onBypass?.(url, method, reason);\n }\n\n return config;\n },\n (error: unknown) => Promise.reject(error),\n );\n }\n}\n\n/**\n * Create mock interceptor instance\n */\nexport function createMockInterceptor(\n options: MockInterceptorOptions,\n): MockInterceptor {\n return new MockInterceptor(options);\n}\n\n/**\n * Load mock data from bundled JSON file\n */\nexport async function loadMockData(): Promise<Record<string, MockBundleData>> {\n try {\n // In production, mock-data.json is generated by automock plugin\n // Use absolute path to load it from dist directory\n const response = await fetch(\"/mock-data.json\");\n if (!response.ok) {\n console.warn(\n \"[MockInterceptor] Failed to load mock-data.json:\",\n response.statusText,\n );\n return {};\n }\n const data = (await response.json()) as Record<string, MockBundleData>;\n return data;\n } catch (error) {\n console.warn(\"[MockInterceptor] Failed to load mock-data.json:\", error);\n return {};\n }\n}\n\n/**\n * Initialize mock interceptor with default settings\n */\nexport async function initMockInterceptor(\n axiosInstance?: AxiosInstance,\n): Promise<void> {\n const mockData = await loadMockData();\n\n if (!axiosInstance) {\n throw new Error(\n \"[MockInterceptor] axiosInstance is required. Please provide an axios instance.\",\n );\n }\n\n // Check if mock is enabled via environment variable\n const isEnvEnabled = getEnvVar(\"VITE_USE_MOCK\") === \"true\";\n\n const interceptor = createMockInterceptor({\n mockData,\n enabled: isEnvEnabled,\n onMockHit: (url: string, method: string) => {\n console.log(`[MOCK HIT] ${method} ${url}`);\n },\n onBypass: (url: string, method: string, reason: string) => {\n console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);\n },\n });\n\n // Setup interceptor on the axios instance\n interceptor.setupAxios(axiosInstance);\n}\n\n/**\n * Set mock enabled state at runtime\n */\nexport function setMockEnabled(enabled: boolean): void {\n window.__MOCK_ENABLED__ = enabled;\n}\n\n/**\n * Get current mock enabled state\n */\nexport function isMockEnabled(): boolean {\n return !!window.__MOCK_ENABLED__;\n}\n\n/**\n * Get the http instance (PureHttp wrapper)\n * This is a placeholder - users should provide their own http instance\n * or use initMockInterceptorForPureHttp with their specific setup\n */\ntype HttpInstance = {\n constructor: { axiosInstance: AxiosInstance };\n};\n\n// This is a reference to the user's http instance\n// It should be set by the user's application code\nlet httpInstanceRef: HttpInstance | undefined;\n\n/**\n * Register the http instance for PureHttp compatibility\n * Call this before initMockInterceptorForPureHttp\n */\nexport function registerHttpInstance(http: HttpInstance): void {\n httpInstanceRef = http;\n}\n\n/**\n * Initialize mock interceptor for PureHttp\n * Should be called after PureHttp is instantiated and registered\n */\nexport async function initMockInterceptorForPureHttp(): Promise<void> {\n if (!httpInstanceRef) {\n throw new Error(\n \"[MockInterceptor] http instance not registered. Call registerHttpInstance(http) first.\",\n );\n }\n\n const mockData = await loadMockData();\n\n // Check if mock is enabled via environment variable\n const isEnvEnabled = getEnvVar(\"VITE_USE_MOCK\") === \"true\";\n\n const interceptor = createMockInterceptor({\n mockData,\n enabled: isEnvEnabled,\n onMockHit: (url: string, method: string) => {\n console.log(`[MOCK HIT] ${method} ${url}`);\n },\n onBypass: (url: string, method: string, reason: string) => {\n console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);\n },\n });\n\n // Get axios instance from PureHttp and setup interceptor\n interceptor.setupAxios(httpInstanceRef.constructor.axiosInstance);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAUA,SAAS,UAAU,MAAkC;AAEnD,MAAI,OAAO,gBAAgB,eAAe,YAAY,KAAK;AACzD,WAAO,YAAY,IAAI,IAA2B;AAAA,EACpD;AAEA,MAAI,OAAO,YAAY,eAAe,QAAQ,KAAK;AACjD,WAAO,QAAQ,IAAI,IAAI;AAAA,EACzB;AACA,SAAO;AACT;AAyBA,IAAM,kBAAN,MAAsB;AAAA,EACZ;AAAA,EAER,YAAY,SAAiC;AAC3C,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAqB;AAEnB,QAAI,OAAO,qBAAqB,QAAW;AACzC,aAAO,OAAO;AAAA,IAChB;AAEA,QAAI,OAAO,KAAK,QAAQ,YAAY,YAAY;AAC9C,aAAO,KAAK,QAAQ,QAAQ;AAAA,IAC9B;AACA,WAAO,KAAK,QAAQ,WAAW;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA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,SAAO,mBAAmB;AAC5B;AAKO,SAAS,gBAAyB;AACvC,SAAO,CAAC,CAAC,OAAO;AAClB;AAaA,IAAI;AAMG,SAAS,qBAAqB,MAA0B;AAC7D,oBAAkB;AACpB;AAMA,eAAsB,iCAAgD;AACpE,MAAI,CAAC,iBAAiB;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,aAAa;AAGpC,QAAM,eAAe,UAAU,eAAe,MAAM;AAEpD,QAAM,cAAc,sBAAsB;AAAA,IACxC;AAAA,IACA,SAAS;AAAA,IACT,WAAW,CAAC,KAAa,WAAmB;AAC1C,cAAQ,IAAI,cAAc,MAAM,IAAI,GAAG,EAAE;AAAA,IAC3C;AAAA,IACA,UAAU,CAAC,KAAa,QAAgB,WAAmB;AACzD,cAAQ,IAAI,iBAAiB,MAAM,IAAI,GAAG,MAAM,MAAM,EAAE;AAAA,IAC1D;AAAA,EACF,CAAC;AAGD,cAAY,WAAW,gBAAgB,YAAY,aAAa;AAClE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/client/index.ts","../../src/client/interceptor.ts"],"sourcesContent":["export {\n createMockInterceptor,\n initMockInterceptor,\n initMockInterceptorForPureHttp,\n setMockEnabled,\n isMockEnabled,\n loadMockData,\n registerHttpInstance\n} from './interceptor'\n\nexport type { MockInterceptorOptions, MockBundleData } from './interceptor'\n","import type {\n AxiosInstance,\n AxiosResponse,\n InternalAxiosRequestConfig,\n} from \"axios\";\n\ndeclare const __AUTOMOCK_ENABLED__: boolean;\n\nexport type MockBundleData = {\n enable: boolean;\n data: unknown;\n delay?: number;\n status?: number;\n isBinary?: boolean;\n};\n\nexport type MockInterceptorOptions = {\n mockData: Record<string, MockBundleData>;\n enabled?: boolean | (() => boolean);\n onMockHit?: (url: string, method: string, mock: MockBundleData) => void;\n onBypass?: (url: string, method: string, reason: string) => void;\n};\n\ntype MockEnabledState = boolean | undefined;\n\ndeclare global {\n interface Window {\n __MOCK_ENABLED__?: MockEnabledState;\n }\n}\n\nclass MockInterceptor {\n private options: MockInterceptorOptions;\n\n constructor(options: MockInterceptorOptions) {\n this.options = options;\n }\n\n /**\n * Check if mock is enabled\n */\n isEnabled(): boolean {\n // Check runtime flag first\n if (window.__MOCK_ENABLED__ !== undefined) {\n return window.__MOCK_ENABLED__;\n }\n // Check environment variable\n if (typeof this.options.enabled === \"function\") {\n return this.options.enabled();\n }\n return this.options.enabled ?? false;\n }\n\n /**\n * Find matching mock data for the request\n * Supports both formats:\n * - \"GET /api/v1/asset/xxx\" (HTTP method + URL)\n * - \"/api/v1/asset/xxx/get.js\" (File path format from automock plugin)\n */\n private findMock(url: string, method: string): MockBundleData | null {\n const methodUpper = method.toUpperCase();\n const methodLower = method.toLowerCase();\n\n // Try HTTP method + URL format first (for compatibility)\n const httpMethodKey = `${methodUpper} ${url}`;\n if (this.options.mockData[httpMethodKey]) {\n return this.options.mockData[httpMethodKey];\n }\n\n // Try file path format from automock plugin: /api/v1/asset/xxx/get.js\n const filePathKey = `${url}/${methodLower}.js`;\n if (this.options.mockData[filePathKey]) {\n return this.options.mockData[filePathKey];\n }\n\n return null;\n }\n\n /**\n * Determine if request should be mocked\n */\n shouldMock(url: string, method: string): boolean {\n if (!this.isEnabled()) {\n return false;\n }\n\n const mock = this.findMock(url, method);\n return mock !== null && mock.enable;\n }\n\n /**\n * Get mock data for request\n */\n getMock(url: string, method: string): MockBundleData | null {\n if (!this.shouldMock(url, method)) {\n return null;\n }\n return this.findMock(url, method);\n }\n\n /**\n * Setup axios interceptor\n */\n setupAxios(axiosInstance: AxiosInstance): void {\n axiosInstance.interceptors.request.use(\n async (config: InternalAxiosRequestConfig) => {\n const url = config.url || \"\";\n const method = config.method?.toUpperCase() || \"GET\";\n\n const mock = this.getMock(url, method);\n\n if (mock) {\n // Trigger mock hit callback\n this.options.onMockHit?.(url, method, mock);\n\n // Set adapter to return mock data\n (config as InternalAxiosRequestConfig & { adapter: () => Promise<AxiosResponse> }).adapter = async () => {\n const { data, delay = 0, status = 200 } = mock;\n\n // Simulate delay\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n return {\n data,\n status,\n statusText: \"OK\",\n headers: {},\n config,\n };\n };\n } else {\n // Trigger bypass callback\n const reason = !this.isEnabled()\n ? \"Mock disabled globally\"\n : \"No matching mock found or mock disabled\";\n this.options.onBypass?.(url, method, reason);\n }\n\n return config;\n },\n (error: unknown) => Promise.reject(error),\n );\n }\n}\n\n/**\n * Create mock interceptor instance\n */\nexport function createMockInterceptor(\n options: MockInterceptorOptions,\n): MockInterceptor {\n return new MockInterceptor(options);\n}\n\n/**\n * Load mock data from bundled JSON file\n */\nexport async function loadMockData(): Promise<Record<string, MockBundleData>> {\n try {\n // In production, mock-data.json is generated by automock plugin\n // Use absolute path to load it from dist directory\n const response = await fetch(\"/mock-data.json\");\n if (!response.ok) {\n console.warn(\n \"[MockInterceptor] Failed to load mock-data.json:\",\n response.statusText,\n );\n return {};\n }\n const data = (await response.json()) as Record<string, MockBundleData>;\n return data;\n } catch (error) {\n console.warn(\"[MockInterceptor] Failed to load mock-data.json:\", error);\n return {};\n }\n}\n\nasync function createInterceptorFromBundle(): Promise<MockInterceptor> {\n const mockData = await loadMockData();\n const isEnabled = typeof __AUTOMOCK_ENABLED__ !== \"undefined\" && __AUTOMOCK_ENABLED__;\n\n return new MockInterceptor({\n mockData,\n enabled: isEnabled,\n onMockHit: (url: string, method: string) => {\n console.log(`[MOCK HIT] ${method} ${url}`);\n },\n onBypass: (url: string, method: string, reason: string) => {\n console.log(`[MOCK BYPASS] ${method} ${url} - ${reason}`);\n },\n });\n}\n\nexport async function initMockInterceptor(\n axiosInstance?: AxiosInstance,\n): Promise<void> {\n if (!axiosInstance) {\n throw new Error(\n \"[MockInterceptor] axiosInstance is required. Please provide an axios instance.\",\n );\n }\n\n const interceptor = await createInterceptorFromBundle();\n interceptor.setupAxios(axiosInstance);\n}\n\nexport function setMockEnabled(enabled: boolean): void {\n window.__MOCK_ENABLED__ = enabled;\n}\n\nexport function isMockEnabled(): boolean {\n return !!window.__MOCK_ENABLED__;\n}\n\ntype HttpInstance = {\n constructor: { axiosInstance: AxiosInstance };\n};\n\nlet httpInstanceRef: HttpInstance | undefined;\n\nexport function registerHttpInstance(http: HttpInstance): void {\n httpInstanceRef = http;\n}\n\nexport async function initMockInterceptorForPureHttp(): Promise<void> {\n if (!httpInstanceRef) {\n throw new Error(\n \"[MockInterceptor] http instance not registered. Call registerHttpInstance(http) first.\",\n );\n }\n\n const interceptor = await createInterceptorFromBundle();\n interceptor.setupAxios(httpInstanceRef.constructor.axiosInstance);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC+BA,IAAM,kBAAN,MAAsB;AAAA,EACZ;AAAA,EAER,YAAY,SAAiC;AAC3C,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAqB;AAEnB,QAAI,OAAO,qBAAqB,QAAW;AACzC,aAAO,OAAO;AAAA,IAChB;AAEA,QAAI,OAAO,KAAK,QAAQ,YAAY,YAAY;AAC9C,aAAO,KAAK,QAAQ,QAAQ;AAAA,IAC9B;AACA,WAAO,KAAK,QAAQ,WAAW;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,SAAS,KAAa,QAAuC;AACnE,UAAM,cAAc,OAAO,YAAY;AACvC,UAAM,cAAc,OAAO,YAAY;AAGvC,UAAM,gBAAgB,GAAG,WAAW,IAAI,GAAG;AAC3C,QAAI,KAAK,QAAQ,SAAS,aAAa,GAAG;AACxC,aAAO,KAAK,QAAQ,SAAS,aAAa;AAAA,IAC5C;AAGA,UAAM,cAAc,GAAG,GAAG,IAAI,WAAW;AACzC,QAAI,KAAK,QAAQ,SAAS,WAAW,GAAG;AACtC,aAAO,KAAK,QAAQ,SAAS,WAAW;AAAA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a;AAClE;","names":[]}
|
package/dist/client/index.mjs
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -31,10 +31,10 @@ interface MockFileInfo {
|
|
|
31
31
|
dataText: string;
|
|
32
32
|
isBinary?: boolean;
|
|
33
33
|
}
|
|
34
|
-
declare
|
|
35
|
-
declare
|
|
36
|
-
declare
|
|
37
|
-
declare
|
|
34
|
+
declare function saveMockData(url: string, method: string, data: Buffer | string, rootDir: string, statusCode?: number, contentType?: string): Promise<string | null>;
|
|
35
|
+
declare function buildMockIndex(mockDir: string): Promise<Map<string, string>>;
|
|
36
|
+
declare function parseMockModule(filePath: string): Promise<MockFileInfo>;
|
|
37
|
+
declare function writeMockFile(filePath: string, mockInfo: Pick<MockFileInfo, "config" | "headerComment" | "description">): Promise<void>;
|
|
38
38
|
|
|
39
39
|
interface MockBundleData {
|
|
40
40
|
enable: boolean;
|
package/dist/index.d.ts
CHANGED
|
@@ -31,10 +31,10 @@ interface MockFileInfo {
|
|
|
31
31
|
dataText: string;
|
|
32
32
|
isBinary?: boolean;
|
|
33
33
|
}
|
|
34
|
-
declare
|
|
35
|
-
declare
|
|
36
|
-
declare
|
|
37
|
-
declare
|
|
34
|
+
declare function saveMockData(url: string, method: string, data: Buffer | string, rootDir: string, statusCode?: number, contentType?: string): Promise<string | null>;
|
|
35
|
+
declare function buildMockIndex(mockDir: string): Promise<Map<string, string>>;
|
|
36
|
+
declare function parseMockModule(filePath: string): Promise<MockFileInfo>;
|
|
37
|
+
declare function writeMockFile(filePath: string, mockInfo: Pick<MockFileInfo, "config" | "headerComment" | "description">): Promise<void>;
|
|
38
38
|
|
|
39
39
|
interface MockBundleData {
|
|
40
40
|
enable: boolean;
|