@modern-js/prod-server 2.47.0 → 2.47.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 (169) hide show
  1. package/README.md +20 -16
  2. package/dist/cjs/{libs/hook-api/route.js → error.js} +16 -25
  3. package/dist/cjs/index.js +46 -24
  4. package/dist/esm/error.js +15 -0
  5. package/dist/esm/index.js +105 -19
  6. package/dist/esm-node/error.js +14 -0
  7. package/dist/esm-node/index.js +44 -17
  8. package/dist/types/error.d.ts +6 -0
  9. package/dist/types/index.d.ts +21 -11
  10. package/package.json +18 -92
  11. package/dist/cjs/constants.js +0 -72
  12. package/dist/cjs/libs/context/context.js +0 -240
  13. package/dist/cjs/libs/context/index.js +0 -31
  14. package/dist/cjs/libs/hook-api/afterRenderForStream.js +0 -34
  15. package/dist/cjs/libs/hook-api/base.js +0 -107
  16. package/dist/cjs/libs/hook-api/index.js +0 -85
  17. package/dist/cjs/libs/hook-api/index.worker.js +0 -119
  18. package/dist/cjs/libs/hook-api/template.js +0 -74
  19. package/dist/cjs/libs/hook-api/templateForStream.js +0 -52
  20. package/dist/cjs/libs/loadConfig.js +0 -70
  21. package/dist/cjs/libs/metrics.js +0 -33
  22. package/dist/cjs/libs/preload/flushServerHeader.js +0 -49
  23. package/dist/cjs/libs/preload/index.js +0 -24
  24. package/dist/cjs/libs/preload/parseLinks.js +0 -124
  25. package/dist/cjs/libs/preload/shouldFlushServerHeader.js +0 -52
  26. package/dist/cjs/libs/preload/transformLinks2String.js +0 -150
  27. package/dist/cjs/libs/proxy.js +0 -99
  28. package/dist/cjs/libs/render/index.js +0 -109
  29. package/dist/cjs/libs/render/measure.js +0 -74
  30. package/dist/cjs/libs/render/ssr.js +0 -126
  31. package/dist/cjs/libs/render/ssrCache/cacheMod.js +0 -56
  32. package/dist/cjs/libs/render/ssrCache/index.js +0 -83
  33. package/dist/cjs/libs/render/ssrCache/manager.js +0 -106
  34. package/dist/cjs/libs/render/static.js +0 -72
  35. package/dist/cjs/libs/render/type.js +0 -33
  36. package/dist/cjs/libs/render/utils.js +0 -41
  37. package/dist/cjs/libs/reporter.js +0 -39
  38. package/dist/cjs/libs/route/index.js +0 -85
  39. package/dist/cjs/libs/route/matcher.js +0 -117
  40. package/dist/cjs/libs/route/route.js +0 -49
  41. package/dist/cjs/libs/serveFile.js +0 -84
  42. package/dist/cjs/libs/serverTiming.js +0 -44
  43. package/dist/cjs/renderHtml.js +0 -72
  44. package/dist/cjs/server/index.js +0 -229
  45. package/dist/cjs/server/modernServer.js +0 -532
  46. package/dist/cjs/server/modernServerSplit.js +0 -67
  47. package/dist/cjs/type.js +0 -16
  48. package/dist/cjs/utils.js +0 -164
  49. package/dist/cjs/workerServer.js +0 -264
  50. package/dist/esm/constants.js +0 -43
  51. package/dist/esm/libs/context/context.js +0 -292
  52. package/dist/esm/libs/context/index.js +0 -8
  53. package/dist/esm/libs/hook-api/afterRenderForStream.js +0 -33
  54. package/dist/esm/libs/hook-api/base.js +0 -108
  55. package/dist/esm/libs/hook-api/index.js +0 -55
  56. package/dist/esm/libs/hook-api/index.worker.js +0 -113
  57. package/dist/esm/libs/hook-api/route.js +0 -41
  58. package/dist/esm/libs/hook-api/template.js +0 -84
  59. package/dist/esm/libs/hook-api/templateForStream.js +0 -35
  60. package/dist/esm/libs/loadConfig.js +0 -36
  61. package/dist/esm/libs/metrics.js +0 -9
  62. package/dist/esm/libs/preload/flushServerHeader.js +0 -50
  63. package/dist/esm/libs/preload/index.js +0 -2
  64. package/dist/esm/libs/preload/parseLinks.js +0 -172
  65. package/dist/esm/libs/preload/shouldFlushServerHeader.js +0 -27
  66. package/dist/esm/libs/preload/transformLinks2String.js +0 -140
  67. package/dist/esm/libs/proxy.js +0 -160
  68. package/dist/esm/libs/render/index.js +0 -175
  69. package/dist/esm/libs/render/measure.js +0 -69
  70. package/dist/esm/libs/render/ssr.js +0 -129
  71. package/dist/esm/libs/render/ssrCache/cacheMod.js +0 -33
  72. package/dist/esm/libs/render/ssrCache/index.js +0 -151
  73. package/dist/esm/libs/render/ssrCache/manager.js +0 -170
  74. package/dist/esm/libs/render/static.js +0 -100
  75. package/dist/esm/libs/render/type.js +0 -9
  76. package/dist/esm/libs/render/utils.js +0 -16
  77. package/dist/esm/libs/reporter.js +0 -15
  78. package/dist/esm/libs/route/index.js +0 -116
  79. package/dist/esm/libs/route/matcher.js +0 -128
  80. package/dist/esm/libs/route/route.js +0 -26
  81. package/dist/esm/libs/serveFile.js +0 -68
  82. package/dist/esm/libs/serverTiming.js +0 -30
  83. package/dist/esm/renderHtml.js +0 -150
  84. package/dist/esm/server/index.js +0 -426
  85. package/dist/esm/server/modernServer.js +0 -1018
  86. package/dist/esm/server/modernServerSplit.js +0 -138
  87. package/dist/esm/type.js +0 -0
  88. package/dist/esm/utils.js +0 -103
  89. package/dist/esm/workerServer.js +0 -347
  90. package/dist/esm-node/constants.js +0 -43
  91. package/dist/esm-node/libs/context/context.js +0 -206
  92. package/dist/esm-node/libs/context/index.js +0 -6
  93. package/dist/esm-node/libs/hook-api/afterRenderForStream.js +0 -10
  94. package/dist/esm-node/libs/hook-api/base.js +0 -72
  95. package/dist/esm-node/libs/hook-api/index.js +0 -57
  96. package/dist/esm-node/libs/hook-api/index.worker.js +0 -92
  97. package/dist/esm-node/libs/hook-api/route.js +0 -24
  98. package/dist/esm-node/libs/hook-api/template.js +0 -49
  99. package/dist/esm-node/libs/hook-api/templateForStream.js +0 -28
  100. package/dist/esm-node/libs/loadConfig.js +0 -34
  101. package/dist/esm-node/libs/metrics.js +0 -9
  102. package/dist/esm-node/libs/preload/flushServerHeader.js +0 -25
  103. package/dist/esm-node/libs/preload/index.js +0 -2
  104. package/dist/esm-node/libs/preload/parseLinks.js +0 -90
  105. package/dist/esm-node/libs/preload/shouldFlushServerHeader.js +0 -27
  106. package/dist/esm-node/libs/preload/transformLinks2String.js +0 -126
  107. package/dist/esm-node/libs/proxy.js +0 -74
  108. package/dist/esm-node/libs/render/index.js +0 -75
  109. package/dist/esm-node/libs/render/measure.js +0 -49
  110. package/dist/esm-node/libs/render/ssr.js +0 -92
  111. package/dist/esm-node/libs/render/ssrCache/cacheMod.js +0 -22
  112. package/dist/esm-node/libs/render/ssrCache/index.js +0 -59
  113. package/dist/esm-node/libs/render/ssrCache/manager.js +0 -82
  114. package/dist/esm-node/libs/render/static.js +0 -38
  115. package/dist/esm-node/libs/render/type.js +0 -9
  116. package/dist/esm-node/libs/render/utils.js +0 -16
  117. package/dist/esm-node/libs/reporter.js +0 -15
  118. package/dist/esm-node/libs/route/index.js +0 -60
  119. package/dist/esm-node/libs/route/matcher.js +0 -93
  120. package/dist/esm-node/libs/route/route.js +0 -25
  121. package/dist/esm-node/libs/serveFile.js +0 -49
  122. package/dist/esm-node/libs/serverTiming.js +0 -20
  123. package/dist/esm-node/renderHtml.js +0 -80
  124. package/dist/esm-node/server/index.js +0 -195
  125. package/dist/esm-node/server/modernServer.js +0 -498
  126. package/dist/esm-node/server/modernServerSplit.js +0 -43
  127. package/dist/esm-node/type.js +0 -0
  128. package/dist/esm-node/utils.js +0 -132
  129. package/dist/esm-node/workerServer.js +0 -239
  130. package/dist/types/constants.d.ts +0 -30
  131. package/dist/types/libs/context/context.d.ts +0 -62
  132. package/dist/types/libs/context/index.d.ts +0 -7
  133. package/dist/types/libs/hook-api/afterRenderForStream.d.ts +0 -4
  134. package/dist/types/libs/hook-api/base.d.ts +0 -53
  135. package/dist/types/libs/hook-api/index.d.ts +0 -6
  136. package/dist/types/libs/hook-api/index.worker.d.ts +0 -19
  137. package/dist/types/libs/hook-api/route.d.ts +0 -9
  138. package/dist/types/libs/hook-api/template.d.ts +0 -22
  139. package/dist/types/libs/hook-api/templateForStream.d.ts +0 -8
  140. package/dist/types/libs/loadConfig.d.ts +0 -13
  141. package/dist/types/libs/metrics.d.ts +0 -3
  142. package/dist/types/libs/preload/flushServerHeader.d.ts +0 -14
  143. package/dist/types/libs/preload/index.d.ts +0 -2
  144. package/dist/types/libs/preload/parseLinks.d.ts +0 -13
  145. package/dist/types/libs/preload/shouldFlushServerHeader.d.ts +0 -3
  146. package/dist/types/libs/preload/transformLinks2String.d.ts +0 -3
  147. package/dist/types/libs/proxy.d.ts +0 -13
  148. package/dist/types/libs/render/index.d.ts +0 -21
  149. package/dist/types/libs/render/measure.d.ts +0 -10
  150. package/dist/types/libs/render/ssr.d.ts +0 -12
  151. package/dist/types/libs/render/ssrCache/cacheMod.d.ts +0 -8
  152. package/dist/types/libs/render/ssrCache/index.d.ts +0 -7
  153. package/dist/types/libs/render/ssrCache/manager.d.ts +0 -14
  154. package/dist/types/libs/render/static.d.ts +0 -3
  155. package/dist/types/libs/render/type.d.ts +0 -36
  156. package/dist/types/libs/render/utils.d.ts +0 -5
  157. package/dist/types/libs/reporter.d.ts +0 -2
  158. package/dist/types/libs/route/index.d.ts +0 -15
  159. package/dist/types/libs/route/matcher.d.ts +0 -15
  160. package/dist/types/libs/route/route.d.ts +0 -14
  161. package/dist/types/libs/serveFile.d.ts +0 -9
  162. package/dist/types/libs/serverTiming.d.ts +0 -13
  163. package/dist/types/renderHtml.d.ts +0 -23
  164. package/dist/types/server/index.d.ts +0 -55
  165. package/dist/types/server/modernServer.d.ts +0 -71
  166. package/dist/types/server/modernServerSplit.d.ts +0 -2
  167. package/dist/types/type.d.ts +0 -77
  168. package/dist/types/utils.d.ts +0 -24
  169. package/dist/types/workerServer.d.ts +0 -59
