@modern-js/prod-server 1.21.6 → 2.0.0-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 (132) hide show
  1. package/CHANGELOG.md +274 -13
  2. package/dist/js/modern/constants.js +32 -27
  3. package/dist/js/modern/index.js +11 -7
  4. package/dist/js/modern/libs/context/context.js +54 -132
  5. package/dist/js/modern/libs/context/index.js +5 -2
  6. package/dist/js/modern/libs/hook-api/index.js +134 -0
  7. package/dist/js/modern/libs/hook-api/route.js +13 -37
  8. package/dist/js/modern/libs/hook-api/template.js +41 -32
  9. package/dist/js/modern/libs/loadConfig.js +46 -32
  10. package/dist/js/modern/libs/metrics.js +6 -7
  11. package/dist/js/modern/libs/proxy.js +70 -44
  12. package/dist/js/modern/libs/render/cache/__tests__/cache.fun.test.js +112 -68
  13. package/dist/js/modern/libs/render/cache/__tests__/cache.test.js +246 -225
  14. package/dist/js/modern/libs/render/cache/__tests__/cacheable.js +43 -49
  15. package/dist/js/modern/libs/render/cache/__tests__/error-configuration.js +36 -34
  16. package/dist/js/modern/libs/render/cache/__tests__/matched-cache.js +83 -113
  17. package/dist/js/modern/libs/render/cache/index.js +93 -50
  18. package/dist/js/modern/libs/render/cache/page-caches/index.js +31 -8
  19. package/dist/js/modern/libs/render/cache/page-caches/lru.js +6 -16
  20. package/dist/js/modern/libs/render/cache/spr.js +133 -167
  21. package/dist/js/modern/libs/render/cache/type.js +0 -1
  22. package/dist/js/modern/libs/render/cache/util.js +71 -45
  23. package/dist/js/modern/libs/render/index.js +76 -61
  24. package/dist/js/modern/libs/render/measure.js +42 -34
  25. package/dist/js/modern/libs/render/reader.js +68 -76
  26. package/dist/js/modern/libs/render/ssr.js +63 -33
  27. package/dist/js/modern/libs/render/static.js +51 -37
  28. package/dist/js/modern/libs/render/type.js +9 -7
  29. package/dist/js/modern/libs/route/index.js +12 -30
  30. package/dist/js/modern/libs/route/matcher.js +28 -50
  31. package/dist/js/modern/libs/route/route.js +9 -31
  32. package/dist/js/modern/libs/serve-file.js +40 -20
  33. package/dist/js/modern/server/index.js +152 -168
  34. package/dist/js/modern/server/modern-server-split.js +44 -60
  35. package/dist/js/modern/server/modern-server.js +416 -526
  36. package/dist/js/modern/type.js +0 -1
  37. package/dist/js/modern/utils.js +62 -58
  38. package/dist/js/modern/worker-server.js +54 -0
  39. package/dist/js/node/constants.js +53 -32
  40. package/dist/js/node/index.js +37 -67
  41. package/dist/js/node/libs/context/context.js +84 -150
  42. package/dist/js/node/libs/context/index.js +28 -16
  43. package/dist/js/node/libs/hook-api/index.js +164 -0
  44. package/dist/js/node/libs/hook-api/route.js +35 -45
  45. package/dist/js/node/libs/hook-api/template.js +64 -40
  46. package/dist/js/node/libs/loadConfig.js +74 -55
  47. package/dist/js/node/libs/metrics.js +28 -12
  48. package/dist/js/node/libs/proxy.js +90 -55
  49. package/dist/js/node/libs/render/cache/__tests__/cache.fun.test.js +99 -61
  50. package/dist/js/node/libs/render/cache/__tests__/cache.test.js +147 -140
  51. package/dist/js/node/libs/render/cache/__tests__/cacheable.js +65 -55
  52. package/dist/js/node/libs/render/cache/__tests__/error-configuration.js +58 -40
  53. package/dist/js/node/libs/render/cache/__tests__/matched-cache.js +105 -119
  54. package/dist/js/node/libs/render/cache/index.js +115 -65
  55. package/dist/js/node/libs/render/cache/page-caches/index.js +54 -16
  56. package/dist/js/node/libs/render/cache/page-caches/lru.js +33 -26
  57. package/dist/js/node/libs/render/cache/spr.js +161 -188
  58. package/dist/js/node/libs/render/cache/type.js +15 -5
  59. package/dist/js/node/libs/render/cache/util.js +99 -63
  60. package/dist/js/node/libs/render/index.js +106 -87
  61. package/dist/js/node/libs/render/measure.js +61 -44
  62. package/dist/js/node/libs/render/reader.js +98 -100
  63. package/dist/js/node/libs/render/ssr.js +92 -58
  64. package/dist/js/node/libs/render/static.js +80 -53
  65. package/dist/js/node/libs/render/type.js +31 -13
  66. package/dist/js/node/libs/route/index.js +35 -44
  67. package/dist/js/node/libs/route/matcher.js +48 -65
  68. package/dist/js/node/libs/route/route.js +29 -37
  69. package/dist/js/node/libs/serve-file.js +74 -37
  70. package/dist/js/node/server/index.js +170 -203
  71. package/dist/js/node/server/modern-server-split.js +70 -73
  72. package/dist/js/node/server/modern-server.js +432 -577
  73. package/dist/js/node/type.js +15 -3
  74. package/dist/js/node/utils.js +87 -93
  75. package/dist/js/node/worker-server.js +77 -0
  76. package/dist/js/treeshaking/constants.js +29 -0
  77. package/dist/js/treeshaking/index.js +13 -0
  78. package/dist/js/treeshaking/libs/context/context.js +274 -0
  79. package/dist/js/treeshaking/libs/context/index.js +5 -0
  80. package/dist/js/treeshaking/libs/hook-api/index.js +281 -0
  81. package/dist/js/treeshaking/libs/hook-api/route.js +68 -0
  82. package/dist/js/treeshaking/libs/hook-api/template.js +127 -0
  83. package/dist/js/treeshaking/libs/loadConfig.js +82 -0
  84. package/dist/js/treeshaking/libs/metrics.js +6 -0
  85. package/dist/js/treeshaking/libs/proxy.js +244 -0
  86. package/dist/js/treeshaking/libs/render/cache/__tests__/cache.fun.test.js +291 -0
  87. package/dist/js/treeshaking/libs/render/cache/__tests__/cache.test.js +781 -0
  88. package/dist/js/treeshaking/libs/render/cache/__tests__/cacheable.js +67 -0
  89. package/dist/js/treeshaking/libs/render/cache/__tests__/error-configuration.js +45 -0
  90. package/dist/js/treeshaking/libs/render/cache/__tests__/matched-cache.js +147 -0
  91. package/dist/js/treeshaking/libs/render/cache/index.js +346 -0
  92. package/dist/js/treeshaking/libs/render/cache/page-caches/index.js +154 -0
  93. package/dist/js/treeshaking/libs/render/cache/page-caches/lru.js +84 -0
  94. package/dist/js/treeshaking/libs/render/cache/spr.js +492 -0
  95. package/dist/js/treeshaking/libs/render/cache/type.js +1 -0
  96. package/dist/js/treeshaking/libs/render/cache/util.js +280 -0
  97. package/dist/js/treeshaking/libs/render/index.js +233 -0
  98. package/dist/js/treeshaking/libs/render/measure.js +146 -0
  99. package/dist/js/treeshaking/libs/render/reader.js +339 -0
  100. package/dist/js/treeshaking/libs/render/ssr.js +223 -0
  101. package/dist/js/treeshaking/libs/render/static.js +216 -0
  102. package/dist/js/treeshaking/libs/render/type.js +7 -0
  103. package/dist/js/treeshaking/libs/route/index.js +130 -0
  104. package/dist/js/treeshaking/libs/route/matcher.js +138 -0
  105. package/dist/js/treeshaking/libs/route/route.js +40 -0
  106. package/dist/js/treeshaking/libs/serve-file.js +184 -0
  107. package/dist/js/treeshaking/server/index.js +505 -0
  108. package/dist/js/treeshaking/server/modern-server-split.js +360 -0
  109. package/dist/js/treeshaking/server/modern-server.js +1083 -0
  110. package/dist/js/treeshaking/type.js +1 -0
  111. package/dist/js/treeshaking/utils.js +147 -0
  112. package/dist/js/treeshaking/worker-server.js +177 -0
  113. package/dist/types/libs/context/context.d.ts +1 -1
  114. package/dist/types/libs/hook-api/index.d.ts +5 -0
  115. package/dist/types/libs/hook-api/route.d.ts +9 -14
  116. package/dist/types/libs/hook-api/template.d.ts +19 -9
  117. package/dist/types/libs/render/cache/index.d.ts +4 -2
  118. package/dist/types/libs/render/type.d.ts +3 -1
  119. package/dist/types/libs/route/route.d.ts +0 -1
  120. package/dist/types/libs/serve-file.d.ts +2 -1
  121. package/dist/types/server/index.d.ts +2 -0
  122. package/dist/types/server/modern-server.d.ts +11 -11
  123. package/dist/types/type.d.ts +8 -10
  124. package/dist/types/utils.d.ts +3 -4
  125. package/dist/types/worker-server.d.ts +15 -0
  126. package/package.json +31 -45
  127. package/dist/js/modern/libs/render/modern/browser-list.js +0 -7
  128. package/dist/js/modern/libs/render/modern/index.js +0 -48
  129. package/dist/js/node/libs/render/modern/browser-list.js +0 -14
  130. package/dist/js/node/libs/render/modern/index.js +0 -64
  131. package/dist/types/libs/render/modern/browser-list.d.ts +0 -1
  132. package/dist/types/libs/render/modern/index.d.ts +0 -3
@@ -1,67 +1,93 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __spreadValues = (a, b) => {
11
+ for (var prop in b || (b = {}))
12
+ if (__hasOwnProp.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ if (__getOwnPropSymbols)
15
+ for (var prop of __getOwnPropSymbols(b)) {
16
+ if (__propIsEnum.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ }
19
+ return a;
20
+ };
21
+ var __objRest = (source, exclude) => {
22
+ var target = {};
23
+ for (var prop in source)
24
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
25
+ target[prop] = source[prop];
26
+ if (source != null && __getOwnPropSymbols)
27
+ for (var prop of __getOwnPropSymbols(source)) {
28
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
29
+ target[prop] = source[prop];
30
+ }
31
+ return target;
32
+ };
33
+ var __export = (target, all) => {
34
+ for (var name in all)
35
+ __defProp(target, name, { get: all[name], enumerable: true });
36
+ };
37
+ var __copyProps = (to, from, except, desc) => {
38
+ if (from && typeof from === "object" || typeof from === "function") {
39
+ for (let key of __getOwnPropNames(from))
40
+ if (!__hasOwnProp.call(to, key) && key !== except)
41
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
42
+ }
43
+ return to;
44
+ };
45
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
46
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
47
+ mod
48
+ ));
49
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
50
+ var __async = (__this, __arguments, generator) => {
51
+ return new Promise((resolve, reject) => {
52
+ var fulfilled = (value) => {
53
+ try {
54
+ step(generator.next(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var rejected = (value) => {
60
+ try {
61
+ step(generator.throw(value));
62
+ } catch (e) {
63
+ reject(e);
64
+ }
65
+ };
66
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
67
+ step((generator = generator.apply(__this, __arguments)).next());
68
+ });
69
+ };
70
+ var modern_server_exports = {};
71
+ __export(modern_server_exports, {
72
+ ModernServer: () => ModernServer
5
73
  });
6
- exports.ModernServer = void 0;
7
-
8
- var _http = require("http");
9
-
10
- var _util = _interopRequireDefault(require("util"));
11
-
12
- var _path = _interopRequireDefault(require("path"));
13
-
14
- var _utils = require("@modern-js/utils");
15
-
16
- var _axios = _interopRequireDefault(require("axios"));
17
-
18
- var _lodash = require("@modern-js/utils/lodash");
19
-
20
- var _route = require("../libs/route");
21
-
22
- var _render = require("../libs/render");
23
-
24
- var _serveFile = require("../libs/serve-file");
25
-
26
- var _utils2 = require("../utils");
27
-
28
- var reader = _interopRequireWildcard(require("../libs/render/reader"));
29
-
30
- var _proxy = require("../libs/proxy");
31
-
32
- var _context = require("../libs/context");
33
-
34
- var _constants = require("../constants");
35
-
36
- var _template = require("../libs/hook-api/template");
37
-
38
- var _route2 = require("../libs/hook-api/route");
39
-
40
- const _excluded = ["getMiddlewares"];
41
-
42
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
43
-
44
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
45
-
46
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
47
-
48
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
49
-
50
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
51
-
52
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
53
-
54
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
55
-
56
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
57
-
58
- const API_DIR = './api';
59
- const SERVER_DIR = './server';
60
-
74
+ module.exports = __toCommonJS(modern_server_exports);
75
+ var import_http = require("http");
76
+ var import_path = __toESM(require("path"));
77
+ var import_utils = require("@modern-js/utils");
78
+ var import_route = require("../libs/route");
79
+ var import_render = require("../libs/render");
80
+ var import_serve_file = require("../libs/serve-file");
81
+ var import_utils2 = require("../utils");
82
+ var reader = __toESM(require("../libs/render/reader"));
83
+ var import_proxy = require("../libs/proxy");
84
+ var import_context = require("../libs/context");
85
+ var import_template = require("../libs/hook-api/template");
86
+ var import_constants = require("../constants");
87
+ var import_hook_api = require("../libs/hook-api");
88
+ const API_DIR = "./api";
89
+ const SERVER_DIR = "./server";
61
90
  class ModernServer {
62
- // appDirectory
63
- // product dist dir
64
- // work on src or dist
65
91
  constructor({
66
92
  pwd,
67
93
  config,
@@ -72,627 +98,456 @@ class ModernServer {
72
98
  runMode,
73
99
  proxyTarget
74
100
  }) {
75
- var _config$output;
76
-
77
- _defineProperty(this, "pwd", void 0);
78
-
79
- _defineProperty(this, "distDir", void 0);
80
-
81
- _defineProperty(this, "workDir", void 0);
82
-
83
- _defineProperty(this, "router", void 0);
84
-
85
- _defineProperty(this, "conf", void 0);
86
-
87
- _defineProperty(this, "handlers", []);
88
-
89
- _defineProperty(this, "presetRoutes", void 0);
90
-
91
- _defineProperty(this, "runner", void 0);
92
-
93
- _defineProperty(this, "logger", void 0);
94
-
95
- _defineProperty(this, "metrics", void 0);
96
-
97
- _defineProperty(this, "runMode", void 0);
98
-
99
- _defineProperty(this, "reader", reader);
100
-
101
- _defineProperty(this, "proxyTarget", void 0);
102
-
103
- _defineProperty(this, "staticFileHandler", void 0);
104
-
105
- _defineProperty(this, "routeRenderHandler", void 0);
106
-
107
- _defineProperty(this, "frameWebHandler", null);
108
-
109
- _defineProperty(this, "frameAPIHandler", null);
110
-
111
- _defineProperty(this, "proxyHandler", null);
112
-
113
- _defineProperty(this, "_handler", void 0);
114
-
115
- _defineProperty(this, "staticGenerate", void 0);
116
-
117
- require('ignore-styles');
118
-
101
+ this.handlers = [];
102
+ this.reader = reader;
103
+ this.beforeRouteHandler = null;
104
+ this.frameWebHandler = null;
105
+ this.frameAPIHandler = null;
106
+ this.proxyHandler = null;
107
+ require("ignore-styles");
119
108
  this.pwd = pwd;
120
- this.distDir = _path.default.join(pwd, ((_config$output = config.output) === null || _config$output === void 0 ? void 0 : _config$output.path) || 'dist');
109
+ this.distDir = import_path.default.join(pwd, config.output.path || "dist");
121
110
  this.workDir = this.distDir;
122
111
  this.conf = config;
123
- (0, _utils2.debug)('server conf', this.conf);
112
+ (0, import_utils2.debug)("server conf", this.conf);
124
113
  this.logger = logger;
125
114
  this.metrics = metrics;
126
- this.router = new _route.RouteMatchManager();
115
+ this.router = new import_route.RouteMatchManager();
127
116
  this.presetRoutes = routes;
128
117
  this.proxyTarget = proxyTarget;
129
118
  this.staticGenerate = staticGenerate || false;
130
- this.runMode = runMode || _constants.RUN_MODE.TYPE;
131
- process.env.BUILD_TYPE = `${this.staticGenerate ? 'ssg' : 'ssr'}`;
132
- } // server prepare
133
-
134
-
135
- async onInit(runner, app) {
136
- var _conf$bff;
137
-
138
- this.runner = runner;
139
- const {
140
- distDir,
141
- staticGenerate,
142
- conf
143
- } = this;
144
- (0, _utils2.debug)('final server conf', this.conf); // proxy handler, each proxy has own handler
145
-
146
- this.proxyHandler = (0, _proxy.createProxyHandler)((_conf$bff = conf.bff) === null || _conf$bff === void 0 ? void 0 : _conf$bff.proxy);
147
-
148
- if (this.proxyHandler) {
149
- this.proxyHandler.forEach(handler => {
150
- this.addHandler(handler);
119
+ this.runMode = runMode || import_constants.RUN_MODE.FULL;
120
+ }
121
+ onInit(runner, app) {
122
+ return __async(this, null, function* () {
123
+ var _a;
124
+ this.runner = runner;
125
+ const { distDir, staticGenerate, conf } = this;
126
+ (0, import_utils2.debug)("final server conf", this.conf);
127
+ this.proxyHandler = (0, import_proxy.createProxyHandler)((_a = conf.bff) == null ? void 0 : _a.proxy);
128
+ if (this.proxyHandler) {
129
+ this.proxyHandler.forEach((handler) => {
130
+ this.addHandler(handler);
131
+ });
132
+ }
133
+ this.reader.init();
134
+ app.on("close", () => {
135
+ this.reader.close();
136
+ });
137
+ const usageRoutes = this.filterRoutes(this.getRoutes());
138
+ this.router.reset(usageRoutes);
139
+ this.warmupSSRBundle();
140
+ yield this.prepareFrameHandler();
141
+ yield this.prepareBeforeRouteHandler(usageRoutes, distDir);
142
+ const staticPathRegExp = (0, import_utils2.getStaticReg)(
143
+ this.conf.output || {},
144
+ this.conf.html
145
+ );
146
+ this.staticFileHandler = (0, import_serve_file.createStaticFileHandler)(
147
+ [
148
+ {
149
+ path: staticPathRegExp,
150
+ target: distDir
151
+ }
152
+ ],
153
+ this.conf.output
154
+ );
155
+ this.routeRenderHandler = (0, import_render.createRenderHandler)({
156
+ distDir,
157
+ staticGenerate
151
158
  });
152
- } // start file reader
153
-
154
-
155
- this.reader.init();
156
- app.on('close', () => {
157
- this.reader.close();
158
- }); // use preset routes priority
159
-
160
- const usageRoutes = this.filterRoutes(this.getRoutes());
161
- this.router.reset(usageRoutes); // warmup ssr bundle in production env
162
-
163
- this.warmupSSRBundle();
164
- await this.prepareFrameHandler(); // Only work when without setting `assetPrefix`.
165
- // Setting `assetPrefix` means these resources should be uploaded to CDN.
166
-
167
- const staticPathRegExp = (0, _utils2.getStaticReg)(this.conf.output || {});
168
- this.staticFileHandler = (0, _serveFile.createStaticFileHandler)([{
169
- path: staticPathRegExp,
170
- target: distDir
171
- }], this.conf.output);
172
- this.routeRenderHandler = (0, _render.createRenderHandler)({
173
- distDir,
174
- staticGenerate
159
+ yield this.setupBeforeProdMiddleware();
160
+ this.addHandler(this.staticFileHandler);
161
+ this.addHandler(import_serve_file.faviconFallbackHandler);
162
+ this.addBeforeRouteHandler();
163
+ this.addHandler(this.routeHandler.bind(this));
164
+ this.compose();
175
165
  });
176
- await this.setupBeforeProdMiddleware();
177
- this.addHandler(this.staticFileHandler);
178
- this.addHandler(this.routeHandler.bind(this)); // compose middlewares to http handler
179
-
180
- this.compose();
181
- } // server ready
182
-
183
-
184
- onRepack(_) {// empty
185
166
  }
186
-
187
- onServerChange({
188
- filepath
189
- }) {
190
- const {
191
- pwd
192
- } = this;
193
- const {
194
- api,
195
- server
196
- } = _constants.AGGRED_DIR;
197
-
198
- const apiPath = _path.default.normalize(_path.default.join(pwd, api));
199
-
200
- const serverPath = _path.default.normalize(_path.default.join(pwd, server));
201
-
167
+ onRepack(_) {
168
+ }
169
+ addBeforeRouteHandler() {
170
+ this.addHandler((context, next) => __async(this, null, function* () {
171
+ if (this.beforeRouteHandler) {
172
+ yield this.beforeRouteHandler(context);
173
+ if (this.isSend(context.res)) {
174
+ return;
175
+ }
176
+ }
177
+ return next();
178
+ }));
179
+ }
180
+ onServerChange({ filepath }) {
181
+ const { pwd } = this;
182
+ const { api, server } = import_constants.AGGRED_DIR;
183
+ const apiPath = import_path.default.normalize(import_path.default.join(pwd, api));
184
+ const serverPath = import_path.default.normalize(import_path.default.join(pwd, server));
202
185
  const onlyApi = filepath.startsWith(apiPath);
203
186
  const onlyWeb = filepath.startsWith(serverPath);
204
- this.prepareFrameHandler({
205
- onlyWeb,
206
- onlyApi
207
- });
208
- } // exposed requestHandler
209
-
210
-
187
+ this.prepareFrameHandler({ onlyWeb, onlyApi });
188
+ }
211
189
  getRequestHandler() {
212
190
  return this.requestHandler.bind(this);
213
191
  }
214
-
215
- async createHTTPServer(handler) {
216
- return (0, _http.createServer)(handler);
192
+ render(req, res, url) {
193
+ return __async(this, null, function* () {
194
+ req.logger = this.logger;
195
+ req.metrics = this.metrics;
196
+ const context = (0, import_context.createContext)(req, res);
197
+ const matched = this.router.match(url || context.path);
198
+ if (!matched) {
199
+ return null;
200
+ }
201
+ const route = matched.generate(context.url);
202
+ const result = yield this.handleWeb(context, route);
203
+ if (!result) {
204
+ return null;
205
+ }
206
+ return result.content.toString();
207
+ });
208
+ }
209
+ createHTTPServer(handler) {
210
+ return __async(this, null, function* () {
211
+ return (0, import_http.createServer)(handler);
212
+ });
217
213
  }
218
- /* —————————————————————— function will be overwrite —————————————————————— */
219
- // get routes info
220
-
221
-
222
214
  getRoutes() {
223
- // Preferred to use preset routes
224
215
  if (this.presetRoutes) {
225
216
  return this.presetRoutes;
226
- } // read routes from spec file
227
-
228
-
229
- const file = _path.default.join(this.distDir, _utils.ROUTE_SPEC_FILE);
230
-
231
- if (_utils.fs.existsSync(file)) {
232
- const content = _utils.fs.readJSONSync(file);
233
-
217
+ }
218
+ const file = import_path.default.join(this.distDir, import_utils.ROUTE_SPEC_FILE);
219
+ if (import_utils.fs.existsSync(file)) {
220
+ const content = import_utils.fs.readJSONSync(file);
234
221
  return content.routes;
235
222
  }
236
-
237
223
  return [];
238
- } // add promisify request handler to server
239
- // handler should do not do more things after invoke next
240
-
241
-
224
+ }
242
225
  addHandler(handler) {
243
- if (handler[Symbol.toStringTag] === 'AsyncFunction') {
244
- this.handlers.push(handler);
245
- } else {
246
- this.handlers.push(_util.default.promisify(handler));
247
- }
248
- } // return 404 page
249
-
250
-
226
+ this.handlers.push(handler);
227
+ }
251
228
  render404(context) {
252
- context.error(_constants.ERROR_DIGEST.ENOTF, '404 Not Found');
229
+ context.error(import_constants.ERROR_DIGEST.ENOTF, "404 Not Found");
253
230
  this.renderErrorPage(context, 404);
254
- } // gather frame extension and get framework handler
255
-
256
-
257
- async prepareFrameHandler(options) {
258
- const {
259
- workDir,
260
- runner
261
- } = this;
262
- const {
263
- onlyApi,
264
- onlyWeb
265
- } = options || {}; // server hook, gather plugin inject
266
-
267
- const _createMiddlewareColl = (0, _utils2.createMiddlewareCollecter)(),
268
- {
269
- getMiddlewares
270
- } = _createMiddlewareColl,
271
- collector = _objectWithoutProperties(_createMiddlewareColl, _excluded);
272
-
273
- await runner.gather(collector);
274
- const {
275
- api: pluginAPIExt,
276
- web: pluginWebExt
277
- } = getMiddlewares();
278
-
279
- const apiDir = _path.default.join(workDir, API_DIR);
280
-
281
- const serverDir = _path.default.join(workDir, SERVER_DIR); // get api or web server handler from server-framework plugin
282
-
283
-
284
- if ((await _utils.fs.pathExists(_path.default.join(serverDir))) && !onlyApi) {
285
- const webExtension = (0, _utils2.mergeExtension)(pluginWebExt);
286
- this.frameWebHandler = await this.prepareWebHandler(webExtension);
287
- }
288
-
289
- if (_utils.fs.existsSync(apiDir) && !onlyWeb) {
290
- const apiExtension = (0, _utils2.mergeExtension)(pluginAPIExt);
291
- this.frameAPIHandler = await this.prepareAPIHandler(apiExtension);
292
- }
293
231
  }
294
-
295
- async prepareWebHandler(extension) {
296
- const {
297
- workDir,
298
- runner
299
- } = this;
300
- return runner.prepareWebServer({
301
- pwd: workDir,
302
- config: extension
303
- }, {
304
- onLast: () => null
232
+ prepareBeforeRouteHandler(specs, distDir) {
233
+ return __async(this, null, function* () {
234
+ const { runner } = this;
235
+ const handler = yield runner.preparebeforeRouteHandler(
236
+ {
237
+ serverRoutes: specs,
238
+ distDir
239
+ },
240
+ {
241
+ onLast: () => null
242
+ }
243
+ );
244
+ this.beforeRouteHandler = handler;
245
+ });
246
+ }
247
+ prepareFrameHandler(options) {
248
+ return __async(this, null, function* () {
249
+ const { workDir, runner } = this;
250
+ const { onlyApi, onlyWeb } = options || {};
251
+ const _a = (0, import_utils2.createMiddlewareCollecter)(), { getMiddlewares } = _a, collector = __objRest(_a, ["getMiddlewares"]);
252
+ yield runner.gather(collector);
253
+ const { api: pluginAPIExt, web: pluginWebExt } = getMiddlewares();
254
+ const apiDir = import_path.default.join(workDir, API_DIR);
255
+ const serverDir = import_path.default.join(workDir, SERVER_DIR);
256
+ if ((yield import_utils.fs.pathExists(import_path.default.join(serverDir))) && !onlyApi) {
257
+ const webExtension = (0, import_utils2.mergeExtension)(pluginWebExt);
258
+ this.frameWebHandler = yield this.prepareWebHandler(webExtension);
259
+ }
260
+ if (import_utils.fs.existsSync(apiDir) && !onlyWeb) {
261
+ const apiExtension = (0, import_utils2.mergeExtension)(pluginAPIExt);
262
+ this.frameAPIHandler = yield this.prepareAPIHandler(apiExtension);
263
+ }
264
+ });
265
+ }
266
+ prepareWebHandler(extension) {
267
+ return __async(this, null, function* () {
268
+ const { workDir, runner } = this;
269
+ const handler = yield runner.prepareWebServer(
270
+ {
271
+ pwd: workDir,
272
+ config: extension
273
+ },
274
+ { onLast: () => null }
275
+ );
276
+ return handler;
305
277
  });
306
278
  }
307
-
308
- async prepareAPIHandler(extension) {
309
- const {
310
- workDir,
311
- runner,
312
- conf
313
- } = this;
314
- const {
315
- bff
316
- } = conf;
317
- const prefix = (bff === null || bff === void 0 ? void 0 : bff.prefix) || '/api';
318
- return runner.prepareApiServer({
319
- pwd: workDir,
320
- config: extension,
321
- prefix: Array.isArray(prefix) ? prefix[0] : prefix
322
- }, {
323
- onLast: () => null
279
+ prepareAPIHandler(extension) {
280
+ return __async(this, null, function* () {
281
+ const { workDir, runner, conf } = this;
282
+ const { bff } = conf;
283
+ const prefix = (bff == null ? void 0 : bff.prefix) || "/api";
284
+ return runner.prepareApiServer(
285
+ {
286
+ pwd: workDir,
287
+ config: extension,
288
+ prefix: Array.isArray(prefix) ? prefix[0] : prefix
289
+ },
290
+ { onLast: () => null }
291
+ );
324
292
  });
325
293
  }
326
-
327
294
  filterRoutes(routes) {
328
295
  return routes;
329
296
  }
330
-
331
- async emitRouteHook(eventName, input) {
332
- input.context = (0, _lodash.clone)(input.context);
333
- return this.runner[eventName](input, {
334
- onLast: _utils2.noop
297
+ setupBeforeProdMiddleware() {
298
+ return __async(this, null, function* () {
299
+ const { conf, runner } = this;
300
+ const preMiddleware = yield runner.beforeProdServer(conf);
301
+ preMiddleware.flat().forEach((mid) => {
302
+ this.addHandler(mid);
303
+ });
335
304
  });
336
305
  }
337
-
338
- async setupBeforeProdMiddleware() {
339
- const {
340
- conf,
341
- runner
342
- } = this;
343
- const preMiddleware = await runner.beforeProdServer(conf);
344
- preMiddleware.flat().forEach(mid => {
345
- this.addHandler(mid);
306
+ handleAPI(context) {
307
+ return __async(this, null, function* () {
308
+ const { req, res } = context;
309
+ if (!this.frameAPIHandler) {
310
+ throw new Error("can not found api handler");
311
+ }
312
+ yield this.frameAPIHandler(req, res);
346
313
  });
347
314
  }
348
-
349
- async handleAPI(context) {
350
- const {
351
- req,
352
- res
353
- } = context;
354
-
355
- if (!this.frameAPIHandler) {
356
- throw new Error('can not found api handler');
357
- }
358
-
359
- await this.frameAPIHandler(req, res);
315
+ handleWeb(context, route) {
316
+ return __async(this, null, function* () {
317
+ return this.routeRenderHandler({
318
+ ctx: context,
319
+ route,
320
+ runner: this.runner
321
+ });
322
+ });
360
323
  }
361
-
362
- async handleWeb(context, route) {
363
- return this.routeRenderHandler({
364
- ctx: context,
365
- route,
366
- runner: this.runner
324
+ proxy() {
325
+ return __async(this, null, function* () {
326
+ return null;
367
327
  });
368
328
  }
369
-
370
- async proxy() {
371
- return null;
372
- } // warmup ssr function
373
-
374
-
375
329
  warmupSSRBundle() {
376
- const {
377
- distDir
378
- } = this;
330
+ const { distDir } = this;
379
331
  const bundles = this.router.getBundles();
380
- bundles.forEach(bundle => {
381
- const filepath = _path.default.join(distDir, bundle); // if error, just throw and let process die
382
-
383
-
332
+ bundles.forEach((bundle) => {
333
+ const filepath = import_path.default.join(distDir, bundle);
384
334
  require(filepath);
385
335
  });
386
336
  }
387
-
388
337
  createContext(req, res, options = {}) {
389
- return (0, _context.createContext)(req, res, options);
338
+ return (0, import_context.createContext)(req, res, options);
390
339
  }
391
- /* —————————————————————— private function —————————————————————— */
392
- // handler route.json, include api / csr / ssr
393
-
394
-
395
- async routeHandler(context) {
396
- const {
397
- req,
398
- res
399
- } = context;
400
- await this.emitRouteHook('beforeMatch', {
401
- context
402
- }); // match routes in the route spec
403
-
404
- const matched = this.router.match(context.path);
405
-
406
- if (!matched) {
407
- this.render404(context);
408
- return;
409
- }
410
-
411
- if (res.headersSent) {
412
- return;
413
- }
414
-
415
- const routeAPI = (0, _route2.createRouteAPI)(matched, this.router, context.url);
416
- await this.emitRouteHook('afterMatch', {
417
- context,
418
- routeAPI
419
- });
420
-
421
- if (this.isSend(res)) {
422
- return;
423
- }
424
-
425
- const {
426
- current
427
- } = routeAPI;
428
- const route = current.generate(context.url);
429
- context.setParams(route.params);
430
- context.setServerData('router', {
431
- baseUrl: route.urlPath,
432
- params: route.params
433
- }); // route is api service
434
-
435
- if (route.isApi) {
436
- await this.handleAPI(context);
437
- return;
438
- }
439
-
440
- if (this.frameWebHandler) {
441
- await this.frameWebHandler(req, res);
442
- } // frameWebHandler has process request
443
-
444
-
445
- if (this.isSend(res)) {
446
- return;
447
- }
448
-
449
- if (route.responseHeaders) {
450
- Object.keys(route.responseHeaders).forEach(key => {
451
- const value = route.responseHeaders[key];
452
-
453
- if (value) {
454
- context.res.setHeader(key, value);
340
+ routeHandler(context) {
341
+ return __async(this, null, function* () {
342
+ const { res } = context;
343
+ const matched = this.router.match(context.path);
344
+ if (!matched) {
345
+ this.render404(context);
346
+ return;
347
+ }
348
+ let route = matched.generate(context.url);
349
+ if (route.isApi) {
350
+ yield this.handleAPI(context);
351
+ return;
352
+ }
353
+ const afterMatchContext = (0, import_hook_api.createAfterMatchContext)(context, route.entryName);
354
+ if (this.runMode === import_constants.RUN_MODE.FULL) {
355
+ yield this.runner.afterMatch(afterMatchContext, { onLast: import_utils2.noop });
356
+ }
357
+ if (this.isSend(res)) {
358
+ return;
359
+ }
360
+ const { current, url, status } = afterMatchContext.router;
361
+ if (url) {
362
+ this.redirect(res, url, status);
363
+ return;
364
+ }
365
+ if (route.entryName !== current) {
366
+ const matched2 = this.router.matchEntry(current);
367
+ if (!matched2) {
368
+ this.render404(context);
369
+ return;
455
370
  }
371
+ route = matched2.generate(context.url);
372
+ }
373
+ context.setParams(route.params);
374
+ context.setServerData("router", {
375
+ baseUrl: route.urlPath,
376
+ params: route.params
456
377
  });
457
- }
458
-
459
- if (route.entryName) {
460
- await this.emitRouteHook('beforeRender', {
461
- context
462
- });
463
- }
464
-
465
- const file = await this.handleWeb(context, route);
466
-
467
- if (!file) {
468
- this.render404(context);
469
- return;
470
- }
471
-
472
- if (file.redirect) {
473
- res.statusCode = file.statusCode;
474
- res.setHeader('Location', file.content);
475
- res.end();
476
- return;
477
- }
478
-
479
- if (this.isSend(res)) {
480
- return;
481
- }
482
-
483
- let response = file.content;
484
-
485
- if (route.entryName) {
486
- const templateAPI = (0, _template.createTemplateAPI)(file.content.toString());
487
- await this.emitRouteHook('afterRender', {
488
- context,
489
- templateAPI
490
- });
491
-
378
+ if (this.frameWebHandler) {
379
+ res.locals = res.locals || {};
380
+ const middlewareContext = (0, import_hook_api.createMiddlewareContext)(context);
381
+ yield this.frameWebHandler(middlewareContext);
382
+ res.locals = __spreadValues(__spreadValues({}, res.locals), middlewareContext.response.locals);
383
+ }
492
384
  if (this.isSend(res)) {
493
385
  return;
494
386
  }
495
-
496
- await this.injectMicroFE(context, templateAPI); // It will inject _SERVER_DATA twice, when SSG mode.
497
- // The first time was in ssg html created, the seoncd time was in prod-server start.
498
- // but the second wound causes route error.
499
- // To ensure that the second injection fails, the _SERVER_DATA inject at the front of head,
500
-
501
- templateAPI.prependHead(`<script>window._SERVER_DATA=${JSON.stringify(context.serverData)}</script>`);
502
- response = templateAPI.get();
503
- }
504
-
505
- res.setHeader('content-type', file.contentType);
506
- res.end(response);
387
+ if (route.responseHeaders) {
388
+ Object.keys(route.responseHeaders).forEach((key) => {
389
+ const value = route.responseHeaders[key];
390
+ if (value) {
391
+ context.res.setHeader(key, value);
392
+ }
393
+ });
394
+ }
395
+ const renderResult = yield this.handleWeb(context, route);
396
+ if (!renderResult) {
397
+ this.render404(context);
398
+ return;
399
+ }
400
+ if (renderResult.redirect) {
401
+ this.redirect(
402
+ res,
403
+ renderResult.content,
404
+ renderResult.statusCode
405
+ );
406
+ return;
407
+ }
408
+ if (this.isSend(res)) {
409
+ return;
410
+ }
411
+ res.setHeader("content-type", renderResult.contentType);
412
+ const { contentStream } = renderResult;
413
+ if (contentStream) {
414
+ contentStream.pipe(
415
+ (0, import_template.templateInjectableStream)({
416
+ prependHead: route.entryName ? `<script>window._SERVER_DATA=${JSON.stringify(
417
+ context.serverData
418
+ )}<\/script>` : void 0
419
+ })
420
+ ).pipe(res);
421
+ return;
422
+ }
423
+ let response = renderResult.content;
424
+ if (route.entryName) {
425
+ const afterRenderContext = (0, import_hook_api.createAfterRenderContext)(
426
+ context,
427
+ response.toString()
428
+ );
429
+ if (this.runMode === import_constants.RUN_MODE.FULL) {
430
+ yield this.runner.afterRender(afterRenderContext, { onLast: import_utils2.noop });
431
+ }
432
+ if (this.isSend(res)) {
433
+ return;
434
+ }
435
+ afterRenderContext.template.prependHead(
436
+ `<script>window._SERVER_DATA=${JSON.stringify(
437
+ context.serverData
438
+ )}<\/script>`
439
+ );
440
+ response = afterRenderContext.template.get();
441
+ }
442
+ res.end(response);
443
+ });
507
444
  }
508
-
509
445
  isSend(res) {
510
446
  if (res.headersSent) {
511
447
  return true;
512
448
  }
513
-
514
- if (res.getHeader('Location') && (0, _utils2.isRedirect)(res.statusCode)) {
449
+ if (res.getHeader("Location") && (0, import_utils2.isRedirect)(res.statusCode)) {
515
450
  res.end();
516
451
  return true;
517
452
  }
518
-
519
453
  return false;
520
454
  }
521
-
522
- async injectMicroFE(context, templateAPI) {
523
- var _conf$runtime, _conf$server;
524
-
525
- const {
526
- conf
527
- } = this;
528
- const masterApp = (_conf$runtime = conf.runtime) === null || _conf$runtime === void 0 ? void 0 : _conf$runtime.masterApp; // no inject if not master App
529
-
530
- if (!masterApp) {
531
- return;
532
- }
533
-
534
- const manifest = masterApp.manifest || {};
535
- let modules = [];
536
- const {
537
- modules: configModules = []
538
- } = manifest; // while config modules is an string, fetch data from remote
539
-
540
- if (typeof configModules === 'string') {
541
- const moduleRequestUrl = configModules;
542
-
543
- try {
544
- const {
545
- data: remoteModules
546
- } = await _axios.default.get(moduleRequestUrl);
547
-
548
- if (Array.isArray(remoteModules)) {
549
- modules.push(...remoteModules);
550
- }
551
- } catch (e) {
552
- context.error(_constants.ERROR_DIGEST.EMICROINJ, e);
553
- }
554
- } else if (Array.isArray(configModules)) {
555
- modules.push(...configModules);
556
- }
557
-
558
- const {
559
- headers
560
- } = context.req;
561
- const debugName = headers['x-micro-frontend-module-name'] || context.query['__debug__micro-frontend-module-name'];
562
- const debugEntry = headers['x-micro-frontend-module-entry'] || context.query['__debug__micro-frontend-module-entry']; // add debug micro App to first
563
-
564
- if (debugName && debugEntry && (_conf$server = conf.server) !== null && _conf$server !== void 0 && _conf$server.enableMicroFrontendDebug) {
565
- modules = modules.map(m => {
566
- if (m.name === debugName) {
567
- return {
568
- name: debugName,
569
- entry: debugEntry
570
- };
571
- }
572
-
573
- return m;
574
- });
575
- }
576
-
577
- try {
578
- // Todo Safety xss
579
- const injection = JSON.stringify(_objectSpread(_objectSpread({}, manifest), {}, {
580
- modules
581
- }));
582
- templateAPI.appendHead(`<script>window.modern_manifest=${injection}</script>`);
583
- } catch (e) {
584
- context.error(_constants.ERROR_DIGEST.EMICROINJ, e);
585
- }
586
- } // compose handlers and create the final handler
587
-
588
-
589
455
  compose() {
590
- const {
591
- handlers
592
- } = this;
593
-
456
+ const { handlers } = this;
594
457
  if (!Array.isArray(handlers)) {
595
- throw new TypeError('Middleware stack must be an array!');
458
+ throw new TypeError("Middleware stack must be an array!");
596
459
  }
597
-
598
460
  for (const fn of handlers) {
599
- if (typeof fn !== 'function') {
600
- throw new TypeError('Middleware must be composed of functions!');
461
+ if (typeof fn !== "function") {
462
+ throw new TypeError("Middleware must be composed of functions!");
601
463
  }
602
464
  }
603
-
604
465
  this._handler = (context, next) => {
605
466
  let i = 0;
606
-
607
- const dispatch = error => {
467
+ const dispatch = (error) => {
608
468
  if (error) {
609
469
  return this.onError(context, error);
610
470
  }
611
-
612
471
  const handler = handlers[i++];
613
-
614
472
  if (!handler) {
615
473
  return next();
616
474
  }
617
-
618
- return handler(context, dispatch).catch(onError);
475
+ try {
476
+ const result = handler(context, dispatch);
477
+ if ((0, import_utils.isPromise)(result)) {
478
+ return result.catch(onError);
479
+ }
480
+ } catch (e) {
481
+ return onError(e);
482
+ }
619
483
  };
620
-
621
- const onError = err => {
484
+ const onError = (err) => {
622
485
  this.onError(context, err);
623
486
  };
624
-
625
487
  return dispatch();
626
488
  };
627
489
  }
628
-
629
- requestHandler(req, res, next = () => {// empty
490
+ requestHandler(req, res, next = () => {
630
491
  }) {
631
492
  res.statusCode = 200;
632
493
  req.logger = this.logger;
633
494
  req.metrics = this.metrics;
634
495
  let context;
635
-
636
496
  try {
637
497
  context = this.createContext(req, res);
638
498
  } catch (e) {
639
499
  this.logger.error(e);
640
500
  res.statusCode = 500;
641
- res.setHeader('content-type', _utils.mime.contentType('html'));
642
- return res.end((0, _utils2.createErrorDocument)(500, _constants.ERROR_PAGE_TEXT[500]));
501
+ res.setHeader("content-type", import_utils.mime.contentType("html"));
502
+ return res.end((0, import_utils2.createErrorDocument)(500, import_constants.ERROR_PAGE_TEXT[500]));
643
503
  }
644
-
645
504
  try {
646
505
  return this._handler(context, next);
647
506
  } catch (err) {
648
507
  return this.onError(context, err);
649
508
  }
650
509
  }
651
-
510
+ redirect(res, url, status = 302) {
511
+ res.setHeader("Location", url);
512
+ res.statusCode = status;
513
+ res.end();
514
+ }
652
515
  onError(context, err) {
653
- context.error(_constants.ERROR_DIGEST.EINTER, err);
516
+ context.error(import_constants.ERROR_DIGEST.EINTER, err);
654
517
  this.renderErrorPage(context, 500);
655
518
  }
656
-
657
- async renderErrorPage(context, status) {
658
- const {
659
- res
660
- } = context;
661
- context.status = status;
662
- res.setHeader('content-type', _utils.mime.contentType('html'));
663
- const statusPage = `/${status}`;
664
- const customErrorPage = `/_error`;
665
- const matched = this.router.match(statusPage) || this.router.match(customErrorPage); // if no custom status page find
666
-
667
- if (matched) {
668
- const route = matched.generate(context.url);
669
- const {
670
- entryName
671
- } = route; // check entryName, avoid matched '/' route
672
-
673
- if (entryName === status.toString() || entryName === '_error') {
674
- try {
675
- const file = await this.routeRenderHandler({
676
- route,
677
- ctx: context,
678
- runner: this.runner
679
- });
680
-
681
- if (file) {
682
- context.res.end(file.content);
683
- return;
519
+ renderErrorPage(context, status) {
520
+ return __async(this, null, function* () {
521
+ const { res } = context;
522
+ context.status = status;
523
+ res.setHeader("content-type", import_utils.mime.contentType("html"));
524
+ const statusPage = `/${status}`;
525
+ const customErrorPage = `/_error`;
526
+ const matched = this.router.match(statusPage) || this.router.match(customErrorPage);
527
+ if (matched) {
528
+ const route = matched.generate(context.url);
529
+ const { entryName } = route;
530
+ if (entryName === status.toString() || entryName === "_error") {
531
+ try {
532
+ const file = yield this.routeRenderHandler({
533
+ route,
534
+ ctx: context,
535
+ runner: this.runner
536
+ });
537
+ if (file) {
538
+ context.res.end(file.content);
539
+ return;
540
+ }
541
+ } catch (e) {
684
542
  }
685
- } catch (e) {// just catch error when the rendering error occurred in the custom error page.
686
543
  }
687
544
  }
688
- }
689
-
690
- const text = _constants.ERROR_PAGE_TEXT[status] || _constants.ERROR_PAGE_TEXT[500];
691
- context.res.end((0, _utils2.createErrorDocument)(status, text));
545
+ const text = import_constants.ERROR_PAGE_TEXT[status] || import_constants.ERROR_PAGE_TEXT[500];
546
+ context.res.end((0, import_utils2.createErrorDocument)(status, text));
547
+ });
692
548
  }
693
-
694
549
  }
695
- /* eslint-enable max-lines */
696
-
697
-
698
- exports.ModernServer = ModernServer;
550
+ // Annotate the CommonJS export names for ESM import in node:
551
+ 0 && (module.exports = {
552
+ ModernServer
553
+ });