@modern-js/prod-server 2.14.0 → 2.16.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 (122) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/cjs/constants.js +15 -31
  3. package/dist/cjs/index.js +35 -37
  4. package/dist/cjs/libs/context/context.js +53 -66
  5. package/dist/cjs/libs/context/index.js +15 -28
  6. package/dist/cjs/libs/hook-api/index.js +59 -54
  7. package/dist/cjs/libs/hook-api/route.js +28 -30
  8. package/dist/cjs/libs/hook-api/template.js +30 -34
  9. package/dist/cjs/libs/loadConfig.js +74 -65
  10. package/dist/cjs/libs/logger.js +46 -37
  11. package/dist/cjs/libs/metrics.js +7 -25
  12. package/dist/cjs/libs/proxy.js +29 -46
  13. package/dist/cjs/libs/render/cache/__tests__/cache.fun.test.js +48 -64
  14. package/dist/cjs/libs/render/cache/__tests__/cache.test.js +53 -37
  15. package/dist/cjs/libs/render/cache/__tests__/cacheable.js +38 -34
  16. package/dist/cjs/libs/render/cache/__tests__/error-configuration.js +22 -30
  17. package/dist/cjs/libs/render/cache/__tests__/matched-cache.js +86 -46
  18. package/dist/cjs/libs/render/cache/index.js +17 -37
  19. package/dist/cjs/libs/render/cache/page-caches/index.js +12 -28
  20. package/dist/cjs/libs/render/cache/page-caches/lru.js +32 -40
  21. package/dist/cjs/libs/render/cache/spr.js +104 -111
  22. package/dist/cjs/libs/render/cache/type.js +4 -15
  23. package/dist/cjs/libs/render/cache/util.js +29 -53
  24. package/dist/cjs/libs/render/index.js +75 -73
  25. package/dist/cjs/libs/render/measure.js +19 -34
  26. package/dist/cjs/libs/render/reader.js +52 -61
  27. package/dist/cjs/libs/render/ssr.js +34 -66
  28. package/dist/cjs/libs/render/static.js +22 -45
  29. package/dist/cjs/libs/render/type.js +10 -28
  30. package/dist/cjs/libs/render/utils.js +17 -38
  31. package/dist/cjs/libs/route/index.js +32 -31
  32. package/dist/cjs/libs/route/matcher.js +38 -38
  33. package/dist/cjs/libs/route/route.js +29 -26
  34. package/dist/cjs/libs/serveFile.js +23 -41
  35. package/dist/cjs/server/index.js +101 -107
  36. package/dist/cjs/server/modernServer.js +191 -171
  37. package/dist/cjs/server/modernServerSplit.js +12 -30
  38. package/dist/cjs/type.js +4 -15
  39. package/dist/cjs/utils.js +50 -50
  40. package/dist/cjs/workerServer.js +26 -36
  41. package/dist/esm/constants.js +24 -25
  42. package/dist/esm/index.js +11 -10
  43. package/dist/esm/libs/context/context.js +271 -264
  44. package/dist/esm/libs/context/index.js +3 -3
  45. package/dist/esm/libs/hook-api/index.js +237 -223
  46. package/dist/esm/libs/hook-api/route.js +62 -60
  47. package/dist/esm/libs/hook-api/template.js +117 -115
  48. package/dist/esm/libs/loadConfig.js +68 -69
  49. package/dist/esm/libs/logger.js +188 -174
  50. package/dist/esm/libs/metrics.js +6 -3
  51. package/dist/esm/libs/proxy.js +236 -221
  52. package/dist/esm/libs/render/cache/__tests__/cache.fun.test.js +286 -267
  53. package/dist/esm/libs/render/cache/__tests__/cache.test.js +765 -745
  54. package/dist/esm/libs/render/cache/__tests__/cacheable.js +62 -63
  55. package/dist/esm/libs/render/cache/__tests__/error-configuration.js +42 -43
  56. package/dist/esm/libs/render/cache/__tests__/matched-cache.js +134 -135
  57. package/dist/esm/libs/render/cache/index.js +337 -326
  58. package/dist/esm/libs/render/cache/page-caches/index.js +147 -141
  59. package/dist/esm/libs/render/cache/page-caches/lru.js +78 -76
  60. package/dist/esm/libs/render/cache/spr.js +465 -456
  61. package/dist/esm/libs/render/cache/type.js +1 -1
  62. package/dist/esm/libs/render/cache/util.js +266 -246
  63. package/dist/esm/libs/render/index.js +226 -218
  64. package/dist/esm/libs/render/measure.js +136 -128
  65. package/dist/esm/libs/render/reader.js +315 -304
  66. package/dist/esm/libs/render/ssr.js +214 -209
  67. package/dist/esm/libs/render/static.js +208 -198
  68. package/dist/esm/libs/render/type.js +6 -7
  69. package/dist/esm/libs/render/utils.js +8 -9
  70. package/dist/esm/libs/route/index.js +134 -123
  71. package/dist/esm/libs/route/matcher.js +140 -130
  72. package/dist/esm/libs/route/route.js +36 -37
  73. package/dist/esm/libs/serveFile.js +177 -168
  74. package/dist/esm/server/index.js +578 -549
  75. package/dist/esm/server/modernServer.js +1137 -1074
  76. package/dist/esm/server/modernServerSplit.js +344 -328
  77. package/dist/esm/type.js +1 -1
  78. package/dist/esm/utils.js +133 -124
  79. package/dist/esm/workerServer.js +226 -220
  80. package/dist/esm-node/constants.js +7 -14
  81. package/dist/esm-node/index.js +4 -9
  82. package/dist/esm-node/libs/context/context.js +32 -25
  83. package/dist/esm-node/libs/context/index.js +2 -5
  84. package/dist/esm-node/libs/hook-api/index.js +40 -21
  85. package/dist/esm-node/libs/hook-api/route.js +21 -8
  86. package/dist/esm-node/libs/hook-api/template.js +19 -14
  87. package/dist/esm-node/libs/loadConfig.js +11 -28
  88. package/dist/esm-node/libs/logger.js +37 -17
  89. package/dist/esm-node/libs/metrics.js +1 -3
  90. package/dist/esm-node/libs/proxy.js +14 -22
  91. package/dist/esm-node/libs/render/cache/__tests__/cache.fun.test.js +25 -36
  92. package/dist/esm-node/libs/render/cache/__tests__/cache.test.js +23 -11
  93. package/dist/esm-node/libs/render/cache/__tests__/cacheable.js +32 -13
  94. package/dist/esm-node/libs/render/cache/__tests__/error-configuration.js +16 -9
  95. package/dist/esm-node/libs/render/cache/__tests__/matched-cache.js +80 -25
  96. package/dist/esm-node/libs/render/cache/index.js +3 -10
  97. package/dist/esm-node/libs/render/cache/page-caches/index.js +4 -5
  98. package/dist/esm-node/libs/render/cache/page-caches/lru.js +20 -8
  99. package/dist/esm-node/libs/render/cache/spr.js +79 -80
  100. package/dist/esm-node/libs/render/cache/type.js +1 -0
  101. package/dist/esm-node/libs/render/cache/util.js +13 -23
  102. package/dist/esm-node/libs/render/index.js +10 -28
  103. package/dist/esm-node/libs/render/measure.js +7 -13
  104. package/dist/esm-node/libs/render/reader.js +31 -26
  105. package/dist/esm-node/libs/render/ssr.js +5 -21
  106. package/dist/esm-node/libs/render/static.js +1 -4
  107. package/dist/esm-node/libs/render/type.js +3 -6
  108. package/dist/esm-node/libs/render/utils.js +6 -18
  109. package/dist/esm-node/libs/route/index.js +20 -9
  110. package/dist/esm-node/libs/route/matcher.js +28 -17
  111. package/dist/esm-node/libs/route/route.js +23 -5
  112. package/dist/esm-node/libs/serveFile.js +2 -6
  113. package/dist/esm-node/server/index.js +72 -75
  114. package/dist/esm-node/server/modernServer.js +102 -130
  115. package/dist/esm-node/server/modernServerSplit.js +1 -4
  116. package/dist/esm-node/type.js +1 -0
  117. package/dist/esm-node/utils.js +41 -32
  118. package/dist/esm-node/workerServer.js +9 -10
  119. package/dist/types/libs/context/context.d.ts +1 -1
  120. package/dist/types/server/modernServer.d.ts +1 -1
  121. package/dist/types/utils.d.ts +1 -1
  122. package/package.json +12 -8
