@modern-js/server 2.12.0 → 2.12.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 (52) hide show
  1. package/dist/cjs/dev-tools/dev-middleware/index.js +1 -1
  2. package/dist/esm/dev-tools/dev-middleware/index.js +1 -1
  3. package/dist/esm-node/dev-tools/dev-middleware/index.js +1 -1
  4. package/dist/js/modern/constants.js +19 -0
  5. package/dist/js/modern/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +41 -0
  6. package/dist/js/modern/dev-tools/dev-middleware/hmr-client/index.js +143 -0
  7. package/dist/js/modern/dev-tools/dev-middleware/index.js +94 -0
  8. package/dist/js/modern/dev-tools/dev-middleware/socket-server.js +132 -0
  9. package/dist/js/modern/dev-tools/https/index.js +49 -0
  10. package/dist/js/modern/dev-tools/mock/getMockData.js +114 -0
  11. package/dist/js/modern/dev-tools/mock/index.js +54 -0
  12. package/dist/js/modern/dev-tools/register/index.js +111 -0
  13. package/dist/js/modern/dev-tools/watcher/dependency-tree.js +59 -0
  14. package/dist/js/modern/dev-tools/watcher/index.js +106 -0
  15. package/dist/js/modern/dev-tools/watcher/stats-cache.js +58 -0
  16. package/dist/js/modern/index.js +12 -0
  17. package/dist/js/modern/server/dev-server.js +293 -0
  18. package/dist/js/modern/server/index.js +16 -0
  19. package/dist/js/modern/types.js +0 -0
  20. package/dist/js/node/constants.js +42 -0
  21. package/dist/js/node/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +65 -0
  22. package/dist/js/node/dev-tools/dev-middleware/hmr-client/index.js +152 -0
  23. package/dist/js/node/dev-tools/dev-middleware/index.js +119 -0
  24. package/dist/js/node/dev-tools/dev-middleware/socket-server.js +159 -0
  25. package/dist/js/node/dev-tools/https/index.js +72 -0
  26. package/dist/js/node/dev-tools/mock/getMockData.js +135 -0
  27. package/dist/js/node/dev-tools/mock/index.js +83 -0
  28. package/dist/js/node/dev-tools/register/index.js +138 -0
  29. package/dist/js/node/dev-tools/watcher/dependency-tree.js +89 -0
  30. package/dist/js/node/dev-tools/watcher/index.js +135 -0
  31. package/dist/js/node/dev-tools/watcher/stats-cache.js +87 -0
  32. package/dist/js/node/index.js +35 -0
  33. package/dist/js/node/server/dev-server.js +310 -0
  34. package/dist/js/node/server/index.js +39 -0
  35. package/dist/js/node/types.js +15 -0
  36. package/dist/js/treeshaking/constants.js +21 -0
  37. package/dist/js/treeshaking/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +51 -0
  38. package/dist/js/treeshaking/dev-tools/dev-middleware/hmr-client/index.js +157 -0
  39. package/dist/js/treeshaking/dev-tools/dev-middleware/index.js +322 -0
  40. package/dist/js/treeshaking/dev-tools/dev-middleware/socket-server.js +209 -0
  41. package/dist/js/treeshaking/dev-tools/https/index.js +193 -0
  42. package/dist/js/treeshaking/dev-tools/mock/getMockData.js +327 -0
  43. package/dist/js/treeshaking/dev-tools/mock/index.js +191 -0
  44. package/dist/js/treeshaking/dev-tools/register/index.js +153 -0
  45. package/dist/js/treeshaking/dev-tools/watcher/dependency-tree.js +150 -0
  46. package/dist/js/treeshaking/dev-tools/watcher/index.js +200 -0
  47. package/dist/js/treeshaking/dev-tools/watcher/stats-cache.js +128 -0
  48. package/dist/js/treeshaking/index.js +9 -0
  49. package/dist/js/treeshaking/server/dev-server.js +799 -0
  50. package/dist/js/treeshaking/server/index.js +92 -0
  51. package/dist/js/treeshaking/types.js +1 -0
  52. package/package.json +3 -3
@@ -40,7 +40,7 @@ function getHMRClientPath(client) {
40
40
  const path = (client == null ? void 0 : client.path) ? `&path=${client.path}` : "";
41
41
  const port = (client == null ? void 0 : client.port) ? `&port=${client.port}` : "";
42
42
  const clientEntry = `${require.resolve("./hmr-client")}?${host}${path}${port}${protocol}`;
43
- return clientEntry;
43
+ return clientEntry.replace("/cjs/", "/esm/");
44
44
  }
45
45
  class DevMiddleware extends import_events.EventEmitter {
46
46
  constructor({ dev, devMiddleware }) {
@@ -244,7 +244,7 @@ function getHMRClientPath(client) {
244
244
  var path = (client === null || client === void 0 ? void 0 : client.path) ? "&path=".concat(client.path) : "";
245
245
  var port = (client === null || client === void 0 ? void 0 : client.port) ? "&port=".concat(client.port) : "";
246
246
  var clientEntry = "".concat(require.resolve("./hmr-client"), "?").concat(host).concat(path).concat(port).concat(protocol);
247
- return clientEntry;
247
+ return clientEntry.replace("/cjs/", "/esm/");
248
248
  }
249
249
  var DevMiddleware = /*#__PURE__*/ function(EventEmitter) {
250
250
  "use strict";
@@ -8,7 +8,7 @@ function getHMRClientPath(client) {
8
8
  const path = (client == null ? void 0 : client.path) ? `&path=${client.path}` : "";
9
9
  const port = (client == null ? void 0 : client.port) ? `&port=${client.port}` : "";
10
10
  const clientEntry = `${require.resolve("./hmr-client")}?${host}${path}${port}${protocol}`;
11
- return clientEntry;
11
+ return clientEntry.replace("/cjs/", "/esm/");
12
12
  }
13
13
  class DevMiddleware extends EventEmitter {
14
14
  constructor({ dev, devMiddleware }) {
@@ -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,143 @@
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.onclose = function() {
14
+ if (typeof console !== "undefined" && typeof console.info === "function") {
15
+ console.info(
16
+ "The development server has disconnected.\nRefresh the page if necessary."
17
+ );
18
+ }
19
+ };
20
+ let isFirstCompilation = true;
21
+ let mostRecentCompilationHash = null;
22
+ let hasCompileErrors = false;
23
+ function clearOutdatedErrors() {
24
+ if (typeof console !== "undefined" && typeof console.clear === "function") {
25
+ if (hasCompileErrors) {
26
+ console.clear();
27
+ }
28
+ }
29
+ }
30
+ function handleSuccess() {
31
+ clearOutdatedErrors();
32
+ const isHotUpdate = !isFirstCompilation;
33
+ isFirstCompilation = false;
34
+ hasCompileErrors = false;
35
+ if (isHotUpdate) {
36
+ tryApplyUpdates();
37
+ }
38
+ }
39
+ function handleWarnings(warnings) {
40
+ clearOutdatedErrors();
41
+ const isHotUpdate = !isFirstCompilation;
42
+ isFirstCompilation = false;
43
+ hasCompileErrors = false;
44
+ function printWarnings() {
45
+ const formatted = formatWebpackMessages({
46
+ warnings,
47
+ errors: []
48
+ });
49
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
50
+ for (let i = 0; i < formatted.warnings.length; i++) {
51
+ if (i === 5) {
52
+ console.warn(
53
+ "There were more warnings in other files.\nYou can find a complete log in the terminal."
54
+ );
55
+ break;
56
+ }
57
+ console.warn(stripAnsi(formatted.warnings[i]));
58
+ }
59
+ }
60
+ }
61
+ printWarnings();
62
+ if (isHotUpdate) {
63
+ tryApplyUpdates();
64
+ }
65
+ }
66
+ function handleErrors(errors) {
67
+ clearOutdatedErrors();
68
+ isFirstCompilation = false;
69
+ hasCompileErrors = true;
70
+ const formatted = formatWebpackMessages({
71
+ errors,
72
+ warnings: []
73
+ });
74
+ if (typeof console !== "undefined" && typeof console.error === "function") {
75
+ for (const error of formatted.errors) {
76
+ console.error(stripAnsi(error));
77
+ }
78
+ }
79
+ }
80
+ function handleAvailableHash(hash) {
81
+ mostRecentCompilationHash = hash;
82
+ }
83
+ connection.onmessage = function(e) {
84
+ const message = JSON.parse(e.data);
85
+ switch (message.type) {
86
+ case "hash":
87
+ handleAvailableHash(message.data);
88
+ break;
89
+ case "still-ok":
90
+ case "ok":
91
+ handleSuccess();
92
+ break;
93
+ case "content-changed":
94
+ window.location.reload();
95
+ break;
96
+ case "warnings":
97
+ handleWarnings(message.data);
98
+ break;
99
+ case "errors":
100
+ handleErrors(message.data);
101
+ break;
102
+ default:
103
+ }
104
+ };
105
+ function isUpdateAvailable() {
106
+ return mostRecentCompilationHash !== __webpack_hash__;
107
+ }
108
+ function canApplyUpdates() {
109
+ return module.hot.status() === "idle";
110
+ }
111
+ function tryApplyUpdates() {
112
+ if (!module.hot) {
113
+ window.location.reload();
114
+ return;
115
+ }
116
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
117
+ return;
118
+ }
119
+ function handleApplyUpdates(err, updatedModules) {
120
+ const wantsForcedReload = err || !updatedModules || hadRuntimeError;
121
+ if (wantsForcedReload) {
122
+ window.location.reload();
123
+ return;
124
+ }
125
+ if (isUpdateAvailable()) {
126
+ tryApplyUpdates();
127
+ }
128
+ }
129
+ const result = module.hot.check(true, handleApplyUpdates);
130
+ if (result == null ? void 0 : result.then) {
131
+ result.then(
132
+ (updatedModules) => {
133
+ handleApplyUpdates(null, updatedModules);
134
+ },
135
+ (err) => {
136
+ handleApplyUpdates(err, null);
137
+ }
138
+ );
139
+ }
140
+ }
141
+ }
142
+ });
143
+ export default require_hmr_client();
@@ -0,0 +1,94 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __async = (__this, __arguments, generator) => {
18
+ return new Promise((resolve, reject) => {
19
+ var fulfilled = (value) => {
20
+ try {
21
+ step(generator.next(value));
22
+ } catch (e) {
23
+ reject(e);
24
+ }
25
+ };
26
+ var rejected = (value) => {
27
+ try {
28
+ step(generator.throw(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
+ step((generator = generator.apply(__this, __arguments)).next());
35
+ });
36
+ };
37
+ import { EventEmitter } from "events";
38
+ import SocketServer from "./socket-server";
39
+ const noop = () => {
40
+ };
41
+ function getHMRClientPath(client) {
42
+ const protocol = (client == null ? void 0 : client.protocol) ? `&protocol=${client.protocol}` : "";
43
+ const host = (client == null ? void 0 : client.host) ? `&host=${client.host}` : "";
44
+ const path = (client == null ? void 0 : client.path) ? `&path=${client.path}` : "";
45
+ const port = (client == null ? void 0 : client.port) ? `&port=${client.port}` : "";
46
+ const clientEntry = `${require.resolve("./hmr-client")}?${host}${path}${port}${protocol}`;
47
+ return clientEntry;
48
+ }
49
+ class DevMiddleware extends EventEmitter {
50
+ constructor({ dev, devMiddleware }) {
51
+ super();
52
+ this.devOptions = dev;
53
+ this.socketServer = new SocketServer(dev);
54
+ if (devMiddleware) {
55
+ this.middleware = this.setupDevMiddleware(devMiddleware);
56
+ }
57
+ }
58
+ init(app) {
59
+ app.on("listening", () => {
60
+ this.socketServer.prepare(app);
61
+ });
62
+ app.on("close", () => __async(this, null, function* () {
63
+ var _a;
64
+ (_a = this.middleware) == null ? void 0 : _a.close(noop);
65
+ this.socketServer.close();
66
+ }));
67
+ }
68
+ sockWrite(type, data) {
69
+ this.socketServer.sockWrite(type, data);
70
+ }
71
+ setupDevMiddleware(devMiddleware) {
72
+ const { devOptions } = this;
73
+ const callbacks = {
74
+ onInvalid: () => {
75
+ this.socketServer.sockWrite("invalid");
76
+ },
77
+ onDone: (stats) => {
78
+ this.socketServer.updateStats(stats);
79
+ this.emit("change", stats);
80
+ }
81
+ };
82
+ const enableHMR = this.devOptions.hot || this.devOptions.liveReload;
83
+ const middleware = devMiddleware(__spreadValues({
84
+ headers: devOptions.headers,
85
+ stats: false,
86
+ callbacks,
87
+ hmrClientPath: enableHMR ? getHMRClientPath(devOptions.client) : void 0
88
+ }, devOptions.devMiddleware));
89
+ return middleware;
90
+ }
91
+ }
92
+ export {
93
+ DevMiddleware as default
94
+ };
@@ -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,49 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ import { chalk, getPackageManager, logger } from "@modern-js/utils";
22
+ const genHttpsOptions = (userOptions, pwd) => __async(void 0, null, function* () {
23
+ const httpsOptions = typeof userOptions === "boolean" ? {} : userOptions;
24
+ if (!httpsOptions.key || !httpsOptions.cert) {
25
+ let devcertPath;
26
+ try {
27
+ devcertPath = require.resolve("devcert", { paths: [pwd, __dirname] });
28
+ } catch (err) {
29
+ const packageManager = yield getPackageManager(pwd);
30
+ const command = chalk.yellow.bold(
31
+ `${packageManager} install devcert@1.2.2 -D`
32
+ );
33
+ logger.error(
34
+ `You have enabled "dev.https" option, but the "devcert" package is not installed.`
35
+ );
36
+ logger.error(
37
+ `Please run ${command} to install manually, otherwise the https can not work.`
38
+ );
39
+ throw new Error('[https] "devcert" is not found.');
40
+ }
41
+ const devcert = require(devcertPath);
42
+ const selfsign = yield devcert.certificateFor(["localhost"]);
43
+ return selfsign;
44
+ }
45
+ return httpsOptions;
46
+ });
47
+ export {
48
+ genHttpsOptions
49
+ };
@@ -0,0 +1,114 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+ import { compatRequire } from "@modern-js/utils";
41
+ import { match } from "path-to-regexp";
42
+ const VALID_METHODS = ["get", "post", "put", "delete", "patch"];
43
+ const BODY_PARSED_METHODS = ["post", "put", "delete", "patch"];
44
+ const createFunctionDataHandler = (method, handler) => (context, next) => __async(void 0, null, function* () {
45
+ const { req, res } = context;
46
+ return handler(req, res, next);
47
+ });
48
+ const createStaticDataHandler = (method, handler) => (context) => {
49
+ const { res } = context;
50
+ res.setHeader("Content-Type", "application/json");
51
+ res.end(JSON.stringify(handler));
52
+ };
53
+ const allowTypes = ["object", "function"];
54
+ const normalizeConfig = (mockConfig) => Object.keys(mockConfig).reduce((acc, key) => {
55
+ const handler = mockConfig[key];
56
+ const type = typeof handler;
57
+ if (!allowTypes.includes(type)) {
58
+ throw new Error(
59
+ `mock value of ${key} should be object or function, but got ${type}`
60
+ );
61
+ }
62
+ const meta = parseKey(key);
63
+ if (type === "object") {
64
+ acc.push(__spreadProps(__spreadValues({}, meta), {
65
+ handler: createStaticDataHandler(meta.method, handler)
66
+ }));
67
+ } else {
68
+ acc.push(__spreadProps(__spreadValues({}, meta), {
69
+ handler: createFunctionDataHandler(meta.method, handler)
70
+ }));
71
+ }
72
+ return acc;
73
+ }, []);
74
+ const _blank = " ";
75
+ const parseKey = (key) => {
76
+ const splitted = key.split(_blank).filter(Boolean);
77
+ if (splitted.length > 1) {
78
+ const [method, pathname] = splitted;
79
+ return {
80
+ method: method.toLowerCase(),
81
+ path: pathname
82
+ };
83
+ }
84
+ return {
85
+ method: "get",
86
+ path: key
87
+ };
88
+ };
89
+ var getMockData_default = (filepath) => {
90
+ const mockModule = compatRequire(filepath);
91
+ if (!mockModule) {
92
+ throw new Error(`Mock file ${filepath} parsed failed!`);
93
+ }
94
+ const data = normalizeConfig(mockModule);
95
+ return data;
96
+ };
97
+ const getMatched = (context, mockApiList) => {
98
+ const { path: targetPathname, method: targetMethod } = context;
99
+ const matched = mockApiList.find((mockApi) => {
100
+ const { method, path: pathname } = mockApi;
101
+ if (method.toLowerCase() === targetMethod.toLowerCase()) {
102
+ return match(pathname, {
103
+ encode: encodeURI,
104
+ decode: decodeURIComponent
105
+ })(targetPathname);
106
+ }
107
+ return false;
108
+ });
109
+ return matched;
110
+ };
111
+ export {
112
+ getMockData_default as default,
113
+ getMatched
114
+ };
@@ -0,0 +1,54 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ import path from "path";
22
+ import { fs } from "@modern-js/utils";
23
+ import { AGGRED_DIR } from "@modern-js/prod-server";
24
+ import getMockData, { getMatched } from "./getMockData";
25
+ const createMockHandler = ({ pwd }) => {
26
+ const exts = [".ts", ".js"];
27
+ let filepath = "";
28
+ for (const ext of exts) {
29
+ const maybeMatch = path.join(pwd, `${AGGRED_DIR.mock}/index${ext}`);
30
+ if (fs.existsSync(maybeMatch)) {
31
+ filepath = maybeMatch;
32
+ break;
33
+ }
34
+ }
35
+ if (!filepath) {
36
+ return null;
37
+ }
38
+ const apiList = getMockData(filepath);
39
+ if (!apiList || apiList.length === 0) {
40
+ return null;
41
+ }
42
+ return (context, next) => __async(void 0, null, function* () {
43
+ const { res } = context;
44
+ const matched = getMatched(context, apiList);
45
+ if (!matched) {
46
+ return next();
47
+ }
48
+ res.setHeader("Access-Control-Allow-Origin", "*");
49
+ return matched.handler(context, next);
50
+ });
51
+ };
52
+ export {
53
+ createMockHandler
54
+ };