rspack-plugin-mock 1.2.0 → 1.3.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.
@@ -1,710 +0,0 @@
1
- import { isArray, isBoolean, isEmptyObject, isFunction, isPlainObject, isString, random, sleep, sortBy, timestamp, toArray, uniq } from "@pengzhanbo/utils";
2
- import path from "node:path";
3
- import fs from "node:fs";
4
- import color from "picocolors";
5
- import os from "node:os";
6
- import { parse } from "node:querystring";
7
- import { URL as URL$1, fileURLToPath } from "node:url";
8
- import Debug from "debug";
9
- import { Volume, createFsFromVolume } from "memfs";
10
- import { match, parse as parse$1, pathToRegexp } from "path-to-regexp";
11
- import { Buffer } from "node:buffer";
12
- import Cookies from "cookies";
13
- import HTTP_STATUS from "http-status";
14
- import * as mime from "mime-types";
15
- import bodyParser from "co-body";
16
- import formidable from "formidable";
17
- import { WebSocketServer } from "ws";
18
-
19
- //#region src/core/utils.ts
20
- const packageDir = getDirname(import.meta.url);
21
- const vfs = createFsFromVolume(new Volume());
22
- function isStream(stream) {
23
- return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
24
- }
25
- function isReadableStream(stream) {
26
- return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
27
- }
28
- function getDirname(importMetaUrl) {
29
- return path.dirname(fileURLToPath(importMetaUrl));
30
- }
31
- const debug = Debug("rspack:mock");
32
- function lookupFile(dir, formats, options) {
33
- for (const format of formats) {
34
- const fullPath = path.join(dir, format);
35
- if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
36
- const result = options?.pathOnly ? fullPath : fs.readFileSync(fullPath, "utf-8");
37
- if (!options?.predicate || options.predicate(result)) return result;
38
- }
39
- }
40
- const parentDir = path.dirname(dir);
41
- if (parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir))) return lookupFile(parentDir, formats, options);
42
- }
43
- function doesProxyContextMatchUrl(context, url, req) {
44
- if (typeof context === "function") return context(url, req);
45
- return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
46
- }
47
- function parseParams(pattern, url) {
48
- const urlMatch = match(pattern, { decode: decodeURIComponent })(url) || { params: {} };
49
- return urlMatch.params || {};
50
- }
51
- /**
52
- * nodejs 从 19.0.0 开始 弃用 url.parse,因此使用 url.parse 来解析 可能会报错,
53
- * 使用 URL 来解析
54
- */
55
- function urlParse(input) {
56
- const url = new URL$1(input, "http://example.com");
57
- const pathname = decodeURIComponent(url.pathname);
58
- const query = parse(url.search.replace(/^\?/, ""));
59
- return {
60
- pathname,
61
- query
62
- };
63
- }
64
- const windowsSlashRE = /\\/g;
65
- const isWindows = os.platform() === "win32";
66
- function slash(p) {
67
- return p.replace(windowsSlashRE, "/");
68
- }
69
- function normalizePath(id) {
70
- return path.posix.normalize(isWindows ? slash(id) : id);
71
- }
72
- function waitingFor(onSuccess, maxRetry = 5) {
73
- return function wait(getter, retry = 0) {
74
- const value = getter();
75
- if (value) onSuccess(value);
76
- else if (retry < maxRetry) setTimeout(() => wait(getter, retry + 1), 100);
77
- };
78
- }
79
-
80
- //#endregion
81
- //#region src/core/validator.ts
82
- function validate(request, validator) {
83
- 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);
84
- }
85
- /**
86
- * Checks if target object is a subset of source object.
87
- * That is, all properties and their corresponding values in target exist in source.
88
- *
89
- * 深度比较两个对象之间,target 是否属于 source 的子集,
90
- * 即 target 的所有属性和对应的值,都在 source 中,
91
- */
92
- function isObjectSubset(source, target) {
93
- if (!target) return true;
94
- for (const key in target) if (!isIncluded(source[key], target[key])) return false;
95
- return true;
96
- }
97
- function isIncluded(source, target) {
98
- if (isArray(source) && isArray(target)) {
99
- const seen = /* @__PURE__ */ new Set();
100
- return target.every((ti) => source.some((si, i) => {
101
- if (seen.has(i)) return false;
102
- const included = isIncluded(si, ti);
103
- if (included) seen.add(i);
104
- return included;
105
- }));
106
- }
107
- if (isPlainObject(source) && isPlainObject(target)) return isObjectSubset(source, target);
108
- return Object.is(source, target);
109
- }
110
-
111
- //#endregion
112
- //#region src/core/transform.ts
113
- function transformRawData(rawData) {
114
- return rawData.filter((item) => item[0]).map(([raw, __filepath__]) => {
115
- let mockConfig;
116
- if (raw.default) if (Array.isArray(raw.default)) mockConfig = raw.default.map((item) => ({
117
- ...item,
118
- __filepath__
119
- }));
120
- else mockConfig = {
121
- ...raw.default,
122
- __filepath__
123
- };
124
- else if ("url" in raw) mockConfig = {
125
- ...raw,
126
- __filepath__
127
- };
128
- else {
129
- mockConfig = [];
130
- Object.keys(raw || {}).forEach((key) => {
131
- if (Array.isArray(raw[key])) mockConfig.push(...raw[key].map((item) => ({
132
- ...item,
133
- __filepath__
134
- })));
135
- else mockConfig.push({
136
- ...raw[key],
137
- __filepath__
138
- });
139
- });
140
- }
141
- return mockConfig;
142
- });
143
- }
144
- function transformMockData(mockList) {
145
- const list = [];
146
- for (const [, handle] of mockList.entries()) if (handle) list.push(...toArray(handle));
147
- const mocks = {};
148
- list.filter((mock) => isPlainObject(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
149
- const { pathname, query } = urlParse(mock.url);
150
- const list$1 = mocks[pathname] ??= [];
151
- const current = {
152
- ...mock,
153
- url: pathname
154
- };
155
- if (current.ws !== true) {
156
- const validator = current.validator;
157
- if (!isEmptyObject(query)) if (isFunction(validator)) current.validator = function(request) {
158
- return isObjectSubset(request.query, query) && validator(request);
159
- };
160
- else if (validator) {
161
- current.validator = { ...validator };
162
- current.validator.query = current.validator.query ? {
163
- ...query,
164
- ...current.validator.query
165
- } : query;
166
- } else current.validator = { query };
167
- }
168
- list$1.push(current);
169
- });
170
- Object.keys(mocks).forEach((key) => {
171
- mocks[key] = sortByValidator(mocks[key]);
172
- });
173
- return mocks;
174
- }
175
- function sortByValidator(mocks) {
176
- return sortBy(mocks, (item) => {
177
- if (item.ws === true) return 0;
178
- const { validator } = item;
179
- if (!validator || isEmptyObject(validator)) return 2;
180
- if (isFunction(validator)) return 0;
181
- const count = Object.keys(validator).reduce((prev, key) => prev + keysCount(validator[key]), 0);
182
- return 1 / count;
183
- });
184
- }
185
- function keysCount(obj) {
186
- if (!obj) return 0;
187
- return Object.keys(obj).length;
188
- }
189
-
190
- //#endregion
191
- //#region src/core/matchingWeight.ts
192
- const tokensCache = {};
193
- function getTokens(rule) {
194
- if (tokensCache[rule]) return tokensCache[rule];
195
- const tks = parse$1(rule);
196
- const tokens = [];
197
- for (const tk of tks) if (!isString(tk)) tokens.push(tk);
198
- else {
199
- const hasPrefix = tk[0] === "/";
200
- const subTks = hasPrefix ? tk.slice(1).split("/") : tk.split("/");
201
- tokens.push(`${hasPrefix ? "/" : ""}${subTks[0]}`, ...subTks.slice(1).map((t) => `/${t}`));
202
- }
203
- tokensCache[rule] = tokens;
204
- return tokens;
205
- }
206
- function getHighest(rules) {
207
- let weights = rules.map((rule) => getTokens(rule).length);
208
- weights = weights.length === 0 ? [1] : weights;
209
- return Math.max(...weights) + 2;
210
- }
211
- function sortFn(rule) {
212
- const tokens = getTokens(rule);
213
- let w = 0;
214
- for (let i = 0; i < tokens.length; i++) {
215
- const token = tokens[i];
216
- if (!isString(token)) w += 10 ** (i + 1);
217
- w += 10 ** (i + 1);
218
- }
219
- return w;
220
- }
221
- function preSort(rules) {
222
- let matched = [];
223
- const preMatch = [];
224
- for (const rule of rules) {
225
- const tokens = getTokens(rule);
226
- const len = tokens.filter((token) => typeof token !== "string").length;
227
- if (!preMatch[len]) preMatch[len] = [];
228
- preMatch[len].push(rule);
229
- }
230
- for (const match$1 of preMatch.filter((v) => v && v.length > 0)) matched = [...matched, ...sortBy(match$1, sortFn).reverse()];
231
- return matched;
232
- }
233
- function defaultPriority(rules) {
234
- const highest = getHighest(rules);
235
- return sortBy(rules, (rule) => {
236
- const tokens = getTokens(rule);
237
- const dym = tokens.filter((token) => typeof token !== "string");
238
- if (dym.length === 0) return 0;
239
- let weight = dym.length;
240
- let exp = 0;
241
- for (let i = 0; i < tokens.length; i++) {
242
- const token = tokens[i];
243
- const isDynamic = !isString(token);
244
- const { pattern = "", modifier, prefix, name } = isDynamic ? token : {};
245
- const isGlob = pattern && pattern.includes(".*");
246
- const isSlash = prefix === "/";
247
- const isNamed = isString(name);
248
- exp += isDynamic && isSlash ? 1 : 0;
249
- if (i === tokens.length - 1 && isGlob) weight += 5 * 10 ** (tokens.length === 1 ? highest + 1 : highest);
250
- else if (isGlob) weight += 3 * 10 ** (highest - 1);
251
- else if (pattern) if (isSlash) weight += (isNamed ? 2 : 1) * 10 ** (exp + 1);
252
- else weight -= 1 * 10 ** exp;
253
- if (modifier === "+") weight += 1 * 10 ** (highest - 1);
254
- if (modifier === "*") weight += 1 * 10 ** (highest - 1) + 1;
255
- if (modifier === "?") weight += 1 * 10 ** (exp + (isSlash ? 1 : 0));
256
- }
257
- return weight;
258
- });
259
- }
260
- function matchingWeight(rules, url, priority) {
261
- let matched = defaultPriority(preSort(rules.filter((rule) => pathToRegexp(rule).test(url))));
262
- const { global = [], special = {} } = priority;
263
- if (global.length === 0 && isEmptyObject(special) || matched.length === 0) return matched;
264
- const [statics, dynamics] = twoPartMatch(matched);
265
- const globalMatch = global.filter((rule) => dynamics.includes(rule));
266
- if (globalMatch.length > 0) matched = uniq([
267
- ...statics,
268
- ...globalMatch,
269
- ...dynamics
270
- ]);
271
- if (isEmptyObject(special)) return matched;
272
- const specialRule = Object.keys(special).filter((rule) => matched.includes(rule))[0];
273
- if (!specialRule) return matched;
274
- const options = special[specialRule];
275
- const { rules: lowerRules, when } = isArray(options) ? {
276
- rules: options,
277
- when: []
278
- } : options;
279
- if (lowerRules.includes(matched[0])) {
280
- if (when.length === 0 || when.some((path$1) => pathToRegexp(path$1).test(url))) matched = uniq([specialRule, ...matched]);
281
- }
282
- return matched;
283
- }
284
- function twoPartMatch(rules) {
285
- const statics = [];
286
- const dynamics = [];
287
- for (const rule of rules) {
288
- const tokens = getTokens(rule);
289
- const dym = tokens.filter((token) => typeof token !== "string");
290
- if (dym.length > 0) dynamics.push(rule);
291
- else statics.push(rule);
292
- }
293
- return [statics, dynamics];
294
- }
295
-
296
- //#endregion
297
- //#region src/core/parseReqBody.ts
298
- const DEFAULT_FORMIDABLE_OPTIONS = {
299
- keepExtensions: true,
300
- filename(name, ext, part) {
301
- return part?.originalFilename || `${name}.${Date.now()}${ext ? `.${ext}` : ""}`;
302
- }
303
- };
304
- async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
305
- const method = req.method.toUpperCase();
306
- if ([
307
- "GET",
308
- "DELETE",
309
- "HEAD"
310
- ].includes(method)) return void 0;
311
- const type = req.headers["content-type"]?.toLocaleLowerCase() || "";
312
- const { limit, formLimit, jsonLimit, textLimit,...rest } = bodyParserOptions;
313
- try {
314
- if (type.startsWith("application/json")) return await bodyParser.json(req, {
315
- limit: jsonLimit || limit,
316
- ...rest
317
- });
318
- if (type.startsWith("application/x-www-form-urlencoded")) return await bodyParser.form(req, {
319
- limit: formLimit || limit,
320
- ...rest
321
- });
322
- if (type.startsWith("text/plain")) return await bodyParser.text(req, {
323
- limit: textLimit || limit,
324
- ...rest
325
- });
326
- if (type.startsWith("multipart/form-data")) return await parseMultipart(req, formidableOptions);
327
- } catch (e) {
328
- console.error(e);
329
- }
330
- return void 0;
331
- }
332
- async function parseMultipart(req, options) {
333
- const form = formidable({
334
- ...DEFAULT_FORMIDABLE_OPTIONS,
335
- ...options
336
- });
337
- return new Promise((resolve, reject) => {
338
- form.parse(req, (error, fields, files) => {
339
- if (error) {
340
- reject(error);
341
- return;
342
- }
343
- resolve({
344
- ...fields,
345
- ...files
346
- });
347
- });
348
- });
349
- }
350
-
351
- //#endregion
352
- //#region src/core/requestRecovery.ts
353
- const requestCollectCache = /* @__PURE__ */ new WeakMap();
354
- function collectRequest(req) {
355
- const chunks = [];
356
- req.addListener("data", (chunk) => {
357
- chunks.push(Buffer.from(chunk));
358
- });
359
- req.addListener("end", () => {
360
- if (chunks.length) requestCollectCache.set(req, Buffer.concat(chunks));
361
- });
362
- }
363
- function rewriteRequest(proxyReq, req) {
364
- const buffer = requestCollectCache.get(req);
365
- if (buffer) {
366
- requestCollectCache.delete(req);
367
- if (!proxyReq.headersSent) proxyReq.setHeader("Content-Length", buffer.byteLength);
368
- if (!proxyReq.writableEnded) proxyReq.write(buffer);
369
- }
370
- }
371
-
372
- //#endregion
373
- //#region src/core/baseMiddleware.ts
374
- function baseMiddleware(compiler, { formidableOptions = {}, bodyParserOptions = {}, proxies, cookiesOptions, logger, priority = {} }) {
375
- return async function(req, res, next) {
376
- const startTime = timestamp();
377
- const { query, pathname } = urlParse(req.url);
378
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url, req))) return next();
379
- const mockData = compiler.mockData;
380
- const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
381
- if (mockUrls.length === 0) return next();
382
- collectRequest(req);
383
- const { query: refererQuery } = urlParse(req.headers.referer || "");
384
- const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
385
- const cookies = new Cookies(req, res, cookiesOptions);
386
- const getCookie = cookies.get.bind(cookies);
387
- const method = req.method.toUpperCase();
388
- let mock;
389
- let _mockUrl;
390
- for (const mockUrl of mockUrls) {
391
- mock = fineMock(mockData[mockUrl], logger, {
392
- pathname,
393
- method,
394
- request: {
395
- query,
396
- refererQuery,
397
- body: reqBody,
398
- headers: req.headers,
399
- getCookie
400
- }
401
- });
402
- if (mock) {
403
- _mockUrl = mockUrl;
404
- break;
405
- }
406
- }
407
- if (!mock) {
408
- const matched = mockUrls.map((m) => m === _mockUrl ? color.underline(color.bold(m)) : color.dim(m)).join(", ");
409
- logger.warn(`${color.green(pathname)} matches ${matched} , but mock data is not found.`);
410
- return next();
411
- }
412
- const request = req;
413
- const response = res;
414
- request.body = reqBody;
415
- request.query = query;
416
- request.refererQuery = refererQuery;
417
- request.params = parseParams(mock.url, pathname);
418
- request.getCookie = getCookie;
419
- response.setCookie = cookies.set.bind(cookies);
420
- const { body, delay, type = "json", response: responseFn, status = 200, statusText, log: logLevel, __filepath__: filepath } = mock;
421
- responseStatus(response, status, statusText);
422
- await provideHeaders(request, response, mock, logger);
423
- await provideCookies(request, response, mock, logger);
424
- logger.info(requestLog(request, filepath), logLevel);
425
- logger.debug(`${color.magenta("DEBUG")} ${color.underline(pathname)} matches: [ ${mockUrls.map((m) => m === _mockUrl ? color.underline(color.bold(m)) : color.dim(m)).join(", ")} ]\n`);
426
- if (body) {
427
- try {
428
- const content = isFunction(body) ? await body(request) : body;
429
- await realDelay(startTime, delay);
430
- sendData(response, content, type);
431
- } catch (e) {
432
- logger.error(`${color.red(`mock error at ${pathname}`)}\n${e}\n at body (${color.underline(filepath)})`, logLevel);
433
- responseStatus(response, 500);
434
- res.end("");
435
- }
436
- return;
437
- }
438
- if (responseFn) {
439
- try {
440
- await realDelay(startTime, delay);
441
- await responseFn(request, response, next);
442
- } catch (e) {
443
- logger.error(`${color.red(`mock error at ${pathname}`)}\n${e}\n at response (${color.underline(filepath)})`, logLevel);
444
- responseStatus(response, 500);
445
- res.end("");
446
- }
447
- return;
448
- }
449
- res.end("");
450
- };
451
- }
452
- function fineMock(mockList, logger, { pathname, method, request }) {
453
- return mockList.find((mock) => {
454
- if (!pathname || !mock || !mock.url || mock.ws === true) return false;
455
- const methods = mock.method ? isArray(mock.method) ? mock.method : [mock.method] : ["GET", "POST"];
456
- if (!methods.includes(method)) return false;
457
- const hasMock = pathToRegexp(mock.url).test(pathname);
458
- if (hasMock && mock.validator) {
459
- const params = parseParams(mock.url, pathname);
460
- if (isFunction(mock.validator)) return mock.validator({
461
- params,
462
- ...request
463
- });
464
- else try {
465
- return validate({
466
- params,
467
- ...request
468
- }, mock.validator);
469
- } catch (e) {
470
- const file = mock.__filepath__;
471
- logger.error(`${color.red(`mock error at ${pathname}`)}\n${e}\n at validator (${color.underline(file)})`, mock.log);
472
- return false;
473
- }
474
- }
475
- return hasMock;
476
- });
477
- }
478
- function responseStatus(response, status = 200, statusText) {
479
- response.statusCode = status;
480
- response.statusMessage = statusText || getHTTPStatusText(status);
481
- }
482
- async function provideHeaders(req, res, mock, logger) {
483
- const { headers, type = "json" } = mock;
484
- const filepath = mock.__filepath__;
485
- const contentType = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
486
- if (contentType) res.setHeader("Content-Type", contentType);
487
- res.setHeader("Cache-Control", "no-cache,max-age=0");
488
- res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
489
- if (filepath) res.setHeader("X-File-Path", filepath);
490
- if (!headers) return;
491
- try {
492
- const raw = isFunction(headers) ? await headers(req) : headers;
493
- Object.keys(raw).forEach((key) => {
494
- res.setHeader(key, raw[key]);
495
- });
496
- } catch (e) {
497
- logger.error(`${color.red(`mock error at ${req.url.split("?")[0]}`)}\n${e}\n at headers (${color.underline(filepath)})`, mock.log);
498
- }
499
- }
500
- async function provideCookies(req, res, mock, logger) {
501
- const { cookies } = mock;
502
- const filepath = mock.__filepath__;
503
- if (!cookies) return;
504
- try {
505
- const raw = isFunction(cookies) ? await cookies(req) : cookies;
506
- Object.keys(raw).forEach((key) => {
507
- const cookie = raw[key];
508
- if (isArray(cookie)) {
509
- const [value, options] = cookie;
510
- res.setCookie(key, value, options);
511
- } else res.setCookie(key, cookie);
512
- });
513
- } catch (e) {
514
- logger.error(`${color.red(`mock error at ${req.url.split("?")[0]}`)}\n${e}\n at cookies (${color.underline(filepath)})`, mock.log);
515
- }
516
- }
517
- function sendData(res, raw, type) {
518
- if (isReadableStream(raw)) raw.pipe(res);
519
- else if (Buffer.isBuffer(raw)) res.end(type === "text" || type === "json" ? raw.toString("utf-8") : raw);
520
- else {
521
- const content = typeof raw === "string" ? raw : JSON.stringify(raw);
522
- res.end(type === "buffer" ? Buffer.from(content) : content);
523
- }
524
- }
525
- async function realDelay(startTime, delay) {
526
- if (!delay || typeof delay === "number" && delay <= 0 || isArray(delay) && delay.length !== 2) return;
527
- let realDelay$1 = 0;
528
- if (isArray(delay)) {
529
- const [min, max] = delay;
530
- realDelay$1 = random(min, max);
531
- } else realDelay$1 = delay - (timestamp() - startTime);
532
- if (realDelay$1 > 0) await sleep(realDelay$1);
533
- }
534
- function getHTTPStatusText(status) {
535
- return HTTP_STATUS[status] || "Unknown";
536
- }
537
- function requestLog(request, filepath) {
538
- const { url, method, query, params, body } = request;
539
- let { pathname } = new URL(url, "http://example.com");
540
- pathname = color.green(decodeURIComponent(pathname));
541
- const format = (prefix, data) => {
542
- return !data || isEmptyObject(data) ? "" : ` ${color.gray(`${prefix}:`)}${JSON.stringify(data)}`;
543
- };
544
- const ms = color.magenta(color.bold(method));
545
- const qs = format("query", query);
546
- const ps = format("params", params);
547
- const bs = format("body", body);
548
- const file = ` ${color.dim(color.underline(`(${filepath})`))}`;
549
- return `${ms} ${pathname}${qs}${ps}${bs}${file}`;
550
- }
551
-
552
- //#endregion
553
- //#region src/core/mockWebsocket.ts
554
- function mockWebSocket(compiler, httpServer, { wsProxies: proxies, cookiesOptions, logger }) {
555
- const hmrMap = /* @__PURE__ */ new Map();
556
- const poolMap = /* @__PURE__ */ new Map();
557
- const wssContextMap = /* @__PURE__ */ new WeakMap();
558
- const getWssMap = (mockUrl) => {
559
- let wssMap = poolMap.get(mockUrl);
560
- if (!wssMap) poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
561
- return wssMap;
562
- };
563
- const addHmr = (filepath, mockUrl) => {
564
- let urlList = hmrMap.get(filepath);
565
- if (!urlList) hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
566
- urlList.add(mockUrl);
567
- };
568
- const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
569
- try {
570
- mock.setup?.(wss, context);
571
- wss.on("close", () => wssMap.delete(pathname));
572
- wss.on("error", (e) => {
573
- logger.error(`${color.red(`WebSocket mock error at ${wss.path}`)}\n${e}\n at setup (${filepath})`, mock.log);
574
- });
575
- } catch (e) {
576
- logger.error(`${color.red(`WebSocket mock error at ${wss.path}`)}\n${e}\n at setup (${filepath})`, mock.log);
577
- }
578
- };
579
- const restartWss = (wssMap, wss, mock, pathname, filepath) => {
580
- const { cleanupList, connectionList, context } = wssContextMap.get(wss);
581
- cleanupRunner(cleanupList);
582
- connectionList.forEach(({ ws }) => ws.removeAllListeners());
583
- wss.removeAllListeners();
584
- setupWss(wssMap, wss, mock, context, pathname, filepath);
585
- connectionList.forEach(({ ws, req }) => emitConnection(wss, ws, req, connectionList));
586
- };
587
- compiler.on("update", ({ filepath }) => {
588
- if (!hmrMap.has(filepath)) return;
589
- const mockUrlList = hmrMap.get(filepath);
590
- if (!mockUrlList) return;
591
- for (const mockUrl of mockUrlList.values()) for (const mock of compiler.mockData[mockUrl]) {
592
- if (!mock.ws || mock.__filepath__ !== filepath) return;
593
- const wssMap = getWssMap(mockUrl);
594
- for (const [pathname, wss] of wssMap.entries()) restartWss(wssMap, wss, mock, pathname, filepath);
595
- }
596
- });
597
- httpServer?.on("upgrade", (req, socket, head) => {
598
- const { pathname, query } = urlParse(req.url);
599
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url, req))) return;
600
- const mockData = compiler.mockData;
601
- const mockUrl = Object.keys(mockData).find((key) => {
602
- return pathToRegexp(key).test(pathname);
603
- });
604
- if (!mockUrl) return;
605
- const mock = mockData[mockUrl].find((mock$1) => {
606
- return mock$1.url && mock$1.ws && pathToRegexp(mock$1.url).test(pathname);
607
- });
608
- if (!mock) return;
609
- const filepath = mock.__filepath__;
610
- addHmr(filepath, mockUrl);
611
- const wssMap = getWssMap(mockUrl);
612
- const wss = getWss(wssMap, pathname);
613
- let wssContext = wssContextMap.get(wss);
614
- if (!wssContext) {
615
- const cleanupList = [];
616
- const context = { onCleanup: (cleanup) => cleanupList.push(cleanup) };
617
- wssContext = {
618
- cleanupList,
619
- context,
620
- connectionList: []
621
- };
622
- wssContextMap.set(wss, wssContext);
623
- setupWss(wssMap, wss, mock, context, pathname, filepath);
624
- }
625
- const request = req;
626
- const cookies = new Cookies(req, req, cookiesOptions);
627
- const { query: refererQuery } = urlParse(req.headers.referer || "");
628
- request.query = query;
629
- request.refererQuery = refererQuery;
630
- request.params = parseParams(mockUrl, pathname);
631
- request.getCookie = cookies.get.bind(cookies);
632
- wss.handleUpgrade(request, socket, head, (ws) => {
633
- logger.info(`${color.magenta(color.bold("WebSocket"))} ${color.green(req.url)} connected ${color.dim(`(${filepath})`)}`, mock.log);
634
- wssContext.connectionList.push({
635
- req: request,
636
- ws
637
- });
638
- emitConnection(wss, ws, request, wssContext.connectionList);
639
- });
640
- });
641
- httpServer?.on("close", () => {
642
- for (const wssMap of poolMap.values()) {
643
- for (const wss of wssMap.values()) {
644
- const wssContext = wssContextMap.get(wss);
645
- cleanupRunner(wssContext.cleanupList);
646
- wss.close();
647
- }
648
- wssMap.clear();
649
- }
650
- poolMap.clear();
651
- hmrMap.clear();
652
- });
653
- }
654
- function getWss(wssMap, pathname) {
655
- let wss = wssMap.get(pathname);
656
- if (!wss) wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
657
- return wss;
658
- }
659
- function emitConnection(wss, ws, req, connectionList) {
660
- wss.emit("connection", ws, req);
661
- ws.on("close", () => {
662
- const i = connectionList.findIndex((item) => item.ws === ws);
663
- if (i !== -1) connectionList.splice(i, 1);
664
- });
665
- }
666
- function cleanupRunner(cleanupList) {
667
- let cleanup;
668
- while (cleanup = cleanupList.shift()) cleanup?.();
669
- }
670
-
671
- //#endregion
672
- //#region src/core/logger.ts
673
- const logLevels = {
674
- silent: 0,
675
- error: 1,
676
- warn: 2,
677
- info: 3,
678
- debug: 4
679
- };
680
- function createLogger(prefix, defaultLevel = "info") {
681
- prefix = `[${prefix}]`;
682
- function output(type, msg, level) {
683
- level = isBoolean(level) ? level ? defaultLevel : "error" : level;
684
- const thresh = logLevels[level];
685
- if (thresh >= logLevels[type]) {
686
- const method = type === "info" || type === "debug" ? "log" : type;
687
- const tag = type === "debug" ? color.magenta(color.bold(prefix)) : type === "info" ? color.cyan(color.bold(prefix)) : type === "warn" ? color.yellow(color.bold(prefix)) : color.red(color.bold(prefix));
688
- const format = `${color.dim((/* @__PURE__ */ new Date()).toLocaleTimeString())} ${tag} ${msg}`;
689
- console[method](format);
690
- }
691
- }
692
- const logger = {
693
- debug(msg, level = defaultLevel) {
694
- output("debug", msg, level);
695
- },
696
- info(msg, level = defaultLevel) {
697
- output("info", msg, level);
698
- },
699
- warn(msg, level = defaultLevel) {
700
- output("warn", msg, level);
701
- },
702
- error(msg, level = defaultLevel) {
703
- output("error", msg, level);
704
- }
705
- };
706
- return logger;
707
- }
708
-
709
- //#endregion
710
- export { baseMiddleware, createLogger, doesProxyContextMatchUrl, logLevels, lookupFile, mockWebSocket, normalizePath, packageDir, rewriteRequest, sortByValidator, transformMockData, transformRawData, urlParse, vfs, waitingFor };