@@ -1,5 +1,5 @@
1
1
  import { headersWithoutCookie } from "../../utils";
2
- const createMetrics = (context, metrics) => {
2
+ export const createMetrics = (context, metrics) => {
3
3
  const { entryName: entry, request } = context;
4
4
  const { pathname = "" } = request || {};
5
5
  const emitTimer = (name, cost, tags = {}) => {
@@ -16,9 +16,12 @@ const createMetrics = (context, metrics) => {
16
16
  entry
17
17
  });
18
18
  };
19
- return { emitTimer, emitCounter };
19
+ return {
20
+ emitTimer,
21
+ emitCounter
22
+ };
20
23
  };
21
- const createLogger = (serverContext, logger) => {
24
+ export const createLogger = (serverContext, logger) => {
22
25
  const request = serverContext.request || {};
23
26
  const { headers = {}, pathname = "" } = request;
24
27
  const debug = (message, ...args) => {
@@ -32,12 +35,7 @@ const createLogger = (serverContext, logger) => {
32
35
  e = message;
33
36
  message = "";
34
37
  }
35
- logger.error(
36
- `SSR Error - ${message}, error = %s, req.url = %s, req.headers = %o`,
37
- e instanceof Error ? e.stack || e.message : e,
38
- pathname,
39
- headersWithoutCookie(headers)
40
- );
38
+ logger.error(`SSR Error - ${message}, error = %s, req.url = %s, req.headers = %o`, e instanceof Error ? e.stack || e.message : e, pathname, headersWithoutCookie(headers));
41
39
  };
42
40
  return {
43
41
  error,
@@ -45,7 +43,3 @@ const createLogger = (serverContext, logger) => {
45
43
  debug
46
44
  };
47
45
  };
48
- export {
49
- createLogger,
50
- createMetrics
51
- };
@@ -1,3 +1,16 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
1
14
  import { fs } from "@modern-js/utils";
2
15
  import LRU from "lru-cache";
3
16
  const Byte = 1;
@@ -11,16 +24,7 @@ const createCacheItem = async (filepath, mtime) => {
11
24
  mtime
12
25
  };
13
26
  };
14
- class LruReader {
15
- // private timer?: NodeJS.Timeout;
16
- constructor() {
17
- this.cache = new LRU({
18
- max: 256 * MB,
19
- length: getContentLength,
20
- maxAge: 5 * 60 * 5e3
21
- // 60s
22
- });
23
- }
27
+ export class LruReader {
24
28
  init() {
25
29
  }
26
30
  close() {
@@ -28,7 +32,9 @@ class LruReader {
28
32
  async read(filepath) {
29
33
  if (this.cache.has(filepath)) {
30
34
  const { content } = this.cache.get(filepath);
31
- return { content };
35
+ return {
36
+ content
37
+ };
32
38
  }
33
39
  if (!fs.existsSync(filepath)) {
34
40
  return null;
@@ -63,28 +69,27 @@ class LruReader {
63
69
  }
64
70
  }
65
71
  }
66
- // private timeTask() {
67
- // this.timer = setInterval(() => this.update, 5 * 60 * 1000).unref();
68
- // }
72
+ // private timer?: NodeJS.Timeout;
73
+ constructor() {
74
+ _define_property(this, "cache", void 0);
75
+ this.cache = new LRU({
76
+ max: 256 * MB,
77
+ length: getContentLength,
78
+ maxAge: 5 * 60 * 5e3
79
+ });
80
+ }
69
81
  }
70
82
  const reader = new LruReader();
71
- const readFile = async (filepath) => {
83
+ export const readFile = async (filepath) => {
72
84
  const file = await reader.read(filepath);
73
- return file == null ? void 0 : file.content;
85
+ return file === null || file === void 0 ? void 0 : file.content;
74
86
  };
75
- const updateFile = () => {
87
+ export const updateFile = () => {
76
88
  reader.update();
77
89
  };
78
- const init = () => {
90
+ export const init = () => {
79
91
  reader.init();
80
92
  };
81
- const close = () => {
93
+ export const close = () => {
82
94
  reader.close();
83
95
  };
84
- export {
85
- LruReader,
86
- close,
87
- init,
88
- readFile,
89
- updateFile
90
- };
@@ -1,24 +1,12 @@
1
1
  import path from "path";
2
2
  import { fs, mime } from "@modern-js/utils";
3
- import {
4
- LOADABLE_STATS_FILE,
5
- ROUTE_MANIFEST_FILE,
6
- SERVER_RENDER_FUNCTION_NAME
7
- } from "@modern-js/utils/constants";
3
+ import { LOADABLE_STATS_FILE, ROUTE_MANIFEST_FILE, SERVER_RENDER_FUNCTION_NAME } from "@modern-js/utils/constants";
8
4
  import cache from "./cache";
9
5
  import { createLogger, createMetrics } from "./measure";
10
6
  import { injectServerDataStream, injectServerData } from "./utils";
11
- const render = async (ctx, renderOptions, runner) => {
12
- var _a;
13
- const {
14
- urlPath,
15
- bundle,
16
- distDir,
17
- template,
18
- entryName,
19
- staticGenerate,
20
- enableUnsafeCtx = false
21
- } = renderOptions;
7
+ export const render = async (ctx, renderOptions, runner) => {
8
+ var _ctx_res;
9
+ const { urlPath, bundle, distDir, template, entryName, staticGenerate, enableUnsafeCtx = false } = renderOptions;
22
10
  const bundleJS = path.join(distDir, bundle);
23
11
  const loadableUri = path.join(distDir, LOADABLE_STATS_FILE);
24
12
  const loadableStats = fs.existsSync(loadableUri) ? require(loadableUri) : "";
@@ -41,13 +29,12 @@ const render = async (ctx, renderOptions, runner) => {
41
29
  status: (code) => {
42
30
  ctx.res.statusCode = code;
43
31
  },
44
- locals: ((_a = ctx.res) == null ? void 0 : _a.locals) || {}
32
+ locals: ((_ctx_res = ctx.res) === null || _ctx_res === void 0 ? void 0 : _ctx_res.locals) || {}
45
33
  },
46
34
  redirection: {},
47
35
  template,
48
36
  loadableStats,
49
37
  routeManifest,
50
- // for streaming ssr
51
38
  entryName,
52
39
  staticGenerate,
53
40
  logger: void 0,
@@ -83,6 +70,3 @@ const render = async (ctx, renderOptions, runner) => {
83
70
  };
84
71
  }
85
72
  };
86
- export {
87
- render
88
- };
@@ -1,7 +1,7 @@
1
1
  import path from "path";
2
2
  import { mime } from "@modern-js/utils";
3
3
  import { readFile } from "./reader";
4
- async function handleDirectory(ctx, entryPath, urlPath) {
4
+ export async function handleDirectory(ctx, entryPath, urlPath) {
5
5
  const { path: pathname } = ctx;
6
6
  const filepath = path.join(entryPath, trimLeft(pathname, urlPath));
7
7
  let content = await readFile(filepath);
@@ -33,6 +33,3 @@ const trimLeft = (str, prefix) => {
33
33
  }
34
34
  return str;
35
35
  };
36
- export {
37
- handleDirectory
38
- };
@@ -1,9 +1,6 @@
1
- var RenderLevel = /* @__PURE__ */ ((RenderLevel2) => {
1
+ export var RenderLevel;
2
+ (function(RenderLevel2) {
2
3
  RenderLevel2[RenderLevel2["CLIENT_RENDER"] = 0] = "CLIENT_RENDER";
3
4
  RenderLevel2[RenderLevel2["SERVER_PREFETCH"] = 1] = "SERVER_PREFETCH";
4
5
  RenderLevel2[RenderLevel2["SERVER_RENDER"] = 2] = "SERVER_RENDER";
5
- return RenderLevel2;
6
- })(RenderLevel || {});
7
- export {
8
- RenderLevel
9
- };
6
+ })(RenderLevel || (RenderLevel = {}));
@@ -1,23 +1,11 @@
1
1
  import { TemplateAPI, templateInjectableStream } from "../hook-api/template";
2
- const injectServerData = (content, context) => {
2
+ export const injectServerData = (content, context) => {
3
3
  const template = new TemplateAPI(content);
4
- template.prependHead(
5
- `<script type="application/json" id="__MODERN_SERVER_DATA__">${JSON.stringify(
6
- context.serverData
7
- )}</script>`
8
- );
4
+ template.prependHead(`<script type="application/json" id="__MODERN_SERVER_DATA__">${JSON.stringify(context.serverData)}</script>`);
9
5
  return template.get();
10
6
  };
11
- const injectServerDataStream = (content, context) => {
12
- return content.pipe(
13
- templateInjectableStream({
14
- prependHead: `<script type="application/json" id="__MODERN_SERVER_DATA__">${JSON.stringify(
15
- context.serverData
16
- )}</script>`
17
- })
18
- );
19
- };
20
- export {
21
- injectServerData,
22
- injectServerDataStream
7
+ export const injectServerDataStream = (content, context) => {
8
+ return content.pipe(templateInjectableStream({
9
+ prependHead: `<script type="application/json" id="__MODERN_SERVER_DATA__">${JSON.stringify(context.serverData)}</script>`
10
+ }));
23
11
  };
@@ -1,9 +1,18 @@
1
- import { RouteMatcher } from "./matcher";
2
- class RouteMatchManager {
3
- constructor() {
4
- this.specs = [];
5
- this.matchers = [];
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
6
11
  }
12
+ return obj;
13
+ }
14
+ import { RouteMatcher } from "./matcher";
15
+ export class RouteMatchManager {
7
16
  // get all routes matches pathname
8
17
  filter(pathname) {
9
18
  return this.matchers.reduce((matches, matcher) => {
@@ -51,8 +60,10 @@ class RouteMatchManager {
51
60
  const bundles = this.specs.filter((route) => route.isSSR).map((route) => route.bundle);
52
61
  return bundles;
53
62
  }
63
+ constructor() {
64
+ _define_property(this, "matchers", void 0);
65
+ _define_property(this, "specs", []);
66
+ this.matchers = [];
67
+ }
54
68
  }
55
- export {
56
- RouteMatchManager,
57
- RouteMatcher
58
- };
69
+ export { RouteMatcher };
@@ -1,8 +1,17 @@
1
- import {
2
- match,
3
- pathToRegexp,
4
- compile
5
- } from "path-to-regexp";
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ import { match, pathToRegexp, compile } from "path-to-regexp";
6
15
  import { ModernRoute } from "./route";
7
16
  const removeTailSlash = (s) => s.replace(/\/+$/, "");
8
17
  const removeHtmlSuffix = (url) => {
@@ -12,16 +21,13 @@ const removeHtmlSuffix = (url) => {
12
21
  return url;
13
22
  };
14
23
  const toPath = (reg, params) => {
15
- const fn = compile(reg, { encode: encodeURIComponent });
24
+ const fn = compile(reg, {
25
+ encode: encodeURIComponent
26
+ });
16
27
  return fn(params);
17
28
  };
18
29
  const regCharsDetector = /[^a-zA-Z\-_0-9\/\.]/;
19
- class RouteMatcher {
20
- constructor(spec) {
21
- this.urlPath = "";
22
- this.spec = spec;
23
- this.setupUrlPath();
24
- }
30
+ export class RouteMatcher {
25
31
  // generate modern route object
26
32
  generate(url) {
27
33
  const route = new ModernRoute(this.spec);
@@ -42,12 +48,12 @@ class RouteMatcher {
42
48
  }
43
49
  // get match url length
44
50
  matchLength(pathname) {
45
- var _a;
46
51
  if (!this.urlReg) {
47
52
  return this.urlPath.length;
48
53
  } else {
54
+ var _result_;
49
55
  const result = this.urlReg.exec(pathname);
50
- return ((_a = result == null ? void 0 : result[0]) == null ? void 0 : _a.length) || null;
56
+ return (result === null || result === void 0 ? void 0 : (_result_ = result[0]) === null || _result_ === void 0 ? void 0 : _result_.length) || null;
51
57
  }
52
58
  }
53
59
  // if match url path
@@ -85,7 +91,12 @@ class RouteMatcher {
85
91
  });
86
92
  }
87
93
  }
94
+ constructor(spec) {
95
+ _define_property(this, "spec", void 0);
96
+ _define_property(this, "urlPath", "");
97
+ _define_property(this, "urlMatcher", void 0);
98
+ _define_property(this, "urlReg", void 0);
99
+ this.spec = spec;
100
+ this.setupUrlPath();
101
+ }
88
102
  }
89
- export {
90
- RouteMatcher
91
- };
@@ -1,6 +1,27 @@
1
- class ModernRoute {
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ export class ModernRoute {
2
15
  constructor(routeSpec) {
3
- this.params = {};
16
+ _define_property(this, "entryName", void 0);
17
+ _define_property(this, "urlPath", void 0);
18
+ _define_property(this, "entryPath", void 0);
19
+ _define_property(this, "bundle", void 0);
20
+ _define_property(this, "isApi", void 0);
21
+ _define_property(this, "isSSR", void 0);
22
+ _define_property(this, "isSPA", void 0);
23
+ _define_property(this, "params", {});
24
+ _define_property(this, "responseHeaders", void 0);
4
25
  this.entryName = routeSpec.entryName || "";
5
26
  this.urlPath = routeSpec.urlPath;
6
27
  this.entryPath = routeSpec.entryPath || "";
@@ -11,6 +32,3 @@ class ModernRoute {
11
32
  this.responseHeaders = routeSpec.responseHeaders;
12
33
  }
13
34
  }
14
- export {
15
- ModernRoute
16
- };
@@ -12,7 +12,7 @@ const removedPrefix = (req, prefix) => {
12
12
  };
13
13
  }
14
14
  };
15
- const faviconFallbackHandler = (context, next) => {
15
+ export const faviconFallbackHandler = (context, next) => {
16
16
  if (context.url === "/favicon.ico") {
17
17
  context.res.statusCode = 204;
18
18
  context.res.end();
@@ -20,7 +20,7 @@ const faviconFallbackHandler = (context, next) => {
20
20
  next();
21
21
  }
22
22
  };
23
- const createStaticFileHandler = (rules, assetPrefix = "/") => (
23
+ export const createStaticFileHandler = (rules, assetPrefix = "/") => (
24
24
  // eslint-disable-next-line consistent-return
25
25
  async (context, next) => {
26
26
  const { url: requestUrl, req, res } = context;
@@ -43,7 +43,3 @@ const createStaticFileHandler = (rules, assetPrefix = "/") => (
43
43
  }
44
44
  }
45
45
  );
46
- export {
47
- createStaticFileHandler,
48
- faviconFallbackHandler
49
- };
@@ -1,51 +1,38 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
1
14
  import path from "path";
2
- import {
3
- fs,
4
- Logger,
5
- SHARED_DIR,
6
- OUTPUT_CONFIG_FILE,
7
- dotenv,
8
- dotenvExpand,
9
- INTERNAL_SERVER_PLUGINS
10
- } from "@modern-js/utils";
11
- import {
12
- serverManager,
13
- AppContext,
14
- ConfigContext,
15
- loadPlugins
16
- } from "@modern-js/server-core";
15
+ import { fs, Logger, SHARED_DIR, OUTPUT_CONFIG_FILE, dotenv, dotenvExpand, INTERNAL_SERVER_PLUGINS } from "@modern-js/utils";
16
+ import { serverManager, AppContext, ConfigContext, loadPlugins } from "@modern-js/server-core";
17
17
  import { metrics as defaultMetrics } from "../libs/metrics";
18
- import {
19
- loadConfig,
20
- getServerConfigPath,
21
- requireConfig
22
- } from "../libs/loadConfig";
18
+ import { loadConfig, getServerConfigPath, requireConfig } from "../libs/loadConfig";
23
19
  import { debug } from "../utils";
24
20
  import { createProdServer } from "./modernServerSplit";
25
- class Server {
26
- constructor(options) {
27
- this.serverImpl = createProdServer;
28
- options.logger = options.logger || new Logger({
29
- level: "warn"
30
- });
31
- options.metrics = options.metrics || defaultMetrics;
32
- this.options = options;
33
- this.serverConfig = {};
34
- }
21
+ export class Server {
35
22
  /**
36
- * 初始化顺序
37
- * - 读取 .env.{process.env.MODERN_ENV} 文件,加载环境变量
38
- * - 获取 server runtime config
39
- * - 设置 context
40
- * - 创建 hooksRunner
41
- * - 合并插件,内置插件和 serverConfig 中配置的插件
42
- * - 执行 config hook
43
- * - 获取最终的配置
44
- * - 设置配置到 context
45
- * - 初始化 server
46
- * - 执行 prepare hook
47
- * - 执行 server init
48
- */
23
+ * 初始化顺序
24
+ * - 读取 .env.{process.env.MODERN_ENV} 文件,加载环境变量
25
+ * - 获取 server runtime config
26
+ * - 设置 context
27
+ * - 创建 hooksRunner
28
+ * - 合并插件,内置插件和 serverConfig 中配置的插件
29
+ * - 执行 config hook
30
+ * - 获取最终的配置
31
+ * - 设置配置到 context
32
+ * - 初始化 server
33
+ * - 执行 prepare hook
34
+ * - 执行 server init
35
+ */
49
36
  async init() {
50
37
  const { options } = this;
51
38
  await this.loadServerEnv(options);
@@ -61,10 +48,10 @@ class Server {
61
48
  return this;
62
49
  }
63
50
  /**
64
- * Execute config hooks
65
- * @param runner
66
- * @param options
67
- */
51
+ * Execute config hooks
52
+ * @param runner
53
+ * @param options
54
+ */
68
55
  runConfigHook(runner, serverConfig) {
69
56
  const newServerConfig = runner.config(serverConfig || {});
70
57
  return newServerConfig;
@@ -75,26 +62,19 @@ class Server {
75
62
  initServerConfig(options) {
76
63
  const { pwd, serverConfigFile } = options;
77
64
  const distDirectory = path.join(pwd, options.config.output.path || "dist");
78
- const serverConfigPath = getServerConfigPath(
79
- distDirectory,
80
- serverConfigFile
81
- );
65
+ const serverConfigPath = getServerConfigPath(distDirectory, serverConfigFile);
82
66
  const serverConfig = requireConfig(serverConfigPath);
83
67
  this.serverConfig = serverConfig;
84
68
  }
85
69
  /**
86
- *
87
- * merge cliConfig and serverConfig
88
- */
70
+ *
71
+ * merge cliConfig and serverConfig
72
+ */
89
73
  async initConfig(runner, options) {
90
74
  const { pwd, config } = options;
91
75
  const { serverConfig } = this;
92
76
  const finalServerConfig = this.runConfigHook(runner, serverConfig);
93
- const resolvedConfigPath = path.join(
94
- pwd,
95
- config.output.path || "dist",
96
- OUTPUT_CONFIG_FILE
97
- );
77
+ const resolvedConfigPath = path.join(pwd, config.output.path || "dist", OUTPUT_CONFIG_FILE);
98
78
  options.config = loadConfig({
99
79
  cliConfig: config,
100
80
  serverConfig: finalServerConfig,
@@ -106,11 +86,13 @@ class Server {
106
86
  }
107
87
  listen(options, listener) {
108
88
  const callback = () => {
109
- listener == null ? void 0 : listener();
89
+ listener === null || listener === void 0 ? void 0 : listener();
110
90
  };
111
91
  if (typeof options === "object") {
112
92
  if (process.env.PORT) {
113
- Object.assign(options, { port: process.env.PORT });
93
+ Object.assign(options, {
94
+ port: process.env.PORT
95
+ });
114
96
  }
115
97
  this.app.listen(options, callback);
116
98
  } else {
@@ -129,13 +111,12 @@ class Server {
129
111
  async createHookRunner() {
130
112
  serverManager.clear();
131
113
  const { options } = this;
132
- const {
133
- internalPlugins = INTERNAL_SERVER_PLUGINS,
134
- pwd,
135
- plugins = []
136
- } = options;
114
+ const { internalPlugins = INTERNAL_SERVER_PLUGINS, pwd, plugins = [] } = options;
137
115
  const serverPlugins = this.serverConfig.plugins || [];
138
- const loadedPlugins = loadPlugins(pwd, [...serverPlugins, ...plugins], {
116
+ const loadedPlugins = loadPlugins(pwd, [
117
+ ...serverPlugins,
118
+ ...plugins
119
+ ], {
139
120
  internalPlugins
140
121
  });
141
122
  debug("plugins", loadedPlugins);
@@ -162,9 +143,9 @@ class Server {
162
143
  }));
163
144
  return {
164
145
  appDirectory,
165
- apiDirectory: appContext == null ? void 0 : appContext.apiDirectory,
166
- lambdaDirectory: appContext == null ? void 0 : appContext.lambdaDirectory,
167
- sharedDirectory: (appContext == null ? void 0 : appContext.sharedDirectory) || path.resolve(appDirectory, SHARED_DIR),
146
+ apiDirectory: appContext === null || appContext === void 0 ? void 0 : appContext.apiDirectory,
147
+ lambdaDirectory: appContext === null || appContext === void 0 ? void 0 : appContext.lambdaDirectory,
148
+ sharedDirectory: (appContext === null || appContext === void 0 ? void 0 : appContext.sharedDirectory) || path.resolve(appDirectory, SHARED_DIR),
168
149
  distDirectory: path.join(appDirectory, config.output.path || "dist"),
169
150
  plugins: serverPlugins
170
151
  };
@@ -174,14 +155,30 @@ class Server {
174
155
  const serverEnv = process.env.MODERN_ENV;
175
156
  const defaultEnvPath = path.resolve(appDirectory, `.env`);
176
157
  const serverEnvPath = path.resolve(appDirectory, `.env.${serverEnv}`);
177
- for (const envPath of [serverEnvPath, defaultEnvPath]) {
158
+ for (const envPath of [
159
+ serverEnvPath,
160
+ defaultEnvPath
161
+ ]) {
178
162
  if (await fs.pathExists(envPath) && !(await fs.stat(envPath)).isDirectory()) {
179
- const envConfig = dotenv.config({ path: envPath });
163
+ const envConfig = dotenv.config({
164
+ path: envPath
165
+ });
180
166
  dotenvExpand(envConfig);
181
167
  }
182
168
  }
183
169
  }
170
+ constructor(options) {
171
+ _define_property(this, "options", void 0);
172
+ _define_property(this, "serverImpl", createProdServer);
173
+ _define_property(this, "server", void 0);
174
+ _define_property(this, "app", void 0);
175
+ _define_property(this, "runner", void 0);
176
+ _define_property(this, "serverConfig", void 0);
177
+ options.logger = options.logger || new Logger({
178
+ level: "warn"
179
+ });
180
+ options.metrics = options.metrics || defaultMetrics;
181
+ this.options = options;
182
+ this.serverConfig = {};
183
+ }
184
184
  }
185
- export {
186
- Server
187
- };