@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,38 +0,0 @@
1
- import path from "path";
2
- import { mime } from "@modern-js/utils";
3
- import { fileReader } from "@modern-js/runtime-utils/fileReader";
4
- async function handleDirectory(ctx, entryPath, urlPath) {
5
- const { path: pathname } = ctx;
6
- const filepath = path.join(entryPath, trimLeft(pathname, urlPath));
7
- let content = await fileReader.readFile(filepath);
8
- let contentType = mime.contentType(path.extname(filepath) || "");
9
- if (!content) {
10
- if (pathname.endsWith("/")) {
11
- content = await fileReader.readFile(`${filepath}index.html`);
12
- } else if (!pathname.includes(".")) {
13
- content = await fileReader.readFile(`${filepath}.html`);
14
- if (!content) {
15
- content = await fileReader.readFile(`${filepath}/index.html`);
16
- }
17
- }
18
- if (content) {
19
- contentType = mime.contentType("html");
20
- }
21
- }
22
- if (!content) {
23
- return null;
24
- }
25
- return {
26
- content,
27
- contentType: contentType || ""
28
- };
29
- }
30
- const trimLeft = (str, prefix) => {
31
- if (str.startsWith(prefix)) {
32
- return str.substring(prefix.length);
33
- }
34
- return str;
35
- };
36
- export {
37
- handleDirectory
38
- };
@@ -1,9 +0,0 @@
1
- var RenderLevel;
2
- (function(RenderLevel2) {
3
- RenderLevel2[RenderLevel2["CLIENT_RENDER"] = 0] = "CLIENT_RENDER";
4
- RenderLevel2[RenderLevel2["SERVER_PREFETCH"] = 1] = "SERVER_PREFETCH";
5
- RenderLevel2[RenderLevel2["SERVER_RENDER"] = 2] = "SERVER_RENDER";
6
- })(RenderLevel || (RenderLevel = {}));
7
- export {
8
- RenderLevel
9
- };
@@ -1,16 +0,0 @@
1
- import { TemplateAPI } from "../hook-api/template";
2
- import { templateInjectableStream } from "../hook-api/templateForStream";
3
- const injectServerData = (content, context) => {
4
- const template = new TemplateAPI(content);
5
- template.prependHead(`<script type="application/json" id="__MODERN_SERVER_DATA__">${JSON.stringify(context.serverData)}</script>`);
6
- return template.get();
7
- };
8
- const injectServerDataStream = (content, context) => {
9
- return content.pipe(templateInjectableStream({
10
- prependHead: `<script type="application/json" id="__MODERN_SERVER_DATA__">${JSON.stringify(context.serverData)}</script>`
11
- }));
12
- };
13
- export {
14
- injectServerData,
15
- injectServerDataStream
16
- };
@@ -1,15 +0,0 @@
1
- const defaultReporter = {
2
- init() {
3
- },
4
- reportError() {
5
- },
6
- reportTiming() {
7
- },
8
- reportInfo() {
9
- },
10
- reportWarn() {
11
- }
12
- };
13
- export {
14
- defaultReporter
15
- };
@@ -1,60 +0,0 @@
1
- import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
- import { RouteMatcher } from "./matcher";
3
- class RouteMatchManager {
4
- // get all routes matches pathname
5
- filter(pathname) {
6
- return this.matchers.reduce((matches, matcher) => {
7
- if (matcher.matchUrlPath(pathname)) {
8
- matches.push(matcher);
9
- }
10
- return matches;
11
- }, []);
12
- }
13
- // get best match from a set of matches
14
- best(pathname, matches) {
15
- let best;
16
- let matchedLen = 0;
17
- for (const match of matches) {
18
- const len = match.matchLength(pathname);
19
- if (len === null) {
20
- continue;
21
- }
22
- if (len > matchedLen) {
23
- best = match;
24
- matchedLen = len;
25
- }
26
- }
27
- return best;
28
- }
29
- // reset routes matcher
30
- reset(specs) {
31
- this.specs = specs;
32
- const matchers = specs.reduce((ms, spec) => {
33
- ms.push(new RouteMatcher(spec));
34
- return ms;
35
- }, []);
36
- this.matchers = matchers;
37
- }
38
- // get best match from all matcher in manager
39
- match(pathname) {
40
- const matches = this.filter(pathname);
41
- const best = this.best(pathname, matches);
42
- return best;
43
- }
44
- matchEntry(entryname) {
45
- return this.matchers.find((matcher) => matcher.matchEntry(entryname));
46
- }
47
- getBundles() {
48
- const bundles = this.specs.filter((route) => route.isSSR).map((route) => route.bundle);
49
- return bundles;
50
- }
51
- constructor() {
52
- _define_property(this, "matchers", void 0);
53
- _define_property(this, "specs", []);
54
- this.matchers = [];
55
- }
56
- }
57
- export {
58
- RouteMatchManager,
59
- RouteMatcher
60
- };
@@ -1,93 +0,0 @@
1
- import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
- import { match, pathToRegexp, compile } from "path-to-regexp";
3
- import { ModernRoute } from "./route";
4
- const removeTailSlash = (s) => s.replace(/\/+$/, "");
5
- const removeHtmlSuffix = (url) => {
6
- if (url.endsWith(".html")) {
7
- return url.slice(0, -5);
8
- }
9
- return url;
10
- };
11
- const toPath = (reg, params) => {
12
- const fn = compile(reg, {
13
- encode: encodeURIComponent
14
- });
15
- return fn(params);
16
- };
17
- const regCharsDetector = /[^a-zA-Z\-_0-9\/\.]/;
18
- class RouteMatcher {
19
- // generate modern route object
20
- generate(url) {
21
- const route = new ModernRoute(this.spec);
22
- if (this.urlPath) {
23
- const params = this.parseURLParams(url);
24
- route.urlPath = toPath(route.urlPath, params);
25
- route.params = params;
26
- }
27
- return route;
28
- }
29
- parseURLParams(pathname) {
30
- if (!this.urlMatcher) {
31
- return {};
32
- } else {
33
- const matchResult = this.urlMatcher(pathname);
34
- return matchResult.params;
35
- }
36
- }
37
- // get match url length
38
- matchLength(pathname) {
39
- if (!this.urlReg) {
40
- return this.urlPath.length;
41
- } else {
42
- var _result_;
43
- const result = this.urlReg.exec(pathname);
44
- return (result === null || result === void 0 ? void 0 : (_result_ = result[0]) === null || _result_ === void 0 ? void 0 : _result_.length) || null;
45
- }
46
- }
47
- // if match url path
48
- matchUrlPath(requestUrl) {
49
- let urlWithoutSlash = requestUrl.endsWith("/") && requestUrl !== "/" ? requestUrl.slice(0, -1) : requestUrl;
50
- urlWithoutSlash = removeHtmlSuffix(urlWithoutSlash);
51
- if (this.urlMatcher) {
52
- return Boolean(this.urlMatcher(urlWithoutSlash));
53
- } else {
54
- const urlPath = removeHtmlSuffix(this.urlPath);
55
- if (urlWithoutSlash.startsWith(urlPath)) {
56
- if (urlPath !== "/" && urlWithoutSlash.length > urlPath.length && !urlWithoutSlash.startsWith(`${urlPath}/`)) {
57
- return false;
58
- }
59
- return true;
60
- }
61
- return false;
62
- }
63
- }
64
- matchEntry(entryName) {
65
- return this.spec.entryName === entryName;
66
- }
67
- // compiler urlPath to regexp if necessary
68
- setupUrlPath() {
69
- const { urlPath } = this.spec;
70
- this.urlPath = urlPath === "/" ? urlPath : removeTailSlash(urlPath);
71
- const useReg = regCharsDetector.test(urlPath);
72
- if (useReg) {
73
- this.urlMatcher = match(urlPath, {
74
- end: false,
75
- decode: decodeURIComponent
76
- });
77
- this.urlReg = pathToRegexp(urlPath, [], {
78
- end: false
79
- });
80
- }
81
- }
82
- constructor(spec) {
83
- _define_property(this, "spec", void 0);
84
- _define_property(this, "urlPath", "");
85
- _define_property(this, "urlMatcher", void 0);
86
- _define_property(this, "urlReg", void 0);
87
- this.spec = spec;
88
- this.setupUrlPath();
89
- }
90
- }
91
- export {
92
- RouteMatcher
93
- };
@@ -1,25 +0,0 @@
1
- import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
- class ModernRoute {
3
- constructor(routeSpec) {
4
- _define_property(this, "entryName", void 0);
5
- _define_property(this, "urlPath", void 0);
6
- _define_property(this, "entryPath", void 0);
7
- _define_property(this, "bundle", void 0);
8
- _define_property(this, "isApi", void 0);
9
- _define_property(this, "isSSR", void 0);
10
- _define_property(this, "isSPA", void 0);
11
- _define_property(this, "params", {});
12
- _define_property(this, "responseHeaders", void 0);
13
- this.entryName = routeSpec.entryName || "";
14
- this.urlPath = routeSpec.urlPath;
15
- this.entryPath = routeSpec.entryPath || "";
16
- this.isSSR = routeSpec.isSSR || false;
17
- this.isSPA = routeSpec.isSPA || false;
18
- this.isApi = routeSpec.isApi || false;
19
- this.bundle = routeSpec.bundle || "";
20
- this.responseHeaders = routeSpec.responseHeaders;
21
- }
22
- }
23
- export {
24
- ModernRoute
25
- };
@@ -1,49 +0,0 @@
1
- import serve from "serve-static";
2
- import { isString, isRegExp } from "@modern-js/utils";
3
- const removedPrefix = (req, prefix) => {
4
- const useLocalPrefix = !prefix.includes(".");
5
- if (useLocalPrefix) {
6
- req.url = req.url.slice(prefix.length);
7
- return () => {
8
- req.url = prefix + req.url;
9
- };
10
- } else {
11
- return () => {
12
- };
13
- }
14
- };
15
- const faviconFallbackHandler = (context, next) => {
16
- if (context.url === "/favicon.ico") {
17
- context.res.statusCode = 204;
18
- context.res.end();
19
- } else {
20
- next();
21
- }
22
- };
23
- const createStaticFileHandler = (rules, assetPrefix = "/") => (
24
- // eslint-disable-next-line consistent-return
25
- async (context, next) => {
26
- const { url: requestUrl, req, res } = context;
27
- const hitRule = rules.find((item) => {
28
- if (isString(item.path) && requestUrl.startsWith(item.path)) {
29
- return true;
30
- } else if (isRegExp(item.path) && item.path.test(requestUrl)) {
31
- return true;
32
- }
33
- return false;
34
- });
35
- if (hitRule) {
36
- const resume = removedPrefix(req, assetPrefix);
37
- serve(hitRule.target)(req, res, () => {
38
- resume();
39
- next();
40
- });
41
- } else {
42
- return next();
43
- }
44
- }
45
- );
46
- export {
47
- createStaticFileHandler,
48
- faviconFallbackHandler
49
- };
@@ -1,20 +0,0 @@
1
- import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
- const SERVER_TIMING = "Server-Timing";
3
- class ServerTiming {
4
- addServeTiming(name, dur, desc) {
5
- const _name = `bd-${this.meta}-${name}`;
6
- const serverTiming = this.res.getHeader(SERVER_TIMING) || this.res.getHeader(SERVER_TIMING.toLocaleLowerCase());
7
- const value = `${_name};${desc ? `decs="${desc}";` : ""} dur=${dur}`;
8
- this.res.set(SERVER_TIMING, serverTiming ? `${serverTiming}, ${value}` : value);
9
- return this;
10
- }
11
- constructor(res, meta) {
12
- _define_property(this, "meta", void 0);
13
- _define_property(this, "res", void 0);
14
- this.meta = meta;
15
- this.res = res;
16
- }
17
- }
18
- export {
19
- ServerTiming
20
- };
@@ -1,80 +0,0 @@
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 { _ as _define_property } from "@swc/helpers/_/_define_property";
6
- import { OutgoingMessage } from "http";
7
- import { Readable } from "stream";
8
- import { Socket } from "net";
9
- import { Server } from "./server";
10
- import { isRedirect } from "./utils";
11
- var require_renderHtml = __commonJS({
12
- "src/renderHtml.ts"(exports, module) {
13
- class IncomingMessageLike extends Readable {
14
- constructor({ method, url, headers }) {
15
- super();
16
- _define_property(this, "headers", void 0);
17
- _define_property(this, "method", void 0);
18
- _define_property(this, "url", void 0);
19
- _define_property(this, "socket", void 0);
20
- this.socket = new Socket();
21
- this.headers = headers || {};
22
- this.headers.host = "localhost:8080";
23
- this.method = method || "get";
24
- this.url = url;
25
- }
26
- }
27
- class ServerResponseLike extends OutgoingMessage {
28
- end(chunk, _encoding, cb) {
29
- this.data.push(chunk.toString());
30
- cb && cb();
31
- this.emit("finish");
32
- return this;
33
- }
34
- constructor() {
35
- super();
36
- _define_property(this, "statusCode", void 0);
37
- _define_property(this, "data", void 0);
38
- this.statusCode = 200;
39
- this.data = [];
40
- }
41
- }
42
- class CustomServer extends Server {
43
- async render(req, res, _url) {
44
- const handler = this.getRequestHandler();
45
- handler(req, res);
46
- return null;
47
- }
48
- }
49
- async function renderHtml({ url, method, headers, body, serverOptions }) {
50
- const req = new IncomingMessageLike({
51
- method,
52
- url,
53
- headers
54
- });
55
- if (body) {
56
- req.push(body);
57
- req.push(null);
58
- }
59
- const res = new ServerResponseLike();
60
- const customServer = new CustomServer(serverOptions);
61
- await customServer.init({
62
- disableHttpServer: true
63
- });
64
- customServer.render(req, res);
65
- return new Promise((resolve) => {
66
- res.addListener("finish", () => {
67
- resolve({
68
- headers: res.getHeaders(),
69
- redirected: isRedirect(res.statusCode),
70
- status: res.statusCode,
71
- url,
72
- body: res.data.join()
73
- });
74
- });
75
- });
76
- }
77
- module.exports = renderHtml;
78
- }
79
- });
80
- export default require_renderHtml();
@@ -1,195 +0,0 @@
1
- import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
- import path from "path";
3
- import { fs, createLogger, SHARED_DIR, OUTPUT_CONFIG_FILE, dotenv, dotenvExpand, INTERNAL_SERVER_PLUGINS, ensureAbsolutePath } from "@modern-js/utils";
4
- import { serverManager, AppContext, ConfigContext, loadPlugins } from "@modern-js/server-core";
5
- import { metrics as defaultMetrics } from "../libs/metrics";
6
- import { loadConfig, getServerConfigPath, requireConfig } from "../libs/loadConfig";
7
- import { debug } from "../utils";
8
- import { createProdServer } from "./modernServerSplit";
9
- class Server {
10
- /**
11
- * 初始化顺序
12
- * - 读取 .env.{process.env.MODERN_ENV} 文件,加载环境变量
13
- * - 获取 server runtime config
14
- * - 设置 context
15
- * - 创建 hooksRunner
16
- * - 合并插件,内置插件和 serverConfig 中配置的插件
17
- * - 执行 config hook
18
- * - 获取最终的配置
19
- * - 设置配置到 context
20
- * - 初始化 server
21
- * - 执行 prepare hook
22
- * - 执行 server init
23
- */
24
- async init({ disableHttpServer = false } = {
25
- disableHttpServer: false
26
- }) {
27
- const { options } = this;
28
- await this.loadServerEnv(options);
29
- this.initServerConfig(options);
30
- await this.injectContext(this.runner, options);
31
- this.runner = await this.createHookRunner();
32
- await this.initConfig(this.runner, options);
33
- await this.injectContext(this.runner, options);
34
- this.server = this.serverImpl(options);
35
- await this.runPrepareHook(this.runner);
36
- if (!disableHttpServer) {
37
- this.app = await this.server.createHTTPServer(this.getRequestHandler());
38
- }
39
- {
40
- const result = await this.runner.beforeServerInit({
41
- app: this.app,
42
- server: this.server
43
- });
44
- ({ app: this.app = this.app, server: this.server } = result);
45
- }
46
- await this.server.onInit(this.runner, this.app);
47
- {
48
- const result = await this.runner.afterServerInit({
49
- app: this.app,
50
- server: this.server
51
- });
52
- ({ app: this.app = this.app, server: this.server } = result);
53
- }
54
- return this;
55
- }
56
- /**
57
- * Execute config hooks
58
- * @param runner
59
- * @param options
60
- */
61
- runConfigHook(runner, serverConfig) {
62
- const newServerConfig = runner.config(serverConfig || {});
63
- return newServerConfig;
64
- }
65
- async runPrepareHook(runner) {
66
- runner.prepare();
67
- }
68
- initServerConfig(options) {
69
- const { pwd, serverConfigFile } = options;
70
- const distDirectory = path.join(pwd, options.config.output.path || "dist");
71
- const serverConfigPath = getServerConfigPath(distDirectory, serverConfigFile);
72
- const serverConfig = requireConfig(serverConfigPath);
73
- this.serverConfig = serverConfig;
74
- }
75
- /**
76
- *
77
- * merge cliConfig and serverConfig
78
- */
79
- async initConfig(runner, options) {
80
- const { pwd, config } = options;
81
- const { serverConfig } = this;
82
- const finalServerConfig = this.runConfigHook(runner, serverConfig);
83
- const resolvedConfigPath = ensureAbsolutePath(pwd, path.join(config.output.path || "dist", OUTPUT_CONFIG_FILE));
84
- options.config = loadConfig({
85
- cliConfig: config,
86
- serverConfig: finalServerConfig,
87
- resolvedConfigPath
88
- });
89
- }
90
- async close() {
91
- var _this_server_close, _this_server;
92
- await ((_this_server_close = (_this_server = this.server).close) === null || _this_server_close === void 0 ? void 0 : _this_server_close.call(_this_server));
93
- this.app.close();
94
- }
95
- listen(options, listener) {
96
- const callback = () => {
97
- listener === null || listener === void 0 ? void 0 : listener();
98
- };
99
- if (typeof options === "object") {
100
- if (process.env.PORT) {
101
- Object.assign(options, {
102
- port: process.env.PORT
103
- });
104
- }
105
- this.app.listen(options, callback);
106
- } else {
107
- this.app.listen(process.env.PORT || options || 8080, callback);
108
- }
109
- }
110
- getRequestHandler() {
111
- return (req, res, next) => {
112
- const requestHandler = this.server.getRequestHandler();
113
- return requestHandler(req, res, next);
114
- };
115
- }
116
- async render(req, res, url) {
117
- return this.server.render(req, res, url);
118
- }
119
- async createHookRunner() {
120
- serverManager.clear();
121
- const { options } = this;
122
- const { internalPlugins = INTERNAL_SERVER_PLUGINS, pwd, plugins = [] } = options;
123
- const serverPlugins = this.serverConfig.plugins || [];
124
- const loadedPlugins = loadPlugins(pwd, [
125
- ...serverPlugins,
126
- ...plugins
127
- ], {
128
- internalPlugins
129
- });
130
- debug("plugins", loadedPlugins);
131
- loadedPlugins.forEach((p) => {
132
- serverManager.usePlugin(p);
133
- });
134
- const hooksRunner = await serverManager.init();
135
- return hooksRunner;
136
- }
137
- async injectContext(runner, options) {
138
- const appContext = this.initAppContext();
139
- const { config, pwd } = options;
140
- ConfigContext.set(config);
141
- AppContext.set({
142
- ...appContext,
143
- distDirectory: path.join(pwd, config.output.path || "dist")
144
- });
145
- }
146
- initAppContext() {
147
- const { options } = this;
148
- const { pwd: appDirectory, plugins = [], config, appContext } = options;
149
- const serverPlugins = plugins.map((p) => ({
150
- server: p
151
- }));
152
- return {
153
- appDirectory,
154
- apiDirectory: appContext === null || appContext === void 0 ? void 0 : appContext.apiDirectory,
155
- lambdaDirectory: appContext === null || appContext === void 0 ? void 0 : appContext.lambdaDirectory,
156
- sharedDirectory: (appContext === null || appContext === void 0 ? void 0 : appContext.sharedDirectory) || path.resolve(appDirectory, SHARED_DIR),
157
- distDirectory: path.join(appDirectory, config.output.path || "dist"),
158
- plugins: serverPlugins
159
- };
160
- }
161
- async loadServerEnv(options) {
162
- const { pwd: appDirectory } = options;
163
- const serverEnv = process.env.MODERN_ENV;
164
- const defaultEnvPath = path.resolve(appDirectory, `.env`);
165
- const serverEnvPath = path.resolve(appDirectory, `.env.${serverEnv}`);
166
- for (const envPath of [
167
- serverEnvPath,
168
- defaultEnvPath
169
- ]) {
170
- if (await fs.pathExists(envPath) && !(await fs.stat(envPath)).isDirectory()) {
171
- const envConfig = dotenv.config({
172
- path: envPath
173
- });
174
- dotenvExpand(envConfig);
175
- }
176
- }
177
- }
178
- constructor(options) {
179
- _define_property(this, "options", void 0);
180
- _define_property(this, "serverImpl", createProdServer);
181
- _define_property(this, "server", void 0);
182
- _define_property(this, "app", void 0);
183
- _define_property(this, "runner", void 0);
184
- _define_property(this, "serverConfig", void 0);
185
- options.logger = options.logger || createLogger({
186
- level: "warn"
187
- });
188
- options.metrics = options.metrics || defaultMetrics;
189
- this.options = options;
190
- this.serverConfig = {};
191
- }
192
- }
193
- export {
194
- Server
195
- };