@modern-js/server 2.4.1-beta.0 → 2.5.1-alpha.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +23 -4
  2. package/dist/cjs/constants.js +42 -0
  3. package/dist/cjs/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +65 -0
  4. package/dist/cjs/dev-tools/dev-middleware/hmr-client/index.js +155 -0
  5. package/dist/cjs/dev-tools/dev-middleware/index.js +86 -0
  6. package/dist/cjs/dev-tools/dev-middleware/socket-server.js +159 -0
  7. package/dist/cjs/dev-tools/https/index.js +52 -0
  8. package/dist/cjs/dev-tools/mock/getMockData.js +91 -0
  9. package/dist/cjs/dev-tools/mock/index.js +79 -0
  10. package/dist/cjs/dev-tools/register/index.js +125 -0
  11. package/dist/cjs/dev-tools/watcher/dependency-tree.js +89 -0
  12. package/dist/cjs/dev-tools/watcher/index.js +126 -0
  13. package/dist/cjs/dev-tools/watcher/stats-cache.js +87 -0
  14. package/dist/cjs/index.js +35 -0
  15. package/dist/cjs/server/dev-server.js +267 -0
  16. package/dist/cjs/server/index.js +39 -0
  17. package/dist/cjs/types.js +15 -0
  18. package/dist/esm/constants.js +21 -0
  19. package/dist/esm/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +51 -0
  20. package/dist/esm/dev-tools/dev-middleware/hmr-client/index.js +162 -0
  21. package/dist/esm/dev-tools/dev-middleware/index.js +322 -0
  22. package/dist/esm/dev-tools/dev-middleware/socket-server.js +209 -0
  23. package/dist/esm/dev-tools/https/index.js +193 -0
  24. package/dist/esm/dev-tools/mock/getMockData.js +318 -0
  25. package/dist/esm/dev-tools/mock/index.js +207 -0
  26. package/dist/esm/dev-tools/register/index.js +154 -0
  27. package/dist/esm/dev-tools/watcher/dependency-tree.js +150 -0
  28. package/dist/esm/dev-tools/watcher/index.js +200 -0
  29. package/dist/esm/dev-tools/watcher/stats-cache.js +128 -0
  30. package/dist/esm/index.js +9 -0
  31. package/dist/esm/server/dev-server.js +800 -0
  32. package/dist/esm/server/index.js +92 -0
  33. package/dist/esm/types.js +1 -0
  34. package/dist/esm-node/constants.js +19 -0
  35. package/dist/esm-node/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +41 -0
  36. package/dist/esm-node/dev-tools/dev-middleware/hmr-client/index.js +146 -0
  37. package/dist/esm-node/dev-tools/dev-middleware/index.js +59 -0
  38. package/dist/esm-node/dev-tools/dev-middleware/socket-server.js +132 -0
  39. package/dist/esm-node/dev-tools/https/index.js +29 -0
  40. package/dist/esm-node/dev-tools/mock/getMockData.js +68 -0
  41. package/dist/esm-node/dev-tools/mock/index.js +50 -0
  42. package/dist/esm-node/dev-tools/register/index.js +96 -0
  43. package/dist/esm-node/dev-tools/watcher/dependency-tree.js +59 -0
  44. package/dist/esm-node/dev-tools/watcher/index.js +95 -0
  45. package/dist/esm-node/dev-tools/watcher/stats-cache.js +58 -0
  46. package/dist/esm-node/index.js +12 -0
  47. package/dist/esm-node/server/dev-server.js +247 -0
  48. package/dist/esm-node/server/index.js +16 -0
  49. package/dist/esm-node/types.js +0 -0
  50. package/dist/js/modern/dev-tools/dev-middleware/hmr-client/index.js +3 -6
  51. package/dist/js/node/dev-tools/dev-middleware/hmr-client/index.js +3 -6
  52. package/dist/js/treeshaking/dev-tools/dev-middleware/hmr-client/index.js +1 -6
  53. package/dist/js/treeshaking/dev-tools/dev-middleware/index.js +2 -2
  54. package/dist/js/treeshaking/dev-tools/dev-middleware/socket-server.js +2 -2
  55. package/dist/js/treeshaking/dev-tools/register/index.js +6 -6
  56. package/dist/js/treeshaking/dev-tools/watcher/index.js +4 -4
  57. package/dist/js/treeshaking/dev-tools/watcher/stats-cache.js +3 -3
  58. package/dist/js/treeshaking/server/dev-server.js +10 -10
  59. package/dist/types/dev-tools/mock/getMockData.d.ts +1 -1
  60. package/package.json +15 -16
@@ -0,0 +1,92 @@
1
+ function _assertThisInitialized(self) {
2
+ if (self === void 0) {
3
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
4
+ }
5
+ return self;
6
+ }
7
+ function _classCallCheck(instance, Constructor) {
8
+ if (!(instance instanceof Constructor)) {
9
+ throw new TypeError("Cannot call a class as a function");
10
+ }
11
+ }
12
+ function _getPrototypeOf(o) {
13
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
14
+ return o.__proto__ || Object.getPrototypeOf(o);
15
+ };
16
+ return _getPrototypeOf(o);
17
+ }
18
+ function _inherits(subClass, superClass) {
19
+ if (typeof superClass !== "function" && superClass !== null) {
20
+ throw new TypeError("Super expression must either be null or a function");
21
+ }
22
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
23
+ constructor: {
24
+ value: subClass,
25
+ writable: true,
26
+ configurable: true
27
+ }
28
+ });
29
+ if (superClass) _setPrototypeOf(subClass, superClass);
30
+ }
31
+ function _possibleConstructorReturn(self, call) {
32
+ if (call && (_typeof(call) === "object" || typeof call === "function")) {
33
+ return call;
34
+ }
35
+ return _assertThisInitialized(self);
36
+ }
37
+ function _setPrototypeOf(o, p) {
38
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
39
+ o.__proto__ = p;
40
+ return o;
41
+ };
42
+ return _setPrototypeOf(o, p);
43
+ }
44
+ var _typeof = function(obj) {
45
+ "@swc/helpers - typeof";
46
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
47
+ };
48
+ function _isNativeReflectConstruct() {
49
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
50
+ if (Reflect.construct.sham) return false;
51
+ if (typeof Proxy === "function") return true;
52
+ try {
53
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
54
+ return true;
55
+ } catch (e) {
56
+ return false;
57
+ }
58
+ }
59
+ function _createSuper(Derived) {
60
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
61
+ return function _createSuperInternal() {
62
+ var Super = _getPrototypeOf(Derived), result;
63
+ if (hasNativeReflectConstruct) {
64
+ var NewTarget = _getPrototypeOf(this).constructor;
65
+ result = Reflect.construct(Super, arguments, NewTarget);
66
+ } else {
67
+ result = Super.apply(this, arguments);
68
+ }
69
+ return _possibleConstructorReturn(this, result);
70
+ };
71
+ }
72
+ import { Server } from "@modern-js/prod-server";
73
+ import { ModernDevServer } from "./dev-server";
74
+ var createDevServer = function(options) {
75
+ return new ModernDevServer(options);
76
+ };
77
+ var DevServer = /*#__PURE__*/ function(Server) {
78
+ "use strict";
79
+ _inherits(DevServer, Server);
80
+ var _super = _createSuper(DevServer);
81
+ function DevServer(options) {
82
+ _classCallCheck(this, DevServer);
83
+ var _this;
84
+ _this = _super.call(this, options);
85
+ if (options.dev) {
86
+ _this.serverImpl = createDevServer;
87
+ }
88
+ return _this;
89
+ }
90
+ return DevServer;
91
+ }(Server);
92
+ export { DevServer };
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,19 @@
1
+ import { getIpv4Interfaces, HMR_SOCK_PATH } from "@modern-js/utils";
2
+ const getDefaultDevOptions = () => {
3
+ const network = getIpv4Interfaces().find((item) => !item.internal);
4
+ return {
5
+ client: {
6
+ port: "8080",
7
+ path: HMR_SOCK_PATH,
8
+ host: (network == null ? void 0 : network.address) || "localhost"
9
+ },
10
+ https: false,
11
+ devMiddleware: { writeToDisk: true },
12
+ watch: true,
13
+ hot: true,
14
+ liveReload: true
15
+ };
16
+ };
17
+ export {
18
+ getDefaultDevOptions
19
+ };
@@ -0,0 +1,41 @@
1
+ import { HMR_SOCK_PATH } from "@modern-js/utils/constants";
2
+ function createSocketUrl(resourceQuery) {
3
+ const searchParams = resourceQuery.substr(1).split("&");
4
+ const options = {};
5
+ for (const pair of searchParams) {
6
+ const ary = pair.split("=");
7
+ options[ary[0]] = decodeURIComponent(ary[1]);
8
+ }
9
+ const currentLocation = self.location;
10
+ return getSocketUrl(options, currentLocation);
11
+ }
12
+ function formatURL({
13
+ port,
14
+ protocol,
15
+ hostname,
16
+ pathname
17
+ }) {
18
+ if (window.URL) {
19
+ const url = new URL("http://localhost");
20
+ url.port = port;
21
+ url.hostname = hostname;
22
+ url.protocol = protocol;
23
+ url.pathname = pathname;
24
+ return url.toString();
25
+ }
26
+ const colon = protocol.indexOf(":") === -1 ? ":" : "";
27
+ return `${protocol}${colon}//${hostname}:${port}${pathname}`;
28
+ }
29
+ function getSocketUrl(urlParts, location) {
30
+ const { host, port, path, protocol } = urlParts;
31
+ return formatURL({
32
+ protocol: protocol || (location.protocol === "https:" ? "wss" : "ws"),
33
+ hostname: host || location.hostname,
34
+ port: port || location.port,
35
+ pathname: path || HMR_SOCK_PATH
36
+ });
37
+ }
38
+ export {
39
+ createSocketUrl,
40
+ formatURL
41
+ };
@@ -0,0 +1,146 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __commonJS = (cb, mod) => function __require() {
3
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4
+ };
5
+ import stripAnsi from "@modern-js/utils/strip-ansi";
6
+ import { formatWebpackMessages } from "@modern-js/utils/format";
7
+ import { createSocketUrl } from "./createSocketUrl";
8
+ var require_hmr_client = __commonJS({
9
+ "src/dev-tools/dev-middleware/hmr-client/index.ts"(exports, module) {
10
+ const hadRuntimeError = false;
11
+ const socketUrl = createSocketUrl(__resourceQuery);
12
+ const connection = new WebSocket(socketUrl);
13
+ connection.onopen = function() {
14
+ if (typeof console !== "undefined" && typeof console.debug === "function") {
15
+ console.debug("[HMR] connected.");
16
+ }
17
+ };
18
+ connection.onclose = function() {
19
+ if (typeof console !== "undefined" && typeof console.info === "function") {
20
+ console.debug("[HMR] disconnected. Refresh the page if necessary.");
21
+ }
22
+ };
23
+ let isFirstCompilation = true;
24
+ let mostRecentCompilationHash = null;
25
+ let hasCompileErrors = false;
26
+ function clearOutdatedErrors() {
27
+ if (typeof console !== "undefined" && typeof console.clear === "function") {
28
+ if (hasCompileErrors) {
29
+ console.clear();
30
+ }
31
+ }
32
+ }
33
+ function handleSuccess() {
34
+ clearOutdatedErrors();
35
+ const isHotUpdate = !isFirstCompilation;
36
+ isFirstCompilation = false;
37
+ hasCompileErrors = false;
38
+ if (isHotUpdate) {
39
+ tryApplyUpdates();
40
+ }
41
+ }
42
+ function handleWarnings(warnings) {
43
+ clearOutdatedErrors();
44
+ const isHotUpdate = !isFirstCompilation;
45
+ isFirstCompilation = false;
46
+ hasCompileErrors = false;
47
+ function printWarnings() {
48
+ const formatted = formatWebpackMessages({
49
+ warnings,
50
+ errors: []
51
+ });
52
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
53
+ for (let i = 0; i < formatted.warnings.length; i++) {
54
+ if (i === 5) {
55
+ console.warn(
56
+ "There were more warnings in other files.\nYou can find a complete log in the terminal."
57
+ );
58
+ break;
59
+ }
60
+ console.warn(stripAnsi(formatted.warnings[i]));
61
+ }
62
+ }
63
+ }
64
+ printWarnings();
65
+ if (isHotUpdate) {
66
+ tryApplyUpdates();
67
+ }
68
+ }
69
+ function handleErrors(errors) {
70
+ clearOutdatedErrors();
71
+ isFirstCompilation = false;
72
+ hasCompileErrors = true;
73
+ const formatted = formatWebpackMessages({
74
+ errors,
75
+ warnings: []
76
+ });
77
+ if (typeof console !== "undefined" && typeof console.error === "function") {
78
+ for (const error of formatted.errors) {
79
+ console.error(stripAnsi(error));
80
+ }
81
+ }
82
+ }
83
+ function handleAvailableHash(hash) {
84
+ mostRecentCompilationHash = hash;
85
+ }
86
+ connection.onmessage = function(e) {
87
+ const message = JSON.parse(e.data);
88
+ switch (message.type) {
89
+ case "hash":
90
+ handleAvailableHash(message.data);
91
+ break;
92
+ case "still-ok":
93
+ case "ok":
94
+ handleSuccess();
95
+ break;
96
+ case "content-changed":
97
+ window.location.reload();
98
+ break;
99
+ case "warnings":
100
+ handleWarnings(message.data);
101
+ break;
102
+ case "errors":
103
+ handleErrors(message.data);
104
+ break;
105
+ default:
106
+ }
107
+ };
108
+ function isUpdateAvailable() {
109
+ return mostRecentCompilationHash !== __webpack_hash__;
110
+ }
111
+ function canApplyUpdates() {
112
+ return module.hot.status() === "idle";
113
+ }
114
+ function tryApplyUpdates() {
115
+ if (!module.hot) {
116
+ window.location.reload();
117
+ return;
118
+ }
119
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
120
+ return;
121
+ }
122
+ function handleApplyUpdates(err, updatedModules) {
123
+ const wantsForcedReload = err || !updatedModules || hadRuntimeError;
124
+ if (wantsForcedReload) {
125
+ window.location.reload();
126
+ return;
127
+ }
128
+ if (isUpdateAvailable()) {
129
+ tryApplyUpdates();
130
+ }
131
+ }
132
+ const result = module.hot.check(true, handleApplyUpdates);
133
+ if (result == null ? void 0 : result.then) {
134
+ result.then(
135
+ (updatedModules) => {
136
+ handleApplyUpdates(null, updatedModules);
137
+ },
138
+ (err) => {
139
+ handleApplyUpdates(err, null);
140
+ }
141
+ );
142
+ }
143
+ }
144
+ }
145
+ });
146
+ export default require_hmr_client();
@@ -0,0 +1,59 @@
1
+ import { EventEmitter } from "events";
2
+ import SocketServer from "./socket-server";
3
+ const noop = () => {
4
+ };
5
+ function getHMRClientPath(client) {
6
+ const protocol = (client == null ? void 0 : client.protocol) ? `&protocol=${client.protocol}` : "";
7
+ const host = (client == null ? void 0 : client.host) ? `&host=${client.host}` : "";
8
+ const path = (client == null ? void 0 : client.path) ? `&path=${client.path}` : "";
9
+ const port = (client == null ? void 0 : client.port) ? `&port=${client.port}` : "";
10
+ const clientEntry = `${require.resolve("./hmr-client")}?${host}${path}${port}${protocol}`;
11
+ return clientEntry;
12
+ }
13
+ class DevMiddleware extends EventEmitter {
14
+ constructor({ dev, devMiddleware }) {
15
+ super();
16
+ this.devOptions = dev;
17
+ this.socketServer = new SocketServer(dev);
18
+ if (devMiddleware) {
19
+ this.middleware = this.setupDevMiddleware(devMiddleware);
20
+ }
21
+ }
22
+ init(app) {
23
+ app.on("listening", () => {
24
+ this.socketServer.prepare(app);
25
+ });
26
+ app.on("close", async () => {
27
+ var _a;
28
+ (_a = this.middleware) == null ? void 0 : _a.close(noop);
29
+ this.socketServer.close();
30
+ });
31
+ }
32
+ sockWrite(type, data) {
33
+ this.socketServer.sockWrite(type, data);
34
+ }
35
+ setupDevMiddleware(devMiddleware) {
36
+ const { devOptions } = this;
37
+ const callbacks = {
38
+ onInvalid: () => {
39
+ this.socketServer.sockWrite("invalid");
40
+ },
41
+ onDone: (stats) => {
42
+ this.socketServer.updateStats(stats);
43
+ this.emit("change", stats);
44
+ }
45
+ };
46
+ const enableHMR = this.devOptions.hot || this.devOptions.liveReload;
47
+ const middleware = devMiddleware({
48
+ headers: devOptions.headers,
49
+ stats: false,
50
+ callbacks,
51
+ hmrClientPath: enableHMR ? getHMRClientPath(devOptions.client) : void 0,
52
+ ...devOptions.devMiddleware
53
+ });
54
+ return middleware;
55
+ }
56
+ }
57
+ export {
58
+ DevMiddleware as default
59
+ };
@@ -0,0 +1,132 @@
1
+ import ws from "ws";
2
+ import { logger } from "@modern-js/utils";
3
+ class SocketServer {
4
+ constructor(options) {
5
+ this.sockets = [];
6
+ this.timer = null;
7
+ this.options = options;
8
+ }
9
+ prepare(app) {
10
+ var _a;
11
+ this.app = app;
12
+ this.wsServer = new ws.Server({
13
+ noServer: true,
14
+ path: (_a = this.options.client) == null ? void 0 : _a.path
15
+ });
16
+ this.app.on("upgrade", (req, sock, head) => {
17
+ if (!this.wsServer.shouldHandle(req)) {
18
+ return;
19
+ }
20
+ this.wsServer.handleUpgrade(req, sock, head, (connection) => {
21
+ this.wsServer.emit("connection", connection, req);
22
+ });
23
+ });
24
+ this.wsServer.on("error", (err) => {
25
+ logger.error(err);
26
+ });
27
+ this.timer = setInterval(() => {
28
+ this.wsServer.clients.forEach((socket) => {
29
+ const extWs = socket;
30
+ if (!extWs.isAlive) {
31
+ extWs.terminate();
32
+ } else {
33
+ extWs.isAlive = false;
34
+ extWs.ping(() => {
35
+ });
36
+ }
37
+ });
38
+ }, 3e4);
39
+ this.wsServer.on("connection", (socket) => {
40
+ this.onConnect(socket);
41
+ });
42
+ }
43
+ updateStats(stats) {
44
+ this.stats = stats;
45
+ this.sendStats();
46
+ }
47
+ sockWrite(type, data) {
48
+ this.sockets.forEach((socket) => {
49
+ this.send(socket, JSON.stringify({ type, data }));
50
+ });
51
+ }
52
+ singleWrite(socket, type, data) {
53
+ this.send(socket, JSON.stringify({ type, data }));
54
+ }
55
+ close() {
56
+ this.sockets.forEach((socket) => {
57
+ socket.close();
58
+ });
59
+ if (this.timer) {
60
+ clearInterval(this.timer);
61
+ this.timer = null;
62
+ }
63
+ }
64
+ onConnect(socket) {
65
+ const connection = socket;
66
+ connection.isAlive = true;
67
+ connection.on("pong", () => {
68
+ connection.isAlive = true;
69
+ });
70
+ if (!connection) {
71
+ return;
72
+ }
73
+ this.sockets.push(connection);
74
+ connection.on("close", () => {
75
+ const idx = this.sockets.indexOf(connection);
76
+ if (idx >= 0) {
77
+ this.sockets.splice(idx, 1);
78
+ }
79
+ });
80
+ if (this.options.hot || this.options.hot === "only") {
81
+ this.singleWrite(connection, "hot");
82
+ }
83
+ if (this.options.liveReload) {
84
+ this.singleWrite(connection, "liveReload");
85
+ }
86
+ if (this.stats) {
87
+ this.sendStats(true);
88
+ }
89
+ }
90
+ getStats() {
91
+ const curStats = this.stats;
92
+ if (!curStats) {
93
+ return null;
94
+ }
95
+ const defaultStats = {
96
+ all: false,
97
+ hash: true,
98
+ assets: true,
99
+ warnings: true,
100
+ errors: true,
101
+ errorDetails: false
102
+ };
103
+ return curStats.toJson(defaultStats);
104
+ }
105
+ sendStats(force = false) {
106
+ const stats = this.getStats();
107
+ if (!stats) {
108
+ return null;
109
+ }
110
+ const shouldEmit = !force && stats && (!stats.errors || stats.errors.length === 0) && stats.assets && stats.assets.every((asset) => !asset.emitted);
111
+ if (shouldEmit) {
112
+ return this.sockWrite("still-ok");
113
+ }
114
+ this.sockWrite("hash", stats.hash);
115
+ if (stats.errors && stats.errors.length > 0) {
116
+ return this.sockWrite("errors", stats.errors);
117
+ } else if (stats.warnings && stats.warnings.length > 0) {
118
+ return this.sockWrite("warnings", stats.warnings);
119
+ } else {
120
+ return this.sockWrite("ok");
121
+ }
122
+ }
123
+ send(connection, message) {
124
+ if (connection.readyState !== 1) {
125
+ return;
126
+ }
127
+ connection.send(message);
128
+ }
129
+ }
130
+ export {
131
+ SocketServer as default
132
+ };
@@ -0,0 +1,29 @@
1
+ import { chalk, getPackageManager, logger } from "@modern-js/utils";
2
+ const genHttpsOptions = async (userOptions, pwd) => {
3
+ const httpsOptions = typeof userOptions === "boolean" ? {} : userOptions;
4
+ if (!httpsOptions.key || !httpsOptions.cert) {
5
+ let devcertPath;
6
+ try {
7
+ devcertPath = require.resolve("devcert", { paths: [pwd, __dirname] });
8
+ } catch (err) {
9
+ const packageManager = await getPackageManager(pwd);
10
+ const command = chalk.yellow.bold(
11
+ `${packageManager} install devcert@1.2.2 -D`
12
+ );
13
+ logger.error(
14
+ `You have enabled "dev.https" option, but the "devcert" package is not installed.`
15
+ );
16
+ logger.error(
17
+ `Please run ${command} to install manually, otherwise the https can not work.`
18
+ );
19
+ throw new Error('[https] "devcert" is not found.');
20
+ }
21
+ const devcert = require(devcertPath);
22
+ const selfsign = await devcert.certificateFor(["localhost"]);
23
+ return selfsign;
24
+ }
25
+ return httpsOptions;
26
+ };
27
+ export {
28
+ genHttpsOptions
29
+ };
@@ -0,0 +1,68 @@
1
+ import { match } from "path-to-regexp";
2
+ const VALID_METHODS = ["get", "post", "put", "delete", "patch"];
3
+ const BODY_PARSED_METHODS = ["post", "put", "delete", "patch"];
4
+ const createFunctionDataHandler = (method, handler) => async (context, next) => {
5
+ const { req, res } = context;
6
+ return handler(req, res, next);
7
+ };
8
+ const createStaticDataHandler = (method, handler) => (context) => {
9
+ const { res } = context;
10
+ res.setHeader("Content-Type", "application/json");
11
+ res.end(JSON.stringify(handler));
12
+ };
13
+ const allowTypes = ["object", "function"];
14
+ var getMockData_default = (mockConfig) => Object.keys(mockConfig).reduce((acc, key) => {
15
+ const handler = mockConfig[key];
16
+ const type = typeof handler;
17
+ if (!allowTypes.includes(type)) {
18
+ throw new Error(
19
+ `mock value of ${key} should be object or function, but got ${type}`
20
+ );
21
+ }
22
+ const meta = parseKey(key);
23
+ if (type === "object") {
24
+ acc.push({
25
+ ...meta,
26
+ handler: createStaticDataHandler(meta.method, handler)
27
+ });
28
+ } else {
29
+ acc.push({
30
+ ...meta,
31
+ handler: createFunctionDataHandler(meta.method, handler)
32
+ });
33
+ }
34
+ return acc;
35
+ }, []);
36
+ const _blank = " ";
37
+ const parseKey = (key) => {
38
+ const splitted = key.split(_blank).filter(Boolean);
39
+ if (splitted.length > 1) {
40
+ const [method, pathname] = splitted;
41
+ return {
42
+ method: method.toLowerCase(),
43
+ path: pathname
44
+ };
45
+ }
46
+ return {
47
+ method: "get",
48
+ path: key
49
+ };
50
+ };
51
+ const getMatched = (context, mockApiList) => {
52
+ const { path: targetPathname, method: targetMethod } = context;
53
+ const matched = mockApiList.find((mockApi) => {
54
+ const { method, path: pathname } = mockApi;
55
+ if (method.toLowerCase() === targetMethod.toLowerCase()) {
56
+ return match(pathname, {
57
+ encode: encodeURI,
58
+ decode: decodeURIComponent
59
+ })(targetPathname);
60
+ }
61
+ return false;
62
+ });
63
+ return matched;
64
+ };
65
+ export {
66
+ getMockData_default as default,
67
+ getMatched
68
+ };
@@ -0,0 +1,50 @@
1
+ import path from "path";
2
+ import { compatRequire, fs } from "@modern-js/utils";
3
+ import { AGGRED_DIR } from "@modern-js/prod-server";
4
+ import getMockData, { getMatched } from "./getMockData";
5
+ const createMockHandler = ({ pwd }) => {
6
+ const exts = [".ts", ".js"];
7
+ let filepath = "";
8
+ for (const ext of exts) {
9
+ const maybeMatch = path.join(pwd, `${AGGRED_DIR.mock}/index${ext}`);
10
+ if (fs.existsSync(maybeMatch)) {
11
+ filepath = maybeMatch;
12
+ break;
13
+ }
14
+ }
15
+ if (!filepath) {
16
+ return null;
17
+ }
18
+ const {
19
+ default: mockModule,
20
+ config
21
+ } = compatRequire(filepath, false);
22
+ if ((config == null ? void 0 : config.enable) === false) {
23
+ return null;
24
+ }
25
+ if (!mockModule) {
26
+ throw new Error(`Mock file ${filepath} parsed failed!`);
27
+ }
28
+ const apiList = getMockData(mockModule);
29
+ if (!apiList || apiList.length === 0) {
30
+ return null;
31
+ }
32
+ return async (context, next) => {
33
+ if (typeof (config == null ? void 0 : config.enable) === "function") {
34
+ const enableMock = config.enable(context.req, context.res);
35
+ if (!enableMock) {
36
+ return next();
37
+ }
38
+ }
39
+ const { res } = context;
40
+ const matched = getMatched(context, apiList);
41
+ if (!matched) {
42
+ return next();
43
+ }
44
+ res.setHeader("Access-Control-Allow-Origin", "*");
45
+ return matched.handler(context, next);
46
+ };
47
+ };
48
+ export {
49
+ createMockHandler
50
+ };