rspack-plugin-mock 1.0.1 → 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/chunk-CUT6urMc.cjs +30 -0
- package/dist/helper.cjs +124 -113
- package/dist/helper.d.cts +92 -104
- package/dist/helper.d.ts +92 -104
- package/dist/helper.js +120 -113
- package/dist/index.cjs +82 -99
- package/dist/index.d.cts +10 -22
- package/dist/index.d.ts +10 -22
- package/dist/index.js +74 -97
- package/dist/json5-loader.cjs +30 -15
- package/dist/logger-C0V8Cvvd.cjs +800 -0
- package/dist/logger-C48_LmdS.js +710 -0
- package/dist/mockWebsocket-DkVHpZCx.d.cts +85 -0
- package/dist/mockWebsocket-qLVAe-RI.d.ts +85 -0
- package/dist/resolvePluginOptions-Da5uqlBx.cjs +506 -0
- package/dist/resolvePluginOptions-DlkIkykz.js +476 -0
- package/dist/rsbuild.cjs +164 -190
- package/dist/rsbuild.d.cts +5 -13
- package/dist/rsbuild.d.ts +5 -13
- package/dist/rsbuild.js +161 -188
- package/dist/server.cjs +9 -18
- package/dist/server.d.cts +21 -25
- package/dist/server.d.ts +21 -25
- package/dist/server.js +3 -18
- package/dist/types-6lajtJPx.d.cts +572 -0
- package/dist/types-DPzh7nJq.d.ts +572 -0
- package/package.json +28 -28
- package/dist/chunk-HTVJXQRM.cjs +0 -906
- package/dist/chunk-HV5L72CY.js +0 -557
- package/dist/chunk-M7F5AAOF.cjs +0 -557
- package/dist/chunk-OGWV5ZGG.js +0 -906
- package/dist/mockWebsocket-DBgZBsdo.d.ts +0 -76
- package/dist/mockWebsocket-Ki_cShTv.d.cts +0 -76
- package/dist/types-Aw0AciTG.d.cts +0 -570
- package/dist/types-Aw0AciTG.d.ts +0 -570
package/dist/chunk-HTVJXQRM.cjs
DELETED
|
@@ -1,906 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } 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; }// src/core/transform.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
var _utils = require('@pengzhanbo/utils');
|
|
9
|
-
|
|
10
|
-
// src/core/utils.ts
|
|
11
|
-
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
12
|
-
var _os = require('os'); var _os2 = _interopRequireDefault(_os);
|
|
13
|
-
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
14
|
-
var _querystring = require('querystring');
|
|
15
|
-
var _url = require('url');
|
|
16
|
-
var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug);
|
|
17
|
-
var _memfs = require('memfs');
|
|
18
|
-
var _pathtoregexp = require('path-to-regexp');
|
|
19
|
-
var packageDir = getDirname(import.meta.url);
|
|
20
|
-
var vfs = _memfs.createFsFromVolume.call(void 0, new (0, _memfs.Volume)());
|
|
21
|
-
function isStream(stream) {
|
|
22
|
-
return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
|
|
23
|
-
}
|
|
24
|
-
function isReadableStream(stream) {
|
|
25
|
-
return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
|
|
26
|
-
}
|
|
27
|
-
function getDirname(importMetaUrl) {
|
|
28
|
-
return _path2.default.dirname(_url.fileURLToPath.call(void 0, importMetaUrl));
|
|
29
|
-
}
|
|
30
|
-
var debug = _debug2.default.call(void 0, "rspack:mock");
|
|
31
|
-
function lookupFile(dir, formats, options) {
|
|
32
|
-
for (const format of formats) {
|
|
33
|
-
const fullPath = _path2.default.join(dir, format);
|
|
34
|
-
if (_fs2.default.existsSync(fullPath) && _fs2.default.statSync(fullPath).isFile()) {
|
|
35
|
-
const result = _optionalChain([options, 'optionalAccess', _ => _.pathOnly]) ? fullPath : _fs2.default.readFileSync(fullPath, "utf-8");
|
|
36
|
-
if (!_optionalChain([options, 'optionalAccess', _2 => _2.predicate]) || options.predicate(result))
|
|
37
|
-
return result;
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
const parentDir = _path2.default.dirname(dir);
|
|
41
|
-
if (parentDir !== dir && (!_optionalChain([options, 'optionalAccess', _3 => _3.rootDir]) || parentDir.startsWith(_optionalChain([options, 'optionalAccess', _4 => _4.rootDir])))) {
|
|
42
|
-
return lookupFile(parentDir, formats, options);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
function doesProxyContextMatchUrl(context, url, req) {
|
|
46
|
-
if (typeof context === "function") {
|
|
47
|
-
return context(url, req);
|
|
48
|
-
}
|
|
49
|
-
return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
|
|
50
|
-
}
|
|
51
|
-
function parseParams(pattern, url) {
|
|
52
|
-
const urlMatch = _pathtoregexp.match.call(void 0, pattern, { decode: decodeURIComponent })(url) || {
|
|
53
|
-
params: {}
|
|
54
|
-
};
|
|
55
|
-
return urlMatch.params || {};
|
|
56
|
-
}
|
|
57
|
-
function urlParse(input) {
|
|
58
|
-
const url = new (0, _url.URL)(input, "http://example.com");
|
|
59
|
-
const pathname = decodeURIComponent(url.pathname);
|
|
60
|
-
const query = _querystring.parse.call(void 0, url.search.replace(/^\?/, ""));
|
|
61
|
-
return { pathname, query };
|
|
62
|
-
}
|
|
63
|
-
var windowsSlashRE = /\\/g;
|
|
64
|
-
var isWindows = _os2.default.platform() === "win32";
|
|
65
|
-
function slash(p) {
|
|
66
|
-
return p.replace(windowsSlashRE, "/");
|
|
67
|
-
}
|
|
68
|
-
function normalizePath(id) {
|
|
69
|
-
return _path2.default.posix.normalize(isWindows ? slash(id) : id);
|
|
70
|
-
}
|
|
71
|
-
function waitingFor(onSuccess, maxRetry = 5) {
|
|
72
|
-
return function wait(getter, retry = 0) {
|
|
73
|
-
const value = getter();
|
|
74
|
-
if (value) {
|
|
75
|
-
onSuccess(value);
|
|
76
|
-
} else if (retry < maxRetry) {
|
|
77
|
-
setTimeout(() => wait(getter, retry + 1), 100);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// src/core/validator.ts
|
|
83
|
-
|
|
84
|
-
function validate(request, validator) {
|
|
85
|
-
return isObjectSubset(request.headers, validator.headers) && isObjectSubset(request.body, validator.body) && isObjectSubset(request.params, validator.params) && isObjectSubset(request.query, validator.query) && isObjectSubset(request.refererQuery, validator.refererQuery);
|
|
86
|
-
}
|
|
87
|
-
function isObjectSubset(source, target) {
|
|
88
|
-
if (!target)
|
|
89
|
-
return true;
|
|
90
|
-
for (const key in target) {
|
|
91
|
-
if (!isIncluded(source[key], target[key]))
|
|
92
|
-
return false;
|
|
93
|
-
}
|
|
94
|
-
return true;
|
|
95
|
-
}
|
|
96
|
-
function isIncluded(source, target) {
|
|
97
|
-
if (_utils.isArray.call(void 0, source) && _utils.isArray.call(void 0, target)) {
|
|
98
|
-
const seen = /* @__PURE__ */ new Set();
|
|
99
|
-
return target.every(
|
|
100
|
-
(ti) => source.some((si, i) => {
|
|
101
|
-
if (seen.has(i))
|
|
102
|
-
return false;
|
|
103
|
-
const included = isIncluded(si, ti);
|
|
104
|
-
if (included)
|
|
105
|
-
seen.add(i);
|
|
106
|
-
return included;
|
|
107
|
-
})
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
if (_utils.isPlainObject.call(void 0, source) && _utils.isPlainObject.call(void 0, target))
|
|
111
|
-
return isObjectSubset(source, target);
|
|
112
|
-
return Object.is(source, target);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// src/core/transform.ts
|
|
116
|
-
function transformRawData(rawData) {
|
|
117
|
-
return rawData.filter((item) => item[0]).map(([raw, __filepath__]) => {
|
|
118
|
-
let mockConfig;
|
|
119
|
-
if (raw.default) {
|
|
120
|
-
if (Array.isArray(raw.default)) {
|
|
121
|
-
mockConfig = raw.default.map((item) => ({ ...item, __filepath__ }));
|
|
122
|
-
} else {
|
|
123
|
-
mockConfig = { ...raw.default, __filepath__ };
|
|
124
|
-
}
|
|
125
|
-
} else if ("url" in raw) {
|
|
126
|
-
mockConfig = { ...raw, __filepath__ };
|
|
127
|
-
} else {
|
|
128
|
-
mockConfig = [];
|
|
129
|
-
Object.keys(raw || {}).forEach((key) => {
|
|
130
|
-
if (Array.isArray(raw[key])) {
|
|
131
|
-
mockConfig.push(...raw[key].map((item) => ({ ...item, __filepath__ })));
|
|
132
|
-
} else {
|
|
133
|
-
mockConfig.push({ ...raw[key], __filepath__ });
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
return mockConfig;
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
function transformMockData(mockList) {
|
|
141
|
-
const list = [];
|
|
142
|
-
for (const [, handle] of mockList.entries()) {
|
|
143
|
-
if (handle)
|
|
144
|
-
list.push(..._utils.toArray.call(void 0, handle));
|
|
145
|
-
}
|
|
146
|
-
const mocks = {};
|
|
147
|
-
list.filter((mock) => _utils.isPlainObject.call(void 0, mock) && mock.enabled !== false && mock.url).forEach((mock) => {
|
|
148
|
-
const { pathname, query } = urlParse(mock.url);
|
|
149
|
-
const list2 = mocks[pathname] ??= [];
|
|
150
|
-
const current = { ...mock, url: pathname };
|
|
151
|
-
if (current.ws !== true) {
|
|
152
|
-
const validator = current.validator;
|
|
153
|
-
if (!_utils.isEmptyObject.call(void 0, query)) {
|
|
154
|
-
if (_utils.isFunction.call(void 0, validator)) {
|
|
155
|
-
current.validator = function(request) {
|
|
156
|
-
return isObjectSubset(request.query, query) && validator(request);
|
|
157
|
-
};
|
|
158
|
-
} else if (validator) {
|
|
159
|
-
current.validator = { ...validator };
|
|
160
|
-
current.validator.query = current.validator.query ? { ...query, ...current.validator.query } : query;
|
|
161
|
-
} else {
|
|
162
|
-
current.validator = { query };
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
list2.push(current);
|
|
167
|
-
});
|
|
168
|
-
Object.keys(mocks).forEach((key) => {
|
|
169
|
-
mocks[key] = sortByValidator(mocks[key]);
|
|
170
|
-
});
|
|
171
|
-
return mocks;
|
|
172
|
-
}
|
|
173
|
-
function sortByValidator(mocks) {
|
|
174
|
-
return _utils.sortBy.call(void 0, mocks, (item) => {
|
|
175
|
-
if (item.ws === true)
|
|
176
|
-
return 0;
|
|
177
|
-
const { validator } = item;
|
|
178
|
-
if (!validator || _utils.isEmptyObject.call(void 0, validator))
|
|
179
|
-
return 2;
|
|
180
|
-
if (_utils.isFunction.call(void 0, validator))
|
|
181
|
-
return 0;
|
|
182
|
-
const count = Object.keys(validator).reduce(
|
|
183
|
-
(prev, key) => prev + keysCount(validator[key]),
|
|
184
|
-
0
|
|
185
|
-
);
|
|
186
|
-
return 1 / count;
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
function keysCount(obj) {
|
|
190
|
-
if (!obj)
|
|
191
|
-
return 0;
|
|
192
|
-
return Object.keys(obj).length;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// src/core/requestRecovery.ts
|
|
196
|
-
var _buffer = require('buffer');
|
|
197
|
-
var requestCollectCache = /* @__PURE__ */ new WeakMap();
|
|
198
|
-
function collectRequest(req) {
|
|
199
|
-
const chunks = [];
|
|
200
|
-
req.addListener("data", (chunk) => {
|
|
201
|
-
chunks.push(_buffer.Buffer.from(chunk));
|
|
202
|
-
});
|
|
203
|
-
req.addListener("end", () => {
|
|
204
|
-
if (chunks.length)
|
|
205
|
-
requestCollectCache.set(req, _buffer.Buffer.concat(chunks));
|
|
206
|
-
});
|
|
207
|
-
}
|
|
208
|
-
function rewriteRequest(proxyReq, req) {
|
|
209
|
-
const buffer = requestCollectCache.get(req);
|
|
210
|
-
if (buffer) {
|
|
211
|
-
requestCollectCache.delete(req);
|
|
212
|
-
if (!proxyReq.headersSent)
|
|
213
|
-
proxyReq.setHeader("Content-Length", buffer.byteLength);
|
|
214
|
-
if (!proxyReq.writableEnded)
|
|
215
|
-
proxyReq.write(buffer);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// src/core/baseMiddleware.ts
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
var _cookies = require('cookies'); var _cookies2 = _interopRequireDefault(_cookies);
|
|
230
|
-
var _httpstatus = require('http-status'); var _httpstatus2 = _interopRequireDefault(_httpstatus);
|
|
231
|
-
var _mimetypes = require('mime-types'); var mime = _interopRequireWildcard(_mimetypes);
|
|
232
|
-
|
|
233
|
-
var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
|
|
234
|
-
|
|
235
|
-
// src/core/matchingWeight.ts
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
var tokensCache = {};
|
|
245
|
-
function getTokens(rule) {
|
|
246
|
-
if (tokensCache[rule])
|
|
247
|
-
return tokensCache[rule];
|
|
248
|
-
const tks = _pathtoregexp.parse.call(void 0, rule);
|
|
249
|
-
const tokens = [];
|
|
250
|
-
for (const tk of tks) {
|
|
251
|
-
if (!_utils.isString.call(void 0, tk)) {
|
|
252
|
-
tokens.push(tk);
|
|
253
|
-
} else {
|
|
254
|
-
const hasPrefix = tk[0] === "/";
|
|
255
|
-
const subTks = hasPrefix ? tk.slice(1).split("/") : tk.split("/");
|
|
256
|
-
tokens.push(
|
|
257
|
-
`${hasPrefix ? "/" : ""}${subTks[0]}`,
|
|
258
|
-
...subTks.slice(1).map((t) => `/${t}`)
|
|
259
|
-
);
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
tokensCache[rule] = tokens;
|
|
263
|
-
return tokens;
|
|
264
|
-
}
|
|
265
|
-
function getHighest(rules) {
|
|
266
|
-
let weights = rules.map((rule) => getTokens(rule).length);
|
|
267
|
-
weights = weights.length === 0 ? [1] : weights;
|
|
268
|
-
return Math.max(...weights) + 2;
|
|
269
|
-
}
|
|
270
|
-
function sortFn(rule) {
|
|
271
|
-
const tokens = getTokens(rule);
|
|
272
|
-
let w = 0;
|
|
273
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
274
|
-
const token = tokens[i];
|
|
275
|
-
if (!_utils.isString.call(void 0, token))
|
|
276
|
-
w += 10 ** (i + 1);
|
|
277
|
-
w += 10 ** (i + 1);
|
|
278
|
-
}
|
|
279
|
-
return w;
|
|
280
|
-
}
|
|
281
|
-
function preSort(rules) {
|
|
282
|
-
let matched = [];
|
|
283
|
-
const preMatch = [];
|
|
284
|
-
for (const rule of rules) {
|
|
285
|
-
const tokens = getTokens(rule);
|
|
286
|
-
const len = tokens.filter((token) => typeof token !== "string").length;
|
|
287
|
-
if (!preMatch[len])
|
|
288
|
-
preMatch[len] = [];
|
|
289
|
-
preMatch[len].push(rule);
|
|
290
|
-
}
|
|
291
|
-
for (const match2 of preMatch.filter((v) => v && v.length > 0))
|
|
292
|
-
matched = [...matched, ..._utils.sortBy.call(void 0, match2, sortFn).reverse()];
|
|
293
|
-
return matched;
|
|
294
|
-
}
|
|
295
|
-
function defaultPriority(rules) {
|
|
296
|
-
const highest = getHighest(rules);
|
|
297
|
-
return _utils.sortBy.call(void 0, rules, (rule) => {
|
|
298
|
-
const tokens = getTokens(rule);
|
|
299
|
-
const dym = tokens.filter((token) => typeof token !== "string");
|
|
300
|
-
if (dym.length === 0)
|
|
301
|
-
return 0;
|
|
302
|
-
let weight = dym.length;
|
|
303
|
-
let exp = 0;
|
|
304
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
305
|
-
const token = tokens[i];
|
|
306
|
-
const isDynamic = !_utils.isString.call(void 0, token);
|
|
307
|
-
const {
|
|
308
|
-
pattern = "",
|
|
309
|
-
modifier,
|
|
310
|
-
prefix,
|
|
311
|
-
name
|
|
312
|
-
} = isDynamic ? token : {};
|
|
313
|
-
const isGlob = pattern && pattern.includes(".*");
|
|
314
|
-
const isSlash = prefix === "/";
|
|
315
|
-
const isNamed = _utils.isString.call(void 0, name);
|
|
316
|
-
exp += isDynamic && isSlash ? 1 : 0;
|
|
317
|
-
if (i === tokens.length - 1 && isGlob) {
|
|
318
|
-
weight += 5 * 10 ** (tokens.length === 1 ? highest + 1 : highest);
|
|
319
|
-
} else {
|
|
320
|
-
if (isGlob) {
|
|
321
|
-
weight += 3 * 10 ** (highest - 1);
|
|
322
|
-
} else if (pattern) {
|
|
323
|
-
if (isSlash) {
|
|
324
|
-
weight += (isNamed ? 2 : 1) * 10 ** (exp + 1);
|
|
325
|
-
} else {
|
|
326
|
-
weight -= 1 * 10 ** exp;
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
if (modifier === "+")
|
|
331
|
-
weight += 1 * 10 ** (highest - 1);
|
|
332
|
-
if (modifier === "*")
|
|
333
|
-
weight += 1 * 10 ** (highest - 1) + 1;
|
|
334
|
-
if (modifier === "?")
|
|
335
|
-
weight += 1 * 10 ** (exp + (isSlash ? 1 : 0));
|
|
336
|
-
}
|
|
337
|
-
return weight;
|
|
338
|
-
});
|
|
339
|
-
}
|
|
340
|
-
function matchingWeight(rules, url, priority) {
|
|
341
|
-
let matched = defaultPriority(
|
|
342
|
-
preSort(rules.filter((rule) => _pathtoregexp.pathToRegexp.call(void 0, rule).test(url)))
|
|
343
|
-
);
|
|
344
|
-
const { global = [], special = {} } = priority;
|
|
345
|
-
if (global.length === 0 && _utils.isEmptyObject.call(void 0, special) || matched.length === 0)
|
|
346
|
-
return matched;
|
|
347
|
-
const [statics, dynamics] = twoPartMatch(matched);
|
|
348
|
-
const globalMatch = global.filter((rule) => dynamics.includes(rule));
|
|
349
|
-
if (globalMatch.length > 0) {
|
|
350
|
-
matched = _utils.uniq.call(void 0, [...statics, ...globalMatch, ...dynamics]);
|
|
351
|
-
}
|
|
352
|
-
if (_utils.isEmptyObject.call(void 0, special))
|
|
353
|
-
return matched;
|
|
354
|
-
const specialRule = Object.keys(special).filter(
|
|
355
|
-
(rule) => matched.includes(rule)
|
|
356
|
-
)[0];
|
|
357
|
-
if (!specialRule)
|
|
358
|
-
return matched;
|
|
359
|
-
const options = special[specialRule];
|
|
360
|
-
const { rules: lowerRules, when } = _utils.isArray.call(void 0, options) ? { rules: options, when: [] } : options;
|
|
361
|
-
if (lowerRules.includes(matched[0])) {
|
|
362
|
-
if (when.length === 0 || when.some((path2) => _pathtoregexp.pathToRegexp.call(void 0, path2).test(url))) {
|
|
363
|
-
matched = _utils.uniq.call(void 0, [specialRule, ...matched]);
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
return matched;
|
|
367
|
-
}
|
|
368
|
-
function twoPartMatch(rules) {
|
|
369
|
-
const statics = [];
|
|
370
|
-
const dynamics = [];
|
|
371
|
-
for (const rule of rules) {
|
|
372
|
-
const tokens = getTokens(rule);
|
|
373
|
-
const dym = tokens.filter((token) => typeof token !== "string");
|
|
374
|
-
if (dym.length > 0)
|
|
375
|
-
dynamics.push(rule);
|
|
376
|
-
else statics.push(rule);
|
|
377
|
-
}
|
|
378
|
-
return [statics, dynamics];
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// src/core/parseReqBody.ts
|
|
382
|
-
var _cobody = require('co-body'); var _cobody2 = _interopRequireDefault(_cobody);
|
|
383
|
-
var _formidable = require('formidable'); var _formidable2 = _interopRequireDefault(_formidable);
|
|
384
|
-
async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
385
|
-
const method = req.method.toUpperCase();
|
|
386
|
-
if (["GET", "DELETE", "HEAD"].includes(method))
|
|
387
|
-
return void 0;
|
|
388
|
-
const type = _optionalChain([req, 'access', _5 => _5.headers, 'access', _6 => _6["content-type"], 'optionalAccess', _7 => _7.toLocaleLowerCase, 'call', _8 => _8()]) || "";
|
|
389
|
-
const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
|
|
390
|
-
try {
|
|
391
|
-
if (type.startsWith("application/json")) {
|
|
392
|
-
return await _cobody2.default.json(req, {
|
|
393
|
-
limit: jsonLimit || limit,
|
|
394
|
-
...rest
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
if (type.startsWith("application/x-www-form-urlencoded")) {
|
|
398
|
-
return await _cobody2.default.form(req, {
|
|
399
|
-
limit: formLimit || limit,
|
|
400
|
-
...rest
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
if (type.startsWith("text/plain")) {
|
|
404
|
-
return await _cobody2.default.text(req, {
|
|
405
|
-
limit: textLimit || limit,
|
|
406
|
-
...rest
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
if (type.startsWith("multipart/form-data"))
|
|
410
|
-
return await parseMultipart(req, formidableOptions);
|
|
411
|
-
} catch (e) {
|
|
412
|
-
console.error(e);
|
|
413
|
-
}
|
|
414
|
-
return void 0;
|
|
415
|
-
}
|
|
416
|
-
async function parseMultipart(req, options) {
|
|
417
|
-
const form = _formidable2.default.call(void 0, options);
|
|
418
|
-
return new Promise((resolve, reject) => {
|
|
419
|
-
form.parse(req, (error, fields, files) => {
|
|
420
|
-
if (error) {
|
|
421
|
-
reject(error);
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
resolve({ ...fields, ...files });
|
|
425
|
-
});
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
// src/core/baseMiddleware.ts
|
|
430
|
-
function baseMiddleware(compiler, {
|
|
431
|
-
formidableOptions = {},
|
|
432
|
-
bodyParserOptions = {},
|
|
433
|
-
proxies,
|
|
434
|
-
cookiesOptions,
|
|
435
|
-
logger,
|
|
436
|
-
priority = {}
|
|
437
|
-
}) {
|
|
438
|
-
return async function(req, res, next) {
|
|
439
|
-
const startTime = _utils.timestamp.call(void 0, );
|
|
440
|
-
const { query, pathname } = urlParse(req.url);
|
|
441
|
-
if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url, req))) {
|
|
442
|
-
return next();
|
|
443
|
-
}
|
|
444
|
-
const mockData = compiler.mockData;
|
|
445
|
-
const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
|
|
446
|
-
if (mockUrls.length === 0) {
|
|
447
|
-
return next();
|
|
448
|
-
}
|
|
449
|
-
collectRequest(req);
|
|
450
|
-
const { query: refererQuery } = urlParse(req.headers.referer || "");
|
|
451
|
-
const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
|
|
452
|
-
const cookies = new (0, _cookies2.default)(req, res, cookiesOptions);
|
|
453
|
-
const getCookie = cookies.get.bind(cookies);
|
|
454
|
-
const method = req.method.toUpperCase();
|
|
455
|
-
let mock;
|
|
456
|
-
let _mockUrl;
|
|
457
|
-
for (const mockUrl of mockUrls) {
|
|
458
|
-
mock = fineMock(mockData[mockUrl], logger, {
|
|
459
|
-
pathname,
|
|
460
|
-
method,
|
|
461
|
-
request: {
|
|
462
|
-
query,
|
|
463
|
-
refererQuery,
|
|
464
|
-
body: reqBody,
|
|
465
|
-
headers: req.headers,
|
|
466
|
-
getCookie
|
|
467
|
-
}
|
|
468
|
-
});
|
|
469
|
-
if (mock) {
|
|
470
|
-
_mockUrl = mockUrl;
|
|
471
|
-
break;
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
if (!mock) {
|
|
475
|
-
const matched = mockUrls.map(
|
|
476
|
-
(m) => m === _mockUrl ? _picocolors2.default.underline(_picocolors2.default.bold(m)) : _picocolors2.default.dim(m)
|
|
477
|
-
).join(", ");
|
|
478
|
-
logger.warn(
|
|
479
|
-
`${_picocolors2.default.green(
|
|
480
|
-
pathname
|
|
481
|
-
)} matches ${matched} , but mock data is not found.`
|
|
482
|
-
);
|
|
483
|
-
return next();
|
|
484
|
-
}
|
|
485
|
-
const request = req;
|
|
486
|
-
const response = res;
|
|
487
|
-
request.body = reqBody;
|
|
488
|
-
request.query = query;
|
|
489
|
-
request.refererQuery = refererQuery;
|
|
490
|
-
request.params = parseParams(mock.url, pathname);
|
|
491
|
-
request.getCookie = getCookie;
|
|
492
|
-
response.setCookie = cookies.set.bind(cookies);
|
|
493
|
-
const {
|
|
494
|
-
body,
|
|
495
|
-
delay,
|
|
496
|
-
type = "json",
|
|
497
|
-
response: responseFn,
|
|
498
|
-
status = 200,
|
|
499
|
-
statusText,
|
|
500
|
-
log: logLevel,
|
|
501
|
-
__filepath__: filepath
|
|
502
|
-
} = mock;
|
|
503
|
-
responseStatus(response, status, statusText);
|
|
504
|
-
await provideHeaders(request, response, mock, logger);
|
|
505
|
-
await provideCookies(request, response, mock, logger);
|
|
506
|
-
logger.info(requestLog(request, filepath), logLevel);
|
|
507
|
-
logger.debug(
|
|
508
|
-
`${_picocolors2.default.magenta("DEBUG")} ${_picocolors2.default.underline(
|
|
509
|
-
pathname
|
|
510
|
-
)} matches: [ ${mockUrls.map(
|
|
511
|
-
(m) => m === _mockUrl ? _picocolors2.default.underline(_picocolors2.default.bold(m)) : _picocolors2.default.dim(m)
|
|
512
|
-
).join(", ")} ]
|
|
513
|
-
`
|
|
514
|
-
);
|
|
515
|
-
if (body) {
|
|
516
|
-
try {
|
|
517
|
-
const content = _utils.isFunction.call(void 0, body) ? await body(request) : body;
|
|
518
|
-
await realDelay(startTime, delay);
|
|
519
|
-
sendData(response, content, type);
|
|
520
|
-
} catch (e) {
|
|
521
|
-
logger.error(
|
|
522
|
-
`${_picocolors2.default.red(
|
|
523
|
-
`mock error at ${pathname}`
|
|
524
|
-
)}
|
|
525
|
-
${e}
|
|
526
|
-
at body (${_picocolors2.default.underline(filepath)})`,
|
|
527
|
-
logLevel
|
|
528
|
-
);
|
|
529
|
-
responseStatus(response, 500);
|
|
530
|
-
res.end("");
|
|
531
|
-
}
|
|
532
|
-
return;
|
|
533
|
-
}
|
|
534
|
-
if (responseFn) {
|
|
535
|
-
try {
|
|
536
|
-
await realDelay(startTime, delay);
|
|
537
|
-
await responseFn(request, response, next);
|
|
538
|
-
} catch (e) {
|
|
539
|
-
logger.error(
|
|
540
|
-
`${_picocolors2.default.red(
|
|
541
|
-
`mock error at ${pathname}`
|
|
542
|
-
)}
|
|
543
|
-
${e}
|
|
544
|
-
at response (${_picocolors2.default.underline(filepath)})`,
|
|
545
|
-
logLevel
|
|
546
|
-
);
|
|
547
|
-
responseStatus(response, 500);
|
|
548
|
-
res.end("");
|
|
549
|
-
}
|
|
550
|
-
return;
|
|
551
|
-
}
|
|
552
|
-
res.end("");
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
function fineMock(mockList, logger, {
|
|
556
|
-
pathname,
|
|
557
|
-
method,
|
|
558
|
-
request
|
|
559
|
-
}) {
|
|
560
|
-
return mockList.find((mock) => {
|
|
561
|
-
if (!pathname || !mock || !mock.url || mock.ws === true)
|
|
562
|
-
return false;
|
|
563
|
-
const methods = mock.method ? _utils.isArray.call(void 0, mock.method) ? mock.method : [mock.method] : ["GET", "POST"];
|
|
564
|
-
if (!methods.includes(method))
|
|
565
|
-
return false;
|
|
566
|
-
const hasMock = _pathtoregexp.pathToRegexp.call(void 0, mock.url).test(pathname);
|
|
567
|
-
if (hasMock && mock.validator) {
|
|
568
|
-
const params = parseParams(mock.url, pathname);
|
|
569
|
-
if (_utils.isFunction.call(void 0, mock.validator)) {
|
|
570
|
-
return mock.validator({ params, ...request });
|
|
571
|
-
} else {
|
|
572
|
-
try {
|
|
573
|
-
return validate({ params, ...request }, mock.validator);
|
|
574
|
-
} catch (e) {
|
|
575
|
-
const file = mock.__filepath__;
|
|
576
|
-
logger.error(
|
|
577
|
-
`${_picocolors2.default.red(
|
|
578
|
-
`mock error at ${pathname}`
|
|
579
|
-
)}
|
|
580
|
-
${e}
|
|
581
|
-
at validator (${_picocolors2.default.underline(file)})`,
|
|
582
|
-
mock.log
|
|
583
|
-
);
|
|
584
|
-
return false;
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
return hasMock;
|
|
589
|
-
});
|
|
590
|
-
}
|
|
591
|
-
function responseStatus(response, status = 200, statusText) {
|
|
592
|
-
response.statusCode = status;
|
|
593
|
-
response.statusMessage = statusText || getHTTPStatusText(status);
|
|
594
|
-
}
|
|
595
|
-
async function provideHeaders(req, res, mock, logger) {
|
|
596
|
-
const { headers, type = "json" } = mock;
|
|
597
|
-
const filepath = mock.__filepath__;
|
|
598
|
-
const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
|
|
599
|
-
if (contentType2)
|
|
600
|
-
res.setHeader("Content-Type", contentType2);
|
|
601
|
-
res.setHeader("Cache-Control", "no-cache,max-age=0");
|
|
602
|
-
res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
|
|
603
|
-
if (filepath)
|
|
604
|
-
res.setHeader("X-File-Path", filepath);
|
|
605
|
-
if (!headers)
|
|
606
|
-
return;
|
|
607
|
-
try {
|
|
608
|
-
const raw = _utils.isFunction.call(void 0, headers) ? await headers(req) : headers;
|
|
609
|
-
Object.keys(raw).forEach((key) => {
|
|
610
|
-
res.setHeader(key, raw[key]);
|
|
611
|
-
});
|
|
612
|
-
} catch (e) {
|
|
613
|
-
logger.error(
|
|
614
|
-
`${_picocolors2.default.red(
|
|
615
|
-
`mock error at ${req.url.split("?")[0]}`
|
|
616
|
-
)}
|
|
617
|
-
${e}
|
|
618
|
-
at headers (${_picocolors2.default.underline(filepath)})`,
|
|
619
|
-
mock.log
|
|
620
|
-
);
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
async function provideCookies(req, res, mock, logger) {
|
|
624
|
-
const { cookies } = mock;
|
|
625
|
-
const filepath = mock.__filepath__;
|
|
626
|
-
if (!cookies)
|
|
627
|
-
return;
|
|
628
|
-
try {
|
|
629
|
-
const raw = _utils.isFunction.call(void 0, cookies) ? await cookies(req) : cookies;
|
|
630
|
-
Object.keys(raw).forEach((key) => {
|
|
631
|
-
const cookie = raw[key];
|
|
632
|
-
if (_utils.isArray.call(void 0, cookie)) {
|
|
633
|
-
const [value, options] = cookie;
|
|
634
|
-
res.setCookie(key, value, options);
|
|
635
|
-
} else {
|
|
636
|
-
res.setCookie(key, cookie);
|
|
637
|
-
}
|
|
638
|
-
});
|
|
639
|
-
} catch (e) {
|
|
640
|
-
logger.error(
|
|
641
|
-
`${_picocolors2.default.red(
|
|
642
|
-
`mock error at ${req.url.split("?")[0]}`
|
|
643
|
-
)}
|
|
644
|
-
${e}
|
|
645
|
-
at cookies (${_picocolors2.default.underline(filepath)})`,
|
|
646
|
-
mock.log
|
|
647
|
-
);
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
function sendData(res, raw, type) {
|
|
651
|
-
if (isReadableStream(raw)) {
|
|
652
|
-
raw.pipe(res);
|
|
653
|
-
} else if (_buffer.Buffer.isBuffer(raw)) {
|
|
654
|
-
res.end(type === "text" || type === "json" ? raw.toString("utf-8") : raw);
|
|
655
|
-
} else {
|
|
656
|
-
const content = typeof raw === "string" ? raw : JSON.stringify(raw);
|
|
657
|
-
res.end(type === "buffer" ? _buffer.Buffer.from(content) : content);
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
async function realDelay(startTime, delay) {
|
|
661
|
-
if (!delay || typeof delay === "number" && delay <= 0 || _utils.isArray.call(void 0, delay) && delay.length !== 2) {
|
|
662
|
-
return;
|
|
663
|
-
}
|
|
664
|
-
let realDelay2 = 0;
|
|
665
|
-
if (_utils.isArray.call(void 0, delay)) {
|
|
666
|
-
const [min, max] = delay;
|
|
667
|
-
realDelay2 = _utils.random.call(void 0, min, max);
|
|
668
|
-
} else {
|
|
669
|
-
realDelay2 = delay - (_utils.timestamp.call(void 0, ) - startTime);
|
|
670
|
-
}
|
|
671
|
-
if (realDelay2 > 0)
|
|
672
|
-
await _utils.sleep.call(void 0, realDelay2);
|
|
673
|
-
}
|
|
674
|
-
function getHTTPStatusText(status) {
|
|
675
|
-
return _httpstatus2.default[status] || "Unknown";
|
|
676
|
-
}
|
|
677
|
-
function requestLog(request, filepath) {
|
|
678
|
-
const { url, method, query, params, body } = request;
|
|
679
|
-
let { pathname } = new URL(url, "http://example.com");
|
|
680
|
-
pathname = _picocolors2.default.green(decodeURIComponent(pathname));
|
|
681
|
-
const format = (prefix, data) => {
|
|
682
|
-
return !data || _utils.isEmptyObject.call(void 0, data) ? "" : ` ${_picocolors2.default.gray(`${prefix}:`)}${JSON.stringify(data)}`;
|
|
683
|
-
};
|
|
684
|
-
const ms = _picocolors2.default.magenta(_picocolors2.default.bold(method));
|
|
685
|
-
const qs = format("query", query);
|
|
686
|
-
const ps = format("params", params);
|
|
687
|
-
const bs = format("body", body);
|
|
688
|
-
const file = ` ${_picocolors2.default.dim(_picocolors2.default.underline(`(${filepath})`))}`;
|
|
689
|
-
return `${ms} ${pathname}${qs}${ps}${bs}${file}`;
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
// src/core/mockWebsocket.ts
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
var _ws = require('ws');
|
|
697
|
-
function mockWebSocket(compiler, httpServer, {
|
|
698
|
-
wsProxies: proxies,
|
|
699
|
-
cookiesOptions,
|
|
700
|
-
logger
|
|
701
|
-
}) {
|
|
702
|
-
const hmrMap = /* @__PURE__ */ new Map();
|
|
703
|
-
const poolMap = /* @__PURE__ */ new Map();
|
|
704
|
-
const wssContextMap = /* @__PURE__ */ new WeakMap();
|
|
705
|
-
const getWssMap = (mockUrl) => {
|
|
706
|
-
let wssMap = poolMap.get(mockUrl);
|
|
707
|
-
if (!wssMap)
|
|
708
|
-
poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
|
|
709
|
-
return wssMap;
|
|
710
|
-
};
|
|
711
|
-
const addHmr = (filepath, mockUrl) => {
|
|
712
|
-
let urlList = hmrMap.get(filepath);
|
|
713
|
-
if (!urlList)
|
|
714
|
-
hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
|
|
715
|
-
urlList.add(mockUrl);
|
|
716
|
-
};
|
|
717
|
-
const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
|
|
718
|
-
try {
|
|
719
|
-
_optionalChain([mock, 'access', _9 => _9.setup, 'optionalCall', _10 => _10(wss, context)]);
|
|
720
|
-
wss.on("close", () => wssMap.delete(pathname));
|
|
721
|
-
wss.on("error", (e) => {
|
|
722
|
-
logger.error(
|
|
723
|
-
`${_picocolors2.default.red(
|
|
724
|
-
`WebSocket mock error at ${wss.path}`
|
|
725
|
-
)}
|
|
726
|
-
${e}
|
|
727
|
-
at setup (${filepath})`,
|
|
728
|
-
mock.log
|
|
729
|
-
);
|
|
730
|
-
});
|
|
731
|
-
} catch (e) {
|
|
732
|
-
logger.error(
|
|
733
|
-
`${_picocolors2.default.red(
|
|
734
|
-
`WebSocket mock error at ${wss.path}`
|
|
735
|
-
)}
|
|
736
|
-
${e}
|
|
737
|
-
at setup (${filepath})`,
|
|
738
|
-
mock.log
|
|
739
|
-
);
|
|
740
|
-
}
|
|
741
|
-
};
|
|
742
|
-
const restartWss = (wssMap, wss, mock, pathname, filepath) => {
|
|
743
|
-
const { cleanupList, connectionList, context } = wssContextMap.get(wss);
|
|
744
|
-
cleanupRunner(cleanupList);
|
|
745
|
-
connectionList.forEach(({ ws }) => ws.removeAllListeners());
|
|
746
|
-
wss.removeAllListeners();
|
|
747
|
-
setupWss(wssMap, wss, mock, context, pathname, filepath);
|
|
748
|
-
connectionList.forEach(
|
|
749
|
-
({ ws, req }) => emitConnection(wss, ws, req, connectionList)
|
|
750
|
-
);
|
|
751
|
-
};
|
|
752
|
-
compiler.on("update", ({ filepath }) => {
|
|
753
|
-
if (!hmrMap.has(filepath))
|
|
754
|
-
return;
|
|
755
|
-
const mockUrlList = hmrMap.get(filepath);
|
|
756
|
-
if (!mockUrlList)
|
|
757
|
-
return;
|
|
758
|
-
for (const mockUrl of mockUrlList.values()) {
|
|
759
|
-
for (const mock of compiler.mockData[mockUrl]) {
|
|
760
|
-
if (!mock.ws || mock.__filepath__ !== filepath)
|
|
761
|
-
return;
|
|
762
|
-
const wssMap = getWssMap(mockUrl);
|
|
763
|
-
for (const [pathname, wss] of wssMap.entries())
|
|
764
|
-
restartWss(wssMap, wss, mock, pathname, filepath);
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
});
|
|
768
|
-
_optionalChain([httpServer, 'optionalAccess', _11 => _11.on, 'call', _12 => _12("upgrade", (req, socket, head) => {
|
|
769
|
-
const { pathname, query } = urlParse(req.url);
|
|
770
|
-
if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url, req))) {
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
const mockData = compiler.mockData;
|
|
774
|
-
const mockUrl = Object.keys(mockData).find((key) => {
|
|
775
|
-
return _pathtoregexp.pathToRegexp.call(void 0, key).test(pathname);
|
|
776
|
-
});
|
|
777
|
-
if (!mockUrl)
|
|
778
|
-
return;
|
|
779
|
-
const mock = mockData[mockUrl].find((mock2) => {
|
|
780
|
-
return mock2.url && mock2.ws && _pathtoregexp.pathToRegexp.call(void 0, mock2.url).test(pathname);
|
|
781
|
-
});
|
|
782
|
-
if (!mock)
|
|
783
|
-
return;
|
|
784
|
-
const filepath = mock.__filepath__;
|
|
785
|
-
addHmr(filepath, mockUrl);
|
|
786
|
-
const wssMap = getWssMap(mockUrl);
|
|
787
|
-
const wss = getWss(wssMap, pathname);
|
|
788
|
-
let wssContext = wssContextMap.get(wss);
|
|
789
|
-
if (!wssContext) {
|
|
790
|
-
const cleanupList = [];
|
|
791
|
-
const context = {
|
|
792
|
-
onCleanup: (cleanup) => cleanupList.push(cleanup)
|
|
793
|
-
};
|
|
794
|
-
wssContext = { cleanupList, context, connectionList: [] };
|
|
795
|
-
wssContextMap.set(wss, wssContext);
|
|
796
|
-
setupWss(wssMap, wss, mock, context, pathname, filepath);
|
|
797
|
-
}
|
|
798
|
-
const request = req;
|
|
799
|
-
const cookies = new (0, _cookies2.default)(req, req, cookiesOptions);
|
|
800
|
-
const { query: refererQuery } = urlParse(req.headers.referer || "");
|
|
801
|
-
request.query = query;
|
|
802
|
-
request.refererQuery = refererQuery;
|
|
803
|
-
request.params = parseParams(mockUrl, pathname);
|
|
804
|
-
request.getCookie = cookies.get.bind(cookies);
|
|
805
|
-
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
806
|
-
logger.info(
|
|
807
|
-
`${_picocolors2.default.magenta(_picocolors2.default.bold("WebSocket"))} ${_picocolors2.default.green(
|
|
808
|
-
req.url
|
|
809
|
-
)} connected ${_picocolors2.default.dim(`(${filepath})`)}`,
|
|
810
|
-
mock.log
|
|
811
|
-
);
|
|
812
|
-
wssContext.connectionList.push({ req: request, ws });
|
|
813
|
-
emitConnection(wss, ws, request, wssContext.connectionList);
|
|
814
|
-
});
|
|
815
|
-
})]);
|
|
816
|
-
_optionalChain([httpServer, 'optionalAccess', _13 => _13.on, 'call', _14 => _14("close", () => {
|
|
817
|
-
for (const wssMap of poolMap.values()) {
|
|
818
|
-
for (const wss of wssMap.values()) {
|
|
819
|
-
const wssContext = wssContextMap.get(wss);
|
|
820
|
-
cleanupRunner(wssContext.cleanupList);
|
|
821
|
-
wss.close();
|
|
822
|
-
}
|
|
823
|
-
wssMap.clear();
|
|
824
|
-
}
|
|
825
|
-
poolMap.clear();
|
|
826
|
-
hmrMap.clear();
|
|
827
|
-
})]);
|
|
828
|
-
}
|
|
829
|
-
function getWss(wssMap, pathname) {
|
|
830
|
-
let wss = wssMap.get(pathname);
|
|
831
|
-
if (!wss)
|
|
832
|
-
wssMap.set(pathname, wss = new (0, _ws.WebSocketServer)({ noServer: true }));
|
|
833
|
-
return wss;
|
|
834
|
-
}
|
|
835
|
-
function emitConnection(wss, ws, req, connectionList) {
|
|
836
|
-
wss.emit("connection", ws, req);
|
|
837
|
-
ws.on("close", () => {
|
|
838
|
-
const i = connectionList.findIndex((item) => item.ws === ws);
|
|
839
|
-
if (i !== -1)
|
|
840
|
-
connectionList.splice(i, 1);
|
|
841
|
-
});
|
|
842
|
-
}
|
|
843
|
-
function cleanupRunner(cleanupList) {
|
|
844
|
-
let cleanup;
|
|
845
|
-
while (cleanup = cleanupList.shift())
|
|
846
|
-
_optionalChain([cleanup, 'optionalCall', _15 => _15()]);
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
// src/core/logger.ts
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
var logLevels = {
|
|
853
|
-
silent: 0,
|
|
854
|
-
error: 1,
|
|
855
|
-
warn: 2,
|
|
856
|
-
info: 3,
|
|
857
|
-
debug: 4
|
|
858
|
-
};
|
|
859
|
-
function createLogger(prefix, defaultLevel = "info") {
|
|
860
|
-
prefix = `[${prefix}]`;
|
|
861
|
-
function output(type, msg, level) {
|
|
862
|
-
level = _utils.isBoolean.call(void 0, level) ? level ? defaultLevel : "error" : level;
|
|
863
|
-
const thresh = logLevels[level];
|
|
864
|
-
if (thresh >= logLevels[type]) {
|
|
865
|
-
const method = type === "info" || type === "debug" ? "log" : type;
|
|
866
|
-
const tag = type === "debug" ? _picocolors2.default.magenta(_picocolors2.default.bold(prefix)) : type === "info" ? _picocolors2.default.cyan(_picocolors2.default.bold(prefix)) : type === "warn" ? _picocolors2.default.yellow(_picocolors2.default.bold(prefix)) : _picocolors2.default.red(_picocolors2.default.bold(prefix));
|
|
867
|
-
const format = `${_picocolors2.default.dim(
|
|
868
|
-
(/* @__PURE__ */ new Date()).toLocaleTimeString()
|
|
869
|
-
)} ${tag} ${msg}`;
|
|
870
|
-
console[method](format);
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
const logger = {
|
|
874
|
-
debug(msg, level = defaultLevel) {
|
|
875
|
-
output("debug", msg, level);
|
|
876
|
-
},
|
|
877
|
-
info(msg, level = defaultLevel) {
|
|
878
|
-
output("info", msg, level);
|
|
879
|
-
},
|
|
880
|
-
warn(msg, level = defaultLevel) {
|
|
881
|
-
output("warn", msg, level);
|
|
882
|
-
},
|
|
883
|
-
error(msg, level = defaultLevel) {
|
|
884
|
-
output("error", msg, level);
|
|
885
|
-
}
|
|
886
|
-
};
|
|
887
|
-
return logger;
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
exports.packageDir = packageDir; exports.vfs = vfs; exports.lookupFile = lookupFile; exports.doesProxyContextMatchUrl = doesProxyContextMatchUrl; exports.urlParse = urlParse; exports.normalizePath = normalizePath; exports.waitingFor = waitingFor; exports.transformRawData = transformRawData; exports.transformMockData = transformMockData; exports.sortByValidator = sortByValidator; exports.rewriteRequest = rewriteRequest; exports.baseMiddleware = baseMiddleware; exports.mockWebSocket = mockWebSocket; exports.logLevels = logLevels; exports.createLogger = createLogger;
|