rspack-plugin-mock 0.2.0 → 0.3.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 +110 -15
- package/README.zh-CN.md +888 -0
- package/dist/chunk-4GMRSIIN.cjs +543 -0
- package/dist/chunk-B5W3PWCX.js +543 -0
- package/dist/{chunk-UJAKORAH.js → chunk-EY46RSAC.js} +90 -433
- package/dist/{chunk-2S4KCTKW.cjs → chunk-ZEC4FWWY.cjs} +90 -433
- package/dist/helper.cjs +16 -5
- package/dist/helper.d.cts +2 -2
- package/dist/helper.d.ts +2 -2
- package/dist/helper.js +15 -4
- package/dist/index.cjs +88 -5
- package/dist/index.d.cts +13 -49
- package/dist/index.d.ts +13 -49
- package/dist/index.js +95 -12
- package/dist/mockWebsocket-CPuTAvL0.d.ts +76 -0
- package/dist/mockWebsocket-Dc9CZBfv.d.cts +76 -0
- package/dist/rsbuild.cjs +87 -64
- package/dist/rsbuild.d.cts +1 -1
- package/dist/rsbuild.d.ts +1 -1
- package/dist/rsbuild.js +79 -56
- package/dist/server.cjs +18 -0
- package/dist/server.d.cts +31 -0
- package/dist/server.d.ts +31 -0
- package/dist/server.js +18 -0
- package/dist/{types-C770q3L0.d.cts → types-BgpcN3jm.d.cts} +1 -1
- package/dist/{types-C770q3L0.d.ts → types-BgpcN3jm.d.ts} +1 -1
- package/package.json +15 -14
- package/dist/chunk-HTOWPFQ7.js +0 -20
- package/dist/chunk-KE2LVHUP.cjs +0 -20
- package/dist/chunk-P6DRAHHI.js +0 -90
- package/dist/chunk-T4AI3L6R.cjs +0 -90
- package/dist/rspack-BcdszmoI.d.cts +0 -29
- package/dist/rspack-E_yBzR5v.d.ts +0 -29
- package/dist/rspack.cjs +0 -9
- package/dist/rspack.d.cts +0 -11
- package/dist/rspack.d.ts +0 -11
- package/dist/rspack.js +0 -9
|
@@ -1,73 +1,4 @@
|
|
|
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; }
|
|
2
|
-
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
3
|
-
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
4
|
-
var _querystring = require('querystring');
|
|
5
|
-
var _url = require('url');
|
|
6
|
-
var _os = require('os'); var _os2 = _interopRequireDefault(_os);
|
|
7
|
-
var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug);
|
|
8
|
-
var _pathtoregexp = require('path-to-regexp');
|
|
9
|
-
function isStream(stream) {
|
|
10
|
-
return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
|
|
11
|
-
}
|
|
12
|
-
function isReadableStream(stream) {
|
|
13
|
-
return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
|
|
14
|
-
}
|
|
15
|
-
function getDirname(importMetaUrl) {
|
|
16
|
-
return _path2.default.dirname(_url.fileURLToPath.call(void 0, importMetaUrl));
|
|
17
|
-
}
|
|
18
|
-
var debug = _debug2.default.call(void 0, "rspack:mock");
|
|
19
|
-
function lookupFile(dir, formats, options) {
|
|
20
|
-
for (const format of formats) {
|
|
21
|
-
const fullPath = _path2.default.join(dir, format);
|
|
22
|
-
if (_fs2.default.existsSync(fullPath) && _fs2.default.statSync(fullPath).isFile()) {
|
|
23
|
-
const result = _optionalChain([options, 'optionalAccess', _ => _.pathOnly]) ? fullPath : _fs2.default.readFileSync(fullPath, "utf-8");
|
|
24
|
-
if (!_optionalChain([options, 'optionalAccess', _2 => _2.predicate]) || options.predicate(result))
|
|
25
|
-
return result;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
const parentDir = _path2.default.dirname(dir);
|
|
29
|
-
if (parentDir !== dir && (!_optionalChain([options, 'optionalAccess', _3 => _3.rootDir]) || parentDir.startsWith(_optionalChain([options, 'optionalAccess', _4 => _4.rootDir])))) {
|
|
30
|
-
return lookupFile(parentDir, formats, options);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
function doesProxyContextMatchUrl(context, url, req) {
|
|
34
|
-
if (typeof context === "function") {
|
|
35
|
-
return context(url, req);
|
|
36
|
-
}
|
|
37
|
-
return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
|
|
38
|
-
}
|
|
39
|
-
function parseParams(pattern, url) {
|
|
40
|
-
const urlMatch = _pathtoregexp.match.call(void 0, pattern, { decode: decodeURIComponent })(url) || {
|
|
41
|
-
params: {}
|
|
42
|
-
};
|
|
43
|
-
return urlMatch.params || {};
|
|
44
|
-
}
|
|
45
|
-
function urlParse(input) {
|
|
46
|
-
const url = new (0, _url.URL)(input, "http://example.com");
|
|
47
|
-
const pathname = decodeURIComponent(url.pathname);
|
|
48
|
-
const query = _querystring.parse.call(void 0, url.search.replace(/^\?/, ""));
|
|
49
|
-
return { pathname, query };
|
|
50
|
-
}
|
|
51
|
-
var windowsSlashRE = /\\/g;
|
|
52
|
-
var isWindows = _os2.default.platform() === "win32";
|
|
53
|
-
function slash(p) {
|
|
54
|
-
return p.replace(windowsSlashRE, "/");
|
|
55
|
-
}
|
|
56
|
-
function normalizePath(id) {
|
|
57
|
-
return _path2.default.posix.normalize(isWindows ? slash(id) : id);
|
|
58
|
-
}
|
|
59
|
-
function waitingFor(onSuccess, maxRetry = 5) {
|
|
60
|
-
return function wait(getter, retry = 0) {
|
|
61
|
-
const value = getter();
|
|
62
|
-
if (value) {
|
|
63
|
-
onSuccess(value);
|
|
64
|
-
} else if (retry < maxRetry) {
|
|
65
|
-
setTimeout(() => wait(getter, retry + 1), 100);
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// src/core/requestRecovery.ts
|
|
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/requestRecovery.ts
|
|
71
2
|
var _buffer = require('buffer');
|
|
72
3
|
var requestCollectCache = /* @__PURE__ */ new WeakMap();
|
|
73
4
|
function collectRequest(req) {
|
|
@@ -91,10 +22,6 @@ function rewriteRequest(proxyReq, req) {
|
|
|
91
22
|
}
|
|
92
23
|
}
|
|
93
24
|
|
|
94
|
-
// src/core/mockMiddleware.ts
|
|
95
|
-
var _cors = require('cors'); var _cors2 = _interopRequireDefault(_cors);
|
|
96
|
-
|
|
97
|
-
|
|
98
25
|
// src/core/baseMiddleware.ts
|
|
99
26
|
|
|
100
27
|
|
|
@@ -108,7 +35,7 @@ var _utils = require('@pengzhanbo/utils');
|
|
|
108
35
|
var _cookies = require('cookies'); var _cookies2 = _interopRequireDefault(_cookies);
|
|
109
36
|
var _httpstatus = require('http-status'); var _httpstatus2 = _interopRequireDefault(_httpstatus);
|
|
110
37
|
var _mimetypes = require('mime-types'); var mime = _interopRequireWildcard(_mimetypes);
|
|
111
|
-
|
|
38
|
+
var _pathtoregexp = require('path-to-regexp');
|
|
112
39
|
var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
|
|
113
40
|
|
|
114
41
|
// src/core/matchingWeight.ts
|
|
@@ -238,7 +165,7 @@ function matchingWeight(rules, url, priority) {
|
|
|
238
165
|
const options = special[specialRule];
|
|
239
166
|
const { rules: lowerRules, when } = _utils.isArray.call(void 0, options) ? { rules: options, when: [] } : options;
|
|
240
167
|
if (lowerRules.includes(matched[0])) {
|
|
241
|
-
if (when.length === 0 || when.some((
|
|
168
|
+
if (when.length === 0 || when.some((path2) => _pathtoregexp.pathToRegexp.call(void 0, path2).test(url))) {
|
|
242
169
|
matched = _utils.uniq.call(void 0, [specialRule, ...matched]);
|
|
243
170
|
}
|
|
244
171
|
}
|
|
@@ -264,7 +191,7 @@ async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
|
264
191
|
const method = req.method.toUpperCase();
|
|
265
192
|
if (["GET", "DELETE", "HEAD"].includes(method))
|
|
266
193
|
return void 0;
|
|
267
|
-
const type = _optionalChain([req, 'access',
|
|
194
|
+
const type = _optionalChain([req, 'access', _ => _.headers, 'access', _2 => _2["content-type"], 'optionalAccess', _3 => _3.toLocaleLowerCase, 'call', _4 => _4()]) || "";
|
|
268
195
|
const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
|
|
269
196
|
try {
|
|
270
197
|
if (type.startsWith("application/json")) {
|
|
@@ -305,6 +232,78 @@ async function parseMultipart(req, options) {
|
|
|
305
232
|
});
|
|
306
233
|
}
|
|
307
234
|
|
|
235
|
+
// src/core/utils.ts
|
|
236
|
+
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
237
|
+
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
238
|
+
var _querystring = require('querystring');
|
|
239
|
+
var _url = require('url');
|
|
240
|
+
var _os = require('os'); var _os2 = _interopRequireDefault(_os);
|
|
241
|
+
var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug);
|
|
242
|
+
|
|
243
|
+
var _memfs = require('memfs');
|
|
244
|
+
var packageDir = getDirname(import.meta.url);
|
|
245
|
+
var vfs = _memfs.createFsFromVolume.call(void 0, new (0, _memfs.Volume)());
|
|
246
|
+
function isStream(stream) {
|
|
247
|
+
return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
|
|
248
|
+
}
|
|
249
|
+
function isReadableStream(stream) {
|
|
250
|
+
return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
|
|
251
|
+
}
|
|
252
|
+
function getDirname(importMetaUrl) {
|
|
253
|
+
return _path2.default.dirname(_url.fileURLToPath.call(void 0, importMetaUrl));
|
|
254
|
+
}
|
|
255
|
+
var debug = _debug2.default.call(void 0, "rspack:mock");
|
|
256
|
+
function lookupFile(dir, formats, options) {
|
|
257
|
+
for (const format of formats) {
|
|
258
|
+
const fullPath = _path2.default.join(dir, format);
|
|
259
|
+
if (_fs2.default.existsSync(fullPath) && _fs2.default.statSync(fullPath).isFile()) {
|
|
260
|
+
const result = _optionalChain([options, 'optionalAccess', _5 => _5.pathOnly]) ? fullPath : _fs2.default.readFileSync(fullPath, "utf-8");
|
|
261
|
+
if (!_optionalChain([options, 'optionalAccess', _6 => _6.predicate]) || options.predicate(result))
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const parentDir = _path2.default.dirname(dir);
|
|
266
|
+
if (parentDir !== dir && (!_optionalChain([options, 'optionalAccess', _7 => _7.rootDir]) || parentDir.startsWith(_optionalChain([options, 'optionalAccess', _8 => _8.rootDir])))) {
|
|
267
|
+
return lookupFile(parentDir, formats, options);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
function doesProxyContextMatchUrl(context, url, req) {
|
|
271
|
+
if (typeof context === "function") {
|
|
272
|
+
return context(url, req);
|
|
273
|
+
}
|
|
274
|
+
return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
|
|
275
|
+
}
|
|
276
|
+
function parseParams(pattern, url) {
|
|
277
|
+
const urlMatch = _pathtoregexp.match.call(void 0, pattern, { decode: decodeURIComponent })(url) || {
|
|
278
|
+
params: {}
|
|
279
|
+
};
|
|
280
|
+
return urlMatch.params || {};
|
|
281
|
+
}
|
|
282
|
+
function urlParse(input) {
|
|
283
|
+
const url = new (0, _url.URL)(input, "http://example.com");
|
|
284
|
+
const pathname = decodeURIComponent(url.pathname);
|
|
285
|
+
const query = _querystring.parse.call(void 0, url.search.replace(/^\?/, ""));
|
|
286
|
+
return { pathname, query };
|
|
287
|
+
}
|
|
288
|
+
var windowsSlashRE = /\\/g;
|
|
289
|
+
var isWindows = _os2.default.platform() === "win32";
|
|
290
|
+
function slash(p) {
|
|
291
|
+
return p.replace(windowsSlashRE, "/");
|
|
292
|
+
}
|
|
293
|
+
function normalizePath(id) {
|
|
294
|
+
return _path2.default.posix.normalize(isWindows ? slash(id) : id);
|
|
295
|
+
}
|
|
296
|
+
function waitingFor(onSuccess, maxRetry = 5) {
|
|
297
|
+
return function wait(getter, retry = 0) {
|
|
298
|
+
const value = getter();
|
|
299
|
+
if (value) {
|
|
300
|
+
onSuccess(value);
|
|
301
|
+
} else if (retry < maxRetry) {
|
|
302
|
+
setTimeout(() => wait(getter, retry + 1), 100);
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
308
307
|
// src/core/validator.ts
|
|
309
308
|
|
|
310
309
|
function validate(request, validator) {
|
|
@@ -601,52 +600,6 @@ function requestLog(request, filepath) {
|
|
|
601
600
|
return `${ms} ${pathname}${qs}${ps}${bs}${file}`;
|
|
602
601
|
}
|
|
603
602
|
|
|
604
|
-
// src/core/mockMiddleware.ts
|
|
605
|
-
function createMockMiddleware(compiler, options) {
|
|
606
|
-
function mockMiddleware(middlewares, reload) {
|
|
607
|
-
middlewares.unshift(baseMiddleware(compiler, options));
|
|
608
|
-
const corsMiddleware = createCorsMiddleware(compiler, options);
|
|
609
|
-
if (corsMiddleware) {
|
|
610
|
-
middlewares.unshift(corsMiddleware);
|
|
611
|
-
}
|
|
612
|
-
if (options.reload) {
|
|
613
|
-
compiler.on("update", () => _optionalChain([reload, 'optionalCall', _9 => _9()]));
|
|
614
|
-
}
|
|
615
|
-
return middlewares;
|
|
616
|
-
}
|
|
617
|
-
return mockMiddleware;
|
|
618
|
-
}
|
|
619
|
-
function createCorsMiddleware(compiler, options) {
|
|
620
|
-
let corsOptions = {};
|
|
621
|
-
const enabled = options.cors !== false;
|
|
622
|
-
if (enabled) {
|
|
623
|
-
corsOptions = {
|
|
624
|
-
...corsOptions,
|
|
625
|
-
...typeof options.cors === "boolean" ? {} : options.cors
|
|
626
|
-
};
|
|
627
|
-
}
|
|
628
|
-
const proxies = options.proxies;
|
|
629
|
-
return !enabled ? void 0 : function(req, res, next) {
|
|
630
|
-
const { pathname } = urlParse(req.url);
|
|
631
|
-
if (!pathname || proxies.length === 0 || !proxies.some(
|
|
632
|
-
(context) => doesProxyContextMatchUrl(context, req.url, req)
|
|
633
|
-
)) {
|
|
634
|
-
return next();
|
|
635
|
-
}
|
|
636
|
-
const mockData = compiler.mockData;
|
|
637
|
-
const mockUrl = Object.keys(mockData).find(
|
|
638
|
-
(key) => _pathtoregexp.pathToRegexp.call(void 0, key).test(pathname)
|
|
639
|
-
);
|
|
640
|
-
if (!mockUrl)
|
|
641
|
-
return next();
|
|
642
|
-
_cors2.default.call(void 0, corsOptions)(req, res, next);
|
|
643
|
-
};
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
// src/core/resolvePluginOptions.ts
|
|
647
|
-
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
|
|
648
|
-
|
|
649
|
-
|
|
650
603
|
// src/core/logger.ts
|
|
651
604
|
|
|
652
605
|
|
|
@@ -688,96 +641,6 @@ function createLogger(prefix, defaultLevel = "info") {
|
|
|
688
641
|
return logger;
|
|
689
642
|
}
|
|
690
643
|
|
|
691
|
-
// src/core/resolvePluginOptions.ts
|
|
692
|
-
function resolvePluginOptions({
|
|
693
|
-
prefix = [],
|
|
694
|
-
wsPrefix = [],
|
|
695
|
-
cwd,
|
|
696
|
-
include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
|
|
697
|
-
exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
|
|
698
|
-
reload = false,
|
|
699
|
-
log = "info",
|
|
700
|
-
cors: cors2 = true,
|
|
701
|
-
formidableOptions = {},
|
|
702
|
-
build = false,
|
|
703
|
-
cookiesOptions = {},
|
|
704
|
-
bodyParserOptions = {},
|
|
705
|
-
priority = {}
|
|
706
|
-
} = {}, { alias, context, plugins, proxies }) {
|
|
707
|
-
const logger = createLogger(
|
|
708
|
-
"rspack:mock",
|
|
709
|
-
_utils.isBoolean.call(void 0, log) ? log ? "info" : "error" : log
|
|
710
|
-
);
|
|
711
|
-
return {
|
|
712
|
-
prefix,
|
|
713
|
-
wsPrefix,
|
|
714
|
-
cwd: cwd || context || _process2.default.cwd(),
|
|
715
|
-
include,
|
|
716
|
-
exclude,
|
|
717
|
-
reload,
|
|
718
|
-
cors: cors2,
|
|
719
|
-
cookiesOptions,
|
|
720
|
-
log,
|
|
721
|
-
formidableOptions: {
|
|
722
|
-
multiples: true,
|
|
723
|
-
...formidableOptions
|
|
724
|
-
},
|
|
725
|
-
bodyParserOptions,
|
|
726
|
-
priority,
|
|
727
|
-
build: build ? Object.assign(
|
|
728
|
-
{
|
|
729
|
-
serverPort: 8080,
|
|
730
|
-
dist: "mockServer",
|
|
731
|
-
log: "error"
|
|
732
|
-
},
|
|
733
|
-
typeof build === "object" ? build : {}
|
|
734
|
-
) : false,
|
|
735
|
-
alias,
|
|
736
|
-
plugins,
|
|
737
|
-
proxies,
|
|
738
|
-
wsProxies: _utils.toArray.call(void 0, wsPrefix),
|
|
739
|
-
logger
|
|
740
|
-
};
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
// src/core/mockCompiler.ts
|
|
744
|
-
var _events = require('events'); var _events2 = _interopRequireDefault(_events);
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
|
|
749
|
-
var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);
|
|
750
|
-
var _pluginutils = require('@rollup/pluginutils');
|
|
751
|
-
var _core = require('@rspack/core'); var rspackCore = _interopRequireWildcard(_core);
|
|
752
|
-
var _memfs = require('memfs');
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
// src/core/loadFromCode.ts
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
async function loadFromCode({
|
|
760
|
-
filepath,
|
|
761
|
-
code,
|
|
762
|
-
isESM,
|
|
763
|
-
cwd
|
|
764
|
-
}) {
|
|
765
|
-
filepath = _path2.default.resolve(cwd, filepath);
|
|
766
|
-
const fileBase = `${filepath}.timestamp-${Date.now()}`;
|
|
767
|
-
const ext = isESM ? ".mjs" : ".cjs";
|
|
768
|
-
const fileNameTmp = `${fileBase}${ext}`;
|
|
769
|
-
await _fs.promises.writeFile(fileNameTmp, code, "utf8");
|
|
770
|
-
try {
|
|
771
|
-
const result = await Promise.resolve().then(() => _interopRequireWildcard(require(fileNameTmp)));
|
|
772
|
-
return result.default || result;
|
|
773
|
-
} finally {
|
|
774
|
-
try {
|
|
775
|
-
_fs2.default.unlinkSync(fileNameTmp);
|
|
776
|
-
} catch (e2) {
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
|
|
781
644
|
// src/core/transform.ts
|
|
782
645
|
|
|
783
646
|
|
|
@@ -865,221 +728,6 @@ function keysCount(obj) {
|
|
|
865
728
|
return Object.keys(obj).length;
|
|
866
729
|
}
|
|
867
730
|
|
|
868
|
-
// src/core/resolveRspackOptions.ts
|
|
869
|
-
|
|
870
|
-
var _dirname = getDirname(import.meta.url);
|
|
871
|
-
function resolveRspackOptions({
|
|
872
|
-
cwd,
|
|
873
|
-
isEsm,
|
|
874
|
-
entryFile,
|
|
875
|
-
outputFile,
|
|
876
|
-
plugins,
|
|
877
|
-
alias,
|
|
878
|
-
watch = false
|
|
879
|
-
}) {
|
|
880
|
-
const targets = ["node >= 18.0.0"];
|
|
881
|
-
return {
|
|
882
|
-
mode: "production",
|
|
883
|
-
context: cwd,
|
|
884
|
-
entry: entryFile,
|
|
885
|
-
watch,
|
|
886
|
-
target: "node18.0",
|
|
887
|
-
externalsType: isEsm ? "module" : "commonjs2",
|
|
888
|
-
externals: /^[^./].*/,
|
|
889
|
-
resolve: {
|
|
890
|
-
alias,
|
|
891
|
-
extensions: [".js", ".ts", ".cjs", ".mjs", ".json5", ".json"]
|
|
892
|
-
},
|
|
893
|
-
plugins,
|
|
894
|
-
output: {
|
|
895
|
-
library: { type: !isEsm ? "commonjs2" : "module" },
|
|
896
|
-
filename: outputFile,
|
|
897
|
-
path: "/"
|
|
898
|
-
},
|
|
899
|
-
experiments: { outputModule: isEsm },
|
|
900
|
-
module: {
|
|
901
|
-
rules: [
|
|
902
|
-
{
|
|
903
|
-
test: /\.json5?$/,
|
|
904
|
-
loader: _path2.default.join(_dirname, "json5-loader.cjs"),
|
|
905
|
-
type: "javascript/auto"
|
|
906
|
-
},
|
|
907
|
-
{
|
|
908
|
-
test: /\.[cm]?js$/,
|
|
909
|
-
use: [
|
|
910
|
-
{
|
|
911
|
-
loader: "builtin:swc-loader",
|
|
912
|
-
options: {
|
|
913
|
-
jsc: { parser: { syntax: "ecmascript" } },
|
|
914
|
-
env: { targets }
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
]
|
|
918
|
-
},
|
|
919
|
-
{
|
|
920
|
-
test: /\.[cm]?ts$/,
|
|
921
|
-
use: [
|
|
922
|
-
{
|
|
923
|
-
loader: "builtin:swc-loader",
|
|
924
|
-
options: {
|
|
925
|
-
jsc: { parser: { syntax: "typescript" } },
|
|
926
|
-
env: { targets }
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
]
|
|
930
|
-
}
|
|
931
|
-
]
|
|
932
|
-
}
|
|
933
|
-
};
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
// src/core/mockCompiler.ts
|
|
937
|
-
var vfs = _memfs.createFsFromVolume.call(void 0, new (0, _memfs.Volume)());
|
|
938
|
-
function createMockCompiler(options) {
|
|
939
|
-
return new MockCompiler(options);
|
|
940
|
-
}
|
|
941
|
-
var MockCompiler = (_class = class extends _events2.default {
|
|
942
|
-
constructor(options) {
|
|
943
|
-
super();_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;
|
|
944
|
-
this.options = options;
|
|
945
|
-
this.cwd = options.cwd || _process2.default.cwd();
|
|
946
|
-
const { include, exclude } = this.options;
|
|
947
|
-
this.fileFilter = _pluginutils.createFilter.call(void 0, include, exclude, { resolve: false });
|
|
948
|
-
try {
|
|
949
|
-
const pkg = lookupFile(this.cwd, ["package.json"]);
|
|
950
|
-
this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
|
|
951
|
-
} catch (e3) {
|
|
952
|
-
}
|
|
953
|
-
this.entryFile = _path2.default.resolve(_process2.default.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
954
|
-
this.outputFile = "mock.bundle.js";
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
__init() {this.moduleType = "cjs"}
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
__init2() {this._mockData = {}}
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
get mockData() {
|
|
966
|
-
return this._mockData;
|
|
967
|
-
}
|
|
968
|
-
async run() {
|
|
969
|
-
await this.updateMockEntry();
|
|
970
|
-
this.watchMockFiles();
|
|
971
|
-
this.createCompiler(async (err, stats) => {
|
|
972
|
-
const name = "[rspack:mock]";
|
|
973
|
-
const logError = _optionalChain([stats, 'optionalAccess', _10 => _10.compilation, 'access', _11 => _11.getLogger, 'call', _12 => _12(name), 'access', _13 => _13.error]) || ((...args) => console.error(_picocolors2.default.red(name), ...args));
|
|
974
|
-
if (err) {
|
|
975
|
-
logError(err.stack || err);
|
|
976
|
-
if ("details" in err) {
|
|
977
|
-
logError(err.details);
|
|
978
|
-
}
|
|
979
|
-
return;
|
|
980
|
-
}
|
|
981
|
-
if (_optionalChain([stats, 'optionalAccess', _14 => _14.hasErrors, 'call', _15 => _15()])) {
|
|
982
|
-
const info = stats.toJson();
|
|
983
|
-
logError(info.errors);
|
|
984
|
-
return;
|
|
985
|
-
}
|
|
986
|
-
const content = vfs.readFileSync(`/${this.outputFile}`, "utf-8");
|
|
987
|
-
try {
|
|
988
|
-
const result = await loadFromCode({
|
|
989
|
-
filepath: this.outputFile,
|
|
990
|
-
code: content,
|
|
991
|
-
isESM: this.moduleType === "esm",
|
|
992
|
-
cwd: this.cwd
|
|
993
|
-
});
|
|
994
|
-
this._mockData = transformMockData(transformRawData(result));
|
|
995
|
-
this.emit("update", this.watchInfo || {});
|
|
996
|
-
} catch (e) {
|
|
997
|
-
logError(e);
|
|
998
|
-
}
|
|
999
|
-
});
|
|
1000
|
-
}
|
|
1001
|
-
close() {
|
|
1002
|
-
this.mockWatcher.close();
|
|
1003
|
-
_optionalChain([this, 'access', _16 => _16.compiler, 'optionalAccess', _17 => _17.close, 'call', _18 => _18(() => {
|
|
1004
|
-
})]);
|
|
1005
|
-
this.emit("close");
|
|
1006
|
-
}
|
|
1007
|
-
updateAlias(alias) {
|
|
1008
|
-
this.options.alias = {
|
|
1009
|
-
...this.options.alias,
|
|
1010
|
-
...alias
|
|
1011
|
-
};
|
|
1012
|
-
}
|
|
1013
|
-
async updateMockEntry() {
|
|
1014
|
-
const files = await this.getMockFiles();
|
|
1015
|
-
await this.resolveEntryFile(files);
|
|
1016
|
-
}
|
|
1017
|
-
async getMockFiles() {
|
|
1018
|
-
const { include } = this.options;
|
|
1019
|
-
const files = await _fastglob2.default.call(void 0, include, { cwd: this.cwd });
|
|
1020
|
-
return files.filter(this.fileFilter);
|
|
1021
|
-
}
|
|
1022
|
-
watchMockFiles() {
|
|
1023
|
-
const { include } = this.options;
|
|
1024
|
-
const [firstGlob, ...otherGlob] = _utils.toArray.call(void 0, include);
|
|
1025
|
-
const watcher = this.mockWatcher = _chokidar2.default.watch(firstGlob, {
|
|
1026
|
-
ignoreInitial: true,
|
|
1027
|
-
cwd: this.cwd
|
|
1028
|
-
});
|
|
1029
|
-
if (otherGlob.length > 0)
|
|
1030
|
-
otherGlob.forEach((glob) => watcher.add(glob));
|
|
1031
|
-
watcher.on("add", (filepath) => {
|
|
1032
|
-
if (this.fileFilter(filepath)) {
|
|
1033
|
-
this.watchInfo = { filepath, type: "add" };
|
|
1034
|
-
this.updateMockEntry();
|
|
1035
|
-
}
|
|
1036
|
-
});
|
|
1037
|
-
watcher.on("change", (filepath) => {
|
|
1038
|
-
if (this.fileFilter(filepath)) {
|
|
1039
|
-
this.watchInfo = { filepath, type: "change" };
|
|
1040
|
-
}
|
|
1041
|
-
});
|
|
1042
|
-
watcher.on("unlink", async (filepath) => {
|
|
1043
|
-
this.watchInfo = { filepath, type: "unlink" };
|
|
1044
|
-
this.updateMockEntry();
|
|
1045
|
-
});
|
|
1046
|
-
}
|
|
1047
|
-
async resolveEntryFile(fileList) {
|
|
1048
|
-
const importers = [];
|
|
1049
|
-
const exporters = [];
|
|
1050
|
-
for (const [index, filepath] of fileList.entries()) {
|
|
1051
|
-
const file = normalizePath(_path2.default.join(this.cwd, filepath));
|
|
1052
|
-
importers.push(`import * as m${index} from '${file}'`);
|
|
1053
|
-
exporters.push(`[m${index}, '${filepath}']`);
|
|
1054
|
-
}
|
|
1055
|
-
const code = `${importers.join("\n")}
|
|
1056
|
-
|
|
1057
|
-
export default [
|
|
1058
|
-
${exporters.join(",\n ")}
|
|
1059
|
-
]`;
|
|
1060
|
-
const dirname = _path2.default.dirname(this.entryFile);
|
|
1061
|
-
if (!_fs2.default.existsSync(dirname)) {
|
|
1062
|
-
await _fs.promises.mkdir(dirname, { recursive: true });
|
|
1063
|
-
}
|
|
1064
|
-
await _fs.promises.writeFile(this.entryFile, code, "utf8");
|
|
1065
|
-
}
|
|
1066
|
-
createCompiler(callback) {
|
|
1067
|
-
const { plugins, alias } = this.options;
|
|
1068
|
-
const options = resolveRspackOptions({
|
|
1069
|
-
isEsm: this.moduleType === "esm",
|
|
1070
|
-
cwd: this.cwd,
|
|
1071
|
-
plugins,
|
|
1072
|
-
entryFile: this.entryFile,
|
|
1073
|
-
outputFile: this.outputFile,
|
|
1074
|
-
alias,
|
|
1075
|
-
watch: true
|
|
1076
|
-
});
|
|
1077
|
-
this.compiler = rspackCore.rspack(options, callback);
|
|
1078
|
-
if (this.compiler)
|
|
1079
|
-
this.compiler.outputFileSystem = vfs;
|
|
1080
|
-
}
|
|
1081
|
-
}, _class);
|
|
1082
|
-
|
|
1083
731
|
// src/core/mockWebsocket.ts
|
|
1084
732
|
|
|
1085
733
|
|
|
@@ -1113,7 +761,7 @@ function mockWebSocket(compiler, httpServer, {
|
|
|
1113
761
|
};
|
|
1114
762
|
const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
|
|
1115
763
|
try {
|
|
1116
|
-
_optionalChain([mock, 'access',
|
|
764
|
+
_optionalChain([mock, 'access', _9 => _9.setup, 'optionalCall', _10 => _10(wss, context)]);
|
|
1117
765
|
wss.on("close", () => wssMap.delete(pathname));
|
|
1118
766
|
wss.on("error", (e) => {
|
|
1119
767
|
logger.error(
|
|
@@ -1170,7 +818,7 @@ ${e}
|
|
|
1170
818
|
}
|
|
1171
819
|
}
|
|
1172
820
|
});
|
|
1173
|
-
_optionalChain([httpServer, 'optionalAccess',
|
|
821
|
+
_optionalChain([httpServer, 'optionalAccess', _11 => _11.on, 'call', _12 => _12("upgrade", (req, socket, head) => {
|
|
1174
822
|
const { pathname, query } = urlParse(req.url);
|
|
1175
823
|
if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url, req))) {
|
|
1176
824
|
return;
|
|
@@ -1218,7 +866,7 @@ ${e}
|
|
|
1218
866
|
emitConnection(wss, ws, request, wssContext.connectionList);
|
|
1219
867
|
});
|
|
1220
868
|
})]);
|
|
1221
|
-
_optionalChain([httpServer, 'optionalAccess',
|
|
869
|
+
_optionalChain([httpServer, 'optionalAccess', _13 => _13.on, 'call', _14 => _14("close", () => {
|
|
1222
870
|
for (const wssMap of poolMap.values()) {
|
|
1223
871
|
for (const wss of wssMap.values()) {
|
|
1224
872
|
const wssContext = wssContextMap.get(wss);
|
|
@@ -1234,7 +882,7 @@ ${e}
|
|
|
1234
882
|
function cleanupRunner(cleanupList) {
|
|
1235
883
|
let cleanup;
|
|
1236
884
|
while (cleanup = cleanupList.shift())
|
|
1237
|
-
_optionalChain([cleanup, 'optionalCall',
|
|
885
|
+
_optionalChain([cleanup, 'optionalCall', _15 => _15()]);
|
|
1238
886
|
}
|
|
1239
887
|
|
|
1240
888
|
|
|
@@ -1244,4 +892,13 @@ function cleanupRunner(cleanupList) {
|
|
|
1244
892
|
|
|
1245
893
|
|
|
1246
894
|
|
|
1247
|
-
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
exports.packageDir = packageDir; exports.vfs = vfs; exports.lookupFile = lookupFile; exports.doesProxyContextMatchUrl = doesProxyContextMatchUrl; exports.urlParse = urlParse; exports.normalizePath = normalizePath; exports.waitingFor = waitingFor; exports.rewriteRequest = rewriteRequest; exports.baseMiddleware = baseMiddleware; exports.logLevels = logLevels; exports.createLogger = createLogger; exports.transformRawData = transformRawData; exports.transformMockData = transformMockData; exports.sortByValidator = sortByValidator; exports.mockWebSocket = mockWebSocket;
|
package/dist/helper.cjs
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true})
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/core/defineMock.ts
|
|
2
|
+
var _utils = require('@pengzhanbo/utils');
|
|
3
|
+
function defineMock(config) {
|
|
4
|
+
return config;
|
|
5
|
+
}
|
|
6
|
+
function createDefineMock(transformer) {
|
|
7
|
+
const define = (config) => {
|
|
8
|
+
if (_utils.isArray.call(void 0, config))
|
|
9
|
+
config = config.map((item) => transformer(item) || item);
|
|
10
|
+
else
|
|
11
|
+
config = transformer(config) || config;
|
|
12
|
+
return config;
|
|
13
|
+
};
|
|
14
|
+
return define;
|
|
15
|
+
}
|
|
2
16
|
|
|
3
17
|
|
|
4
|
-
var _chunkKE2LVHUPcjs = require('./chunk-KE2LVHUP.cjs');
|
|
5
18
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
exports.createDefineMock = _chunkKE2LVHUPcjs.createDefineMock; exports.defineMock = _chunkKE2LVHUPcjs.defineMock;
|
|
19
|
+
exports.createDefineMock = createDefineMock; exports.defineMock = defineMock;
|
package/dist/helper.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile,
|
|
1
|
+
import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-BgpcN3jm.cjs';
|
|
2
|
+
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-BgpcN3jm.cjs';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
5
|
import 'node:stream';
|
package/dist/helper.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile,
|
|
1
|
+
import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-BgpcN3jm.js';
|
|
2
|
+
export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-BgpcN3jm.js';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
5
|
import 'node:stream';
|
package/dist/helper.js
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
// src/core/defineMock.ts
|
|
2
|
+
import { isArray } from "@pengzhanbo/utils";
|
|
3
|
+
function defineMock(config) {
|
|
4
|
+
return config;
|
|
5
|
+
}
|
|
6
|
+
function createDefineMock(transformer) {
|
|
7
|
+
const define = (config) => {
|
|
8
|
+
if (isArray(config))
|
|
9
|
+
config = config.map((item) => transformer(item) || item);
|
|
10
|
+
else
|
|
11
|
+
config = transformer(config) || config;
|
|
12
|
+
return config;
|
|
13
|
+
};
|
|
14
|
+
return define;
|
|
15
|
+
}
|
|
5
16
|
export {
|
|
6
17
|
createDefineMock,
|
|
7
18
|
defineMock
|