@@ -1,498 +0,0 @@
1
- import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
- import { createServer } from "http";
3
- import path from "path";
4
- import { fs, isProd, isPromise, isWebOnly, mime, ROUTE_SPEC_FILE } from "@modern-js/utils";
5
- import { time } from "@modern-js/runtime-utils/time";
6
- import { RouteMatchManager } from "../libs/route";
7
- import { createRenderHandler } from "../libs/render";
8
- import { createStaticFileHandler, faviconFallbackHandler } from "../libs/serveFile";
9
- import { createErrorDocument, createMiddlewareCollecter, getStaticReg, mergeExtension, noop, debug, isRedirect } from "../utils";
10
- import { createProxyHandler } from "../libs/proxy";
11
- import { createContext } from "../libs/context";
12
- import { AGGRED_DIR, ERROR_DIGEST, ERROR_PAGE_TEXT, RUN_MODE, ServerReportTimings } from "../constants";
13
- import { createAfterMatchContext, createAfterRenderContext, createMiddlewareContext } from "../libs/hook-api";
14
- import { cacheMod } from "../libs/render/ssrCache/cacheMod";
15
- const SERVER_DIR = "./server";
16
- class ModernServer {
17
- // server prepare
18
- async onInit(runner, app) {
19
- var _conf_bff, _this_conf_output;
20
- this.runner = runner;
21
- const { distDir, conf } = this;
22
- debug("final server conf", this.conf);
23
- if ((_conf_bff = conf.bff) === null || _conf_bff === void 0 ? void 0 : _conf_bff.proxy) {
24
- const { handlers, handleUpgrade } = createProxyHandler(conf.bff.proxy);
25
- app && handleUpgrade(app);
26
- handlers.forEach((handler) => {
27
- this.addHandler(handler);
28
- });
29
- }
30
- const usageRoutes = this.filterRoutes(this.getRoutes());
31
- this.router.reset(usageRoutes);
32
- this.warmupSSRBundle();
33
- cacheMod.loadServerCacheMod(isProd() ? distDir : this.pwd);
34
- await this.prepareFrameHandler();
35
- await this.prepareLoaderHandler(usageRoutes, distDir);
36
- this.routeRenderHandler = this.getRenderHandler();
37
- await this.setupBeforeProdMiddleware();
38
- this.addHandler(this.setupStaticMiddleware((_this_conf_output = this.conf.output) === null || _this_conf_output === void 0 ? void 0 : _this_conf_output.assetPrefix));
39
- this.addHandler(faviconFallbackHandler);
40
- this.addHandler(this.routeHandler.bind(this));
41
- this.compose();
42
- }
43
- getRenderHandler() {
44
- var _this_conf_server, _conf_security;
45
- const { distDir, staticGenerate, conf, metaName } = this;
46
- const ssrConfig = (_this_conf_server = this.conf.server) === null || _this_conf_server === void 0 ? void 0 : _this_conf_server.ssr;
47
- const forceCSR = typeof ssrConfig === "object" ? ssrConfig.forceCSR : false;
48
- return createRenderHandler({
49
- distDir,
50
- staticGenerate,
51
- forceCSR,
52
- conf: this.conf,
53
- nonce: (_conf_security = conf.security) === null || _conf_security === void 0 ? void 0 : _conf_security.nonce,
54
- metaName
55
- });
56
- }
57
- // server ready
58
- onRepack(_) {
59
- }
60
- // exposed requestHandler
61
- getRequestHandler() {
62
- return this.requestHandler.bind(this);
63
- }
64
- async render(req, res, url) {
65
- req.logger = req.logger || this.logger;
66
- req.metrics = req.metrics || this.metrics;
67
- const context = createContext(req, res, {
68
- metaName: this.metaName
69
- });
70
- const matched = this.router.match(url || context.path);
71
- if (!matched) {
72
- return null;
73
- }
74
- res.statusCode = 200;
75
- const route = matched.generate(context.url);
76
- const result = await this.handleWeb(context, route);
77
- if (!result) {
78
- return null;
79
- }
80
- if (result.contentStream) {
81
- return result.contentStream;
82
- }
83
- return result.content.toString();
84
- }
85
- async createHTTPServer(handler) {
86
- return createServer(handler);
87
- }
88
- /* —————————————————————— function will be overwrite —————————————————————— */
89
- async onServerChange({ filepath }) {
90
- const { pwd } = this;
91
- const { api, server } = AGGRED_DIR;
92
- const apiPath = path.normalize(path.join(pwd, api));
93
- const serverPath = path.normalize(path.join(pwd, server));
94
- const onlyApi = filepath.startsWith(apiPath);
95
- const onlyWeb = filepath.startsWith(serverPath);
96
- await this.prepareFrameHandler({
97
- onlyWeb,
98
- onlyApi
99
- });
100
- }
101
- // get routes info
102
- getRoutes() {
103
- if (this.presetRoutes) {
104
- return this.presetRoutes;
105
- }
106
- const file = path.join(this.distDir, ROUTE_SPEC_FILE);
107
- if (fs.existsSync(file)) {
108
- const content = fs.readJSONSync(file);
109
- return content.routes;
110
- }
111
- return [];
112
- }
113
- // add promisify request handler to server
114
- // handler should do not do more things after invoke next
115
- addHandler(handler) {
116
- this.handlers.push(handler);
117
- }
118
- // return 404 page
119
- render404(context) {
120
- context.error(ERROR_DIGEST.ENOTF, "404 Not Found");
121
- this.renderErrorPage(context, 404);
122
- }
123
- async prepareLoaderHandler(specs, distDir) {
124
- const { runner } = this;
125
- const handler = await runner.prepareLoaderHandler({
126
- serverRoutes: specs,
127
- distDir
128
- }, {
129
- onLast: () => null
130
- });
131
- this.loaderHandler = handler;
132
- }
133
- // gather frame extension and get framework handler
134
- async prepareFrameHandler(options) {
135
- const { workDir, runner } = this;
136
- const { onlyApi, onlyWeb } = options || {};
137
- const { getMiddlewares, ...collector } = createMiddlewareCollecter();
138
- await runner.gather(collector);
139
- const { api: pluginAPIExt, web: pluginWebExt } = getMiddlewares();
140
- const serverDir = path.join(workDir, SERVER_DIR);
141
- if (await fs.pathExists(path.join(serverDir)) && !onlyApi) {
142
- const webExtension = mergeExtension(pluginWebExt);
143
- this.frameWebHandler = await this.prepareWebHandler(webExtension);
144
- }
145
- if (!onlyWeb) {
146
- const apiExtension = mergeExtension(pluginAPIExt);
147
- this.frameAPIHandler = await this.prepareAPIHandler(apiExtension);
148
- }
149
- }
150
- async prepareWebHandler(extension) {
151
- const { workDir, runner } = this;
152
- const handler = await runner.prepareWebServer({
153
- pwd: workDir,
154
- config: extension
155
- }, {
156
- onLast: () => null
157
- });
158
- return handler;
159
- }
160
- async prepareAPIHandler(extension) {
161
- const { workDir, runner, conf } = this;
162
- const { bff } = conf;
163
- const prefix = (bff === null || bff === void 0 ? void 0 : bff.prefix) || "/api";
164
- const webOnly = await isWebOnly();
165
- if (webOnly && process.env.NODE_ENV === "development") {
166
- return (req, res) => {
167
- res.setHeader("Content-Type", "text/plain");
168
- res.end(JSON.stringify(""));
169
- };
170
- }
171
- return runner.prepareApiServer({
172
- pwd: workDir,
173
- config: extension,
174
- prefix: Array.isArray(prefix) ? prefix[0] : prefix,
175
- httpMethodDecider: bff === null || bff === void 0 ? void 0 : bff.httpMethodDecider,
176
- render: this.render.bind(this)
177
- }, {
178
- onLast: () => null
179
- });
180
- }
181
- filterRoutes(routes) {
182
- return routes;
183
- }
184
- async setupBeforeProdMiddleware() {
185
- const { conf, runner } = this;
186
- const preMiddleware = await runner.beforeProdServer(conf);
187
- preMiddleware.flat().forEach((mid) => {
188
- this.addHandler(mid);
189
- });
190
- }
191
- setupStaticMiddleware(prefix) {
192
- const staticPathRegExp = getStaticReg(this.conf.output, this.conf.html, prefix);
193
- return createStaticFileHandler([
194
- {
195
- path: staticPathRegExp,
196
- target: this.distDir
197
- }
198
- ], prefix);
199
- }
200
- async handleAPI(context) {
201
- const { req, res } = context;
202
- if (!this.frameAPIHandler) {
203
- throw new Error("can not found api handler");
204
- }
205
- await this.frameAPIHandler(req, res);
206
- }
207
- async handleWeb(context, route) {
208
- const { res } = context;
209
- if (this.loaderHandler) {
210
- await this.loaderHandler(context);
211
- if (this.isSend(res)) {
212
- return null;
213
- }
214
- }
215
- context.setParams(route.params);
216
- context.setServerData("router", {
217
- baseUrl: route.urlPath,
218
- params: route.params
219
- });
220
- if (route.responseHeaders) {
221
- Object.keys(route.responseHeaders).forEach((key) => {
222
- const value = route.responseHeaders[key];
223
- if (value) {
224
- context.res.setHeader(key, value);
225
- }
226
- });
227
- }
228
- const renderResult = await this.routeRenderHandler({
229
- ctx: context,
230
- route,
231
- runner: this.runner
232
- });
233
- if (!renderResult) {
234
- this.render404(context);
235
- return null;
236
- }
237
- if (renderResult.redirect) {
238
- this.redirect(res, renderResult.content, renderResult.statusCode);
239
- return null;
240
- }
241
- if (this.isSend(res)) {
242
- return null;
243
- }
244
- res.set("content-type", renderResult.contentType);
245
- return renderResult;
246
- }
247
- async proxy() {
248
- return null;
249
- }
250
- // warmup ssr function
251
- warmupSSRBundle() {
252
- const { distDir } = this;
253
- const bundles = this.router.getBundles();
254
- bundles.forEach((bundle) => {
255
- const filepath = path.join(distDir, bundle);
256
- if (fs.existsSync(filepath)) {
257
- require(filepath);
258
- }
259
- });
260
- }
261
- createContext(req, res, options = {}) {
262
- return createContext(req, res, options);
263
- }
264
- /* —————————————————————— private function —————————————————————— */
265
- // handler route.json, include api / csr / ssr
266
- async routeHandler(context) {
267
- const { res, reporter } = context;
268
- const matched = this.router.match(context.path);
269
- if (!matched) {
270
- this.render404(context);
271
- return;
272
- }
273
- await reporter.init({
274
- match: matched
275
- });
276
- const end = time();
277
- res.on("finish", () => {
278
- const cost = end();
279
- reporter.reportTiming(ServerReportTimings.SERVER_HANDLE_REQUEST, cost);
280
- });
281
- let route = matched.generate(context.url);
282
- if (route.isApi) {
283
- await this.handleAPI(context);
284
- return;
285
- }
286
- if (route.entryName && this.runMode === RUN_MODE.FULL) {
287
- const afterMatchContext = createAfterMatchContext(context, route.entryName);
288
- const end2 = time();
289
- await this.runner.afterMatch(afterMatchContext, {
290
- onLast: noop
291
- });
292
- const cost = end2();
293
- cost && reporter.reportTiming(ServerReportTimings.SERVER_HOOK_AFTER_MATCH, cost);
294
- if (this.isSend(res)) {
295
- return;
296
- }
297
- const { current, url, status } = afterMatchContext.router;
298
- if (url) {
299
- this.redirect(res, url, status);
300
- return;
301
- }
302
- if (route.entryName !== current) {
303
- const matched2 = this.router.matchEntry(current);
304
- if (!matched2) {
305
- this.render404(context);
306
- return;
307
- }
308
- route = matched2.generate(context.url);
309
- }
310
- }
311
- if (this.frameWebHandler) {
312
- res.locals = res.locals || {};
313
- const middlewareContext = createMiddlewareContext(context);
314
- const end2 = time();
315
- await this.frameWebHandler(middlewareContext);
316
- const cost = end2();
317
- cost && reporter.reportTiming(ServerReportTimings.SERVER_MIDDLEWARE, cost);
318
- res.locals = {
319
- ...res.locals,
320
- ...middlewareContext.response.locals
321
- };
322
- if (this.isSend(res)) {
323
- return;
324
- }
325
- }
326
- const renderResult = await this.handleWeb(context, route);
327
- if (!renderResult) {
328
- return;
329
- }
330
- const { contentStream: responseStream } = renderResult;
331
- let { content: response } = renderResult;
332
- if (route.entryName && responseStream) {
333
- responseStream.pipe(res);
334
- return;
335
- }
336
- if (route.entryName && this.runMode === RUN_MODE.FULL) {
337
- const afterRenderContext = createAfterRenderContext(context, route, response.toString());
338
- const end2 = time();
339
- await this.runner.afterRender(afterRenderContext, {
340
- onLast: noop
341
- });
342
- const cost = end2();
343
- cost && reporter.reportTiming(ServerReportTimings.SERVER_HOOK_AFTER_RENDER, cost);
344
- if (this.isSend(res)) {
345
- return;
346
- }
347
- response = afterRenderContext.template.get();
348
- }
349
- res.end(response);
350
- }
351
- isSend(res) {
352
- if (res.modernFlushedHeaders) {
353
- if (res.writableFinished) {
354
- return true;
355
- }
356
- } else if (res.headersSent) {
357
- return true;
358
- }
359
- if (res.getHeader("Location") && isRedirect(res.statusCode)) {
360
- res.end();
361
- return true;
362
- }
363
- return false;
364
- }
365
- // compose handlers and create the final handler
366
- compose() {
367
- const { handlers } = this;
368
- if (!Array.isArray(handlers)) {
369
- throw new TypeError("Middleware stack must be an array!");
370
- }
371
- for (const fn of handlers) {
372
- if (typeof fn !== "function") {
373
- throw new TypeError("Middleware must be composed of functions!");
374
- }
375
- }
376
- this._handler = (context, next) => {
377
- let i = 0;
378
- const dispatch = (error) => {
379
- if (error) {
380
- return this.onError(context, error);
381
- }
382
- const handler = handlers[i++];
383
- if (!handler) {
384
- return next();
385
- }
386
- try {
387
- const result = handler(context, dispatch);
388
- if (isPromise(result)) {
389
- return result.catch(onError);
390
- }
391
- } catch (e) {
392
- return onError(e);
393
- }
394
- };
395
- const onError = (err) => {
396
- this.onError(context, err);
397
- };
398
- return dispatch();
399
- };
400
- }
401
- requestHandler(req, res, next = () => {
402
- }) {
403
- res.statusCode = 200;
404
- req.logger = req.logger || this.logger;
405
- req.metrics = req.metrics || this.metrics;
406
- let context;
407
- try {
408
- context = this.createContext(req, res, {
409
- metaName: this.metaName
410
- });
411
- } catch (e) {
412
- this.logger.error(e);
413
- res.statusCode = 500;
414
- res.setHeader("content-type", mime.contentType("html"));
415
- return res.end(createErrorDocument(500, ERROR_PAGE_TEXT[500]));
416
- }
417
- try {
418
- return this._handler(context, next);
419
- } catch (err) {
420
- return this.onError(context, err);
421
- }
422
- }
423
- redirect(res, url, status = 302) {
424
- res.set("Location", url);
425
- res.statusCode = status;
426
- res.end();
427
- }
428
- onError(context, err) {
429
- context.error(ERROR_DIGEST.EINTER, err);
430
- this.renderErrorPage(context, 500);
431
- }
432
- async renderErrorPage(context, status) {
433
- const { res } = context;
434
- context.status = status;
435
- res.set("content-type", mime.contentType("html"));
436
- const statusPage = `/${status}`;
437
- const customErrorPage = `/_error`;
438
- const matched = this.router.match(statusPage) || this.router.match(customErrorPage);
439
- if (matched) {
440
- const route = matched.generate(context.url);
441
- const { entryName } = route;
442
- if (entryName === status.toString() || entryName === "_error") {
443
- try {
444
- const file = await this.routeRenderHandler({
445
- route,
446
- ctx: context,
447
- runner: this.runner
448
- });
449
- if (file) {
450
- context.res.end(file.content);
451
- return;
452
- }
453
- } catch (e) {
454
- }
455
- }
456
- }
457
- const text = ERROR_PAGE_TEXT[status] || ERROR_PAGE_TEXT[500];
458
- context.res.end(createErrorDocument(status, text));
459
- }
460
- constructor({ pwd, config, routes, staticGenerate, logger, metrics, runMode, proxyTarget, appContext }) {
461
- _define_property(this, "pwd", void 0);
462
- _define_property(this, "distDir", void 0);
463
- _define_property(this, "workDir", void 0);
464
- _define_property(this, "router", void 0);
465
- _define_property(this, "conf", void 0);
466
- _define_property(this, "handlers", []);
467
- _define_property(this, "presetRoutes", void 0);
468
- _define_property(this, "runner", void 0);
469
- _define_property(this, "logger", void 0);
470
- _define_property(this, "metrics", void 0);
471
- _define_property(this, "runMode", void 0);
472
- _define_property(this, "proxyTarget", void 0);
473
- _define_property(this, "routeRenderHandler", void 0);
474
- _define_property(this, "staticGenerate", void 0);
475
- _define_property(this, "metaName", void 0);
476
- _define_property(this, "loaderHandler", null);
477
- _define_property(this, "frameWebHandler", null);
478
- _define_property(this, "frameAPIHandler", null);
479
- _define_property(this, "_handler", void 0);
480
- require("ignore-styles");
481
- this.pwd = pwd;
482
- this.distDir = path.resolve(pwd, config.output.path || "dist");
483
- this.workDir = this.distDir;
484
- this.conf = config;
485
- debug("server conf", this.conf);
486
- this.logger = logger;
487
- this.metrics = metrics;
488
- this.router = new RouteMatchManager();
489
- this.presetRoutes = routes;
490
- this.proxyTarget = proxyTarget;
491
- this.staticGenerate = staticGenerate || false;
492
- this.runMode = runMode || RUN_MODE.FULL;
493
- this.metaName = appContext === null || appContext === void 0 ? void 0 : appContext.metaName;
494
- }
495
- }
496
- export {
497
- ModernServer
498
- };
@@ -1,43 +0,0 @@
1
- import { ModernServer } from "./modernServer";
2
- class ModernSSRServer extends ModernServer {
3
- prepareAPIHandler(_) {
4
- return null;
5
- }
6
- async handleAPI(context) {
7
- return this.render404(context);
8
- }
9
- }
10
- class ModernAPIServer extends ModernServer {
11
- prepareWebHandler(_) {
12
- return null;
13
- }
14
- filterRoutes(routes) {
15
- return routes.filter((route) => route.isApi);
16
- }
17
- }
18
- class ModernWebServer extends ModernServer {
19
- async warmupSSRBundle() {
20
- return null;
21
- }
22
- async handleAPI(context) {
23
- return this.render404(context);
24
- }
25
- async handleWeb(context, route) {
26
- route.isSSR = false;
27
- return super.handleWeb(context, route);
28
- }
29
- }
30
- const createProdServer = (options) => {
31
- if (options.apiOnly) {
32
- return new ModernAPIServer(options);
33
- } else if (options.ssrOnly) {
34
- return new ModernSSRServer(options);
35
- } else if (options.webOnly) {
36
- return new ModernWebServer(options);
37
- } else {
38
- return new ModernServer(options);
39
- }
40
- };
41
- export {
42
- createProdServer
43
- };
File without changes
@@ -1,132 +0,0 @@
1
- import { createDebugger } from "@modern-js/utils";
2
- const debug = createDebugger("prod-server");
3
- const mergeExtension = (users) => {
4
- const output = [];
5
- return {
6
- middleware: output.concat(users)
7
- };
8
- };
9
- const noop = () => {
10
- };
11
- const createErrorDocument = (status, text) => {
12
- const title = `${status}: ${text}`;
13
- return `<!DOCTYPE html>
14
- <html lang="en">
15
- <head>
16
- <meta charset="utf-8">
17
- <meta name="viewport" content="width=device-width">
18
- <title>${title}</title>
19
- <style>
20
- html,body {
21
- margin: 0;
22
- }
23
-
24
- .page-container {
25
- color: #000;
26
- background: #fff;
27
- height: 100vh;
28
- text-align: center;
29
- display: flex;
30
- flex-direction: column;
31
- align-items: center;
32
- justify-content: center;
33
- }
34
- </style>
35
- </head>
36
- <body>
37
- <div class="page-container">
38
- <h1>${status}</h1>
39
- <div>${text}</div>
40
- </body>
41
- </html>
42
- `;
43
- };
44
- const createMiddlewareCollecter = () => {
45
- const webMiddlewares = [];
46
- const apiMiddlewares = [];
47
- const addWebMiddleware = (input) => {
48
- webMiddlewares.push(input);
49
- };
50
- const addAPIMiddleware = (input) => {
51
- apiMiddlewares.push(input);
52
- };
53
- const getMiddlewares = () => ({
54
- web: webMiddlewares,
55
- api: apiMiddlewares
56
- });
57
- return {
58
- getMiddlewares,
59
- addWebMiddleware,
60
- addAPIMiddleware
61
- };
62
- };
63
- const getStaticReg = (output = {}, html = {}, prefix = "/") => {
64
- const { distPath: { css: cssPath, js: jsPath, media: mediaPath } = {} } = output;
65
- const { favicon, faviconByEntries } = html;
66
- const favicons = prepareFavicons(favicon, faviconByEntries);
67
- const staticFiles = [
68
- cssPath,
69
- jsPath,
70
- mediaPath
71
- ].filter((v) => Boolean(v));
72
- const staticReg = [
73
- "static/",
74
- "upload/",
75
- ...staticFiles
76
- ];
77
- const iconReg = [
78
- "favicon.ico",
79
- "icon.png",
80
- ...favicons
81
- ];
82
- const regPrefix = prefix.endsWith("/") ? prefix : `${prefix}/`;
83
- const staticPathRegExp = new RegExp(`^${regPrefix}(${[
84
- ...staticReg,
85
- ...iconReg
86
- ].join("|")})`);
87
- return staticPathRegExp;
88
- };
89
- const prepareFavicons = (favicon, faviconByEntries) => {
90
- const faviconNames = [];
91
- if (favicon) {
92
- faviconNames.push(favicon.substring(favicon.lastIndexOf("/") + 1));
93
- }
94
- if (faviconByEntries) {
95
- Object.keys(faviconByEntries).forEach((f) => {
96
- const curFavicon = faviconByEntries[f];
97
- if (curFavicon) {
98
- faviconNames.push(curFavicon.substring(curFavicon.lastIndexOf("/") + 1));
99
- }
100
- });
101
- }
102
- return faviconNames;
103
- };
104
- const headersWithoutCookie = (headers) => {
105
- if (typeof headers.cookie !== "undefined") {
106
- const safeHeaders = {
107
- ...headers
108
- };
109
- delete safeHeaders.cookie;
110
- return safeHeaders;
111
- }
112
- return headers;
113
- };
114
- const isRedirect = (code) => {
115
- return [
116
- 301,
117
- 302,
118
- 307,
119
- 308
120
- ].includes(code);
121
- };
122
- export {
123
- createErrorDocument,
124
- createMiddlewareCollecter,
125
- debug,
126
- getStaticReg,
127
- headersWithoutCookie,
128
- isRedirect,
129
- mergeExtension,
130
- noop,
131
- prepareFavicons
132
- };