@modern-js/prod-server 1.1.2 → 1.1.5

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 (83) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/js/modern/libs/context/context.js +21 -22
  3. package/dist/js/modern/libs/hook-api/route.js +8 -3
  4. package/dist/js/modern/libs/hook-api/template.js +4 -1
  5. package/dist/js/modern/libs/metrics.js +2 -2
  6. package/dist/js/modern/libs/proxy.js +2 -2
  7. package/dist/js/modern/libs/render/cache/page-caches/lru.js +6 -2
  8. package/dist/js/modern/libs/render/cache/spr.js +7 -4
  9. package/dist/js/modern/libs/render/measure.js +59 -0
  10. package/dist/js/modern/libs/render/reader.js +4 -1
  11. package/dist/js/modern/libs/render/ssr.js +5 -2
  12. package/dist/js/modern/libs/route/index.js +6 -2
  13. package/dist/js/modern/libs/route/matcher.js +10 -4
  14. package/dist/js/modern/libs/route/route.js +20 -9
  15. package/dist/js/modern/server/index.js +16 -8
  16. package/dist/js/modern/server/modern-server-split.js +4 -4
  17. package/dist/js/modern/server/modern-server.js +61 -33
  18. package/dist/js/modern/utils.js +0 -9
  19. package/dist/js/node/libs/context/context.js +21 -23
  20. package/dist/js/node/libs/hook-api/route.js +8 -3
  21. package/dist/js/node/libs/hook-api/template.js +5 -1
  22. package/dist/js/node/libs/metrics.js +2 -2
  23. package/dist/js/node/libs/proxy.js +2 -2
  24. package/dist/js/node/libs/render/cache/page-caches/lru.js +6 -2
  25. package/dist/js/node/libs/render/cache/spr.js +6 -6
  26. package/dist/js/node/libs/render/measure.js +71 -0
  27. package/dist/js/node/libs/render/reader.js +4 -1
  28. package/dist/js/node/libs/render/ssr.js +6 -2
  29. package/dist/js/node/libs/route/index.js +6 -2
  30. package/dist/js/node/libs/route/matcher.js +10 -4
  31. package/dist/js/node/libs/route/route.js +20 -9
  32. package/dist/js/node/server/index.js +15 -7
  33. package/dist/js/node/server/modern-server-split.js +4 -4
  34. package/dist/js/node/server/modern-server.js +61 -33
  35. package/dist/js/node/utils.js +1 -13
  36. package/dist/types/libs/context/context.d.ts +3 -8
  37. package/dist/types/libs/render/measure.d.ts +10 -0
  38. package/dist/types/server/modern-server.d.ts +2 -2
  39. package/dist/types/utils.d.ts +0 -1
  40. package/package.json +30 -9
  41. package/.eslintrc.js +0 -8
  42. package/dist/js/styles/tsconfig.json +0 -12
  43. package/jest.config.js +0 -8
  44. package/modern.config.js +0 -2
  45. package/src/constants.ts +0 -31
  46. package/src/index.ts +0 -19
  47. package/src/libs/context/context.ts +0 -183
  48. package/src/libs/context/index.ts +0 -7
  49. package/src/libs/hook-api/route.ts +0 -42
  50. package/src/libs/hook-api/template.ts +0 -53
  51. package/src/libs/loadConfig.ts +0 -59
  52. package/src/libs/metrics.ts +0 -15
  53. package/src/libs/proxy.ts +0 -44
  54. package/src/libs/render/cache/__tests__/cache.fun.test.ts +0 -94
  55. package/src/libs/render/cache/__tests__/cache.test.ts +0 -240
  56. package/src/libs/render/cache/__tests__/cacheable.ts +0 -44
  57. package/src/libs/render/cache/__tests__/error-configuration.ts +0 -34
  58. package/src/libs/render/cache/__tests__/matched-cache.ts +0 -88
  59. package/src/libs/render/cache/index.ts +0 -73
  60. package/src/libs/render/cache/page-caches/index.ts +0 -11
  61. package/src/libs/render/cache/page-caches/lru.ts +0 -38
  62. package/src/libs/render/cache/spr.ts +0 -300
  63. package/src/libs/render/cache/type.ts +0 -59
  64. package/src/libs/render/cache/util.ts +0 -94
  65. package/src/libs/render/index.ts +0 -79
  66. package/src/libs/render/modern/browser-list.ts +0 -7
  67. package/src/libs/render/modern/index.ts +0 -41
  68. package/src/libs/render/modern/module.d.ts +0 -4
  69. package/src/libs/render/reader.ts +0 -119
  70. package/src/libs/render/ssr.ts +0 -66
  71. package/src/libs/render/static.ts +0 -52
  72. package/src/libs/render/type.ts +0 -38
  73. package/src/libs/route/index.ts +0 -76
  74. package/src/libs/route/matcher.ts +0 -108
  75. package/src/libs/route/route.ts +0 -34
  76. package/src/libs/serve-file.ts +0 -34
  77. package/src/server/index.ts +0 -227
  78. package/src/server/modern-server-split.ts +0 -93
  79. package/src/server/modern-server.ts +0 -620
  80. package/src/tsconfig.json +0 -12
  81. package/src/type.ts +0 -95
  82. package/src/utils.ts +0 -125
  83. package/tsconfig.json +0 -11
@@ -0,0 +1,10 @@
1
+ import { BaseSSRServerContext, Logger, Metrics } from '@modern-js/types';
2
+ export declare const createMetrics: (context: BaseSSRServerContext, metrics: Metrics) => {
3
+ emitTimer: (name: string, cost: number, tags?: Record<string, unknown>) => void;
4
+ emitCounter: (name: string, counter: number, tags?: Record<string, unknown>) => void;
5
+ };
6
+ export declare const createLogger: (serverContext: BaseSSRServerContext, logger: Logger) => {
7
+ error: (message: string, e: Error | string) => void;
8
+ info: (message: string, ...args: any[]) => void;
9
+ debug: (message: string, ...args: any[]) => void;
10
+ };
@@ -46,7 +46,7 @@ export declare class ModernServer implements ModernServerInterface {
46
46
  onRepack(_: BuildOptions): void;
47
47
  onListening(_: Server): void;
48
48
  protected onServerChange(_: Record<string, any>): void;
49
- getRequestHandler(): (req: IncomingMessage, res: ServerResponse, next?: () => void) => void;
49
+ getRequestHandler(): (req: IncomingMessage, res: ServerResponse, next?: () => void) => void | ServerResponse;
50
50
  createHTTPServer(handler: (req: IncomingMessage, res: ServerResponse, next?: () => void) => void): Promise<Server>;
51
51
  protected getRoutes(): ModernRouteInterface[];
52
52
  protected addHandler(handler: ModernServerHandler): void;
@@ -59,7 +59,7 @@ export declare class ModernServer implements ModernServerInterface {
59
59
  context: ModernServerContext;
60
60
  [propsName: string]: any;
61
61
  }): Promise<any>;
62
- protected preServerInit(): Promise<void>;
62
+ protected setupBeforeProdMiddleware(): Promise<void>;
63
63
  protected handleAPI(context: ModernServerContext): Promise<void>;
64
64
  protected handleWeb(context: ModernServerContext, route: ModernRoute): Promise<import("../type").RenderResult | null>;
65
65
  protected proxy(): Promise<any>;
@@ -3,7 +3,6 @@ export declare const debug: any;
3
3
  export declare const mergeExtension: (users: any[]) => {
4
4
  middleware: any[];
5
5
  };
6
- export declare const toMessage: (dig: string, e: Error | string) => string;
7
6
  export declare const noop: () => void;
8
7
  export declare const createErrorDocument: (status: number, text: string) => string;
9
8
  export declare type CollectMiddlewaresResult = {
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.1.2",
14
+ "version": "1.1.5",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -28,9 +28,9 @@
28
28
  }
29
29
  },
30
30
  "dependencies": {
31
- "@modern-js/utils": "^1.6.0",
31
+ "@modern-js/utils": "^1.7.3",
32
32
  "@babel/compat-data": "^7.17.0",
33
- "@modern-js/server-core": "^1.3.2",
33
+ "@modern-js/server-core": "^1.3.5",
34
34
  "axios": "^0.24.0",
35
35
  "compare-versions": "^3.6.0",
36
36
  "cookie": "^0.4.2",
@@ -43,18 +43,17 @@
43
43
  "ua-parser-js": "^0.7.28"
44
44
  },
45
45
  "devDependencies": {
46
- "@modern-js/types": "1.5.1",
47
- "@modern-js/core": "1.9.0",
46
+ "@modern-js/types": "1.5.3",
47
+ "@modern-js/core": "1.10.2",
48
48
  "@scripts/jest-config": "0.0.0",
49
49
  "@scripts/build": "0.0.0",
50
50
  "@types/cookie": "^0.4.1",
51
- "@types/jest": "^26.0.9",
51
+ "@types/jest": "^27",
52
52
  "@types/lru-cache": "^5.1.1",
53
53
  "@types/merge-deep": "^3.0.0",
54
54
  "@types/node": "^14",
55
55
  "@types/serve-static": "^1.13.10",
56
56
  "@types/ua-parser-js": "^0.7.36",
57
- "del-cli": "^4.0.1",
58
57
  "jest": "^27",
59
58
  "node-mocks-http": "^1.11.0",
60
59
  "portfinder": "^1.0.28",
@@ -70,11 +69,33 @@
70
69
  "access": "public",
71
70
  "registry": "https://registry.npmjs.org/"
72
71
  },
72
+ "wireit": {
73
+ "build": {
74
+ "command": "modern build",
75
+ "files": [
76
+ "src/**/*",
77
+ "tsconfig.json",
78
+ "package.json"
79
+ ],
80
+ "output": [
81
+ "dist/**/*"
82
+ ]
83
+ },
84
+ "test": {
85
+ "command": "jest",
86
+ "files": [
87
+ "src/**/*",
88
+ "tsconfig.json",
89
+ "package.json"
90
+ ],
91
+ "output": []
92
+ }
93
+ },
73
94
  "scripts": {
74
95
  "new": "modern new",
75
- "build": "modern build",
96
+ "build": "wireit",
76
97
  "dev": "modern build --watch",
77
- "test": "jest"
98
+ "test": "wireit"
78
99
  },
79
100
  "readme": "\n<p align=\"center\">\n <a href=\"https://modernjs.dev\" target=\"blank\"><img src=\"https://lf3-static.bytednsdoc.com/obj/eden-cn/ylaelkeh7nuhfnuhf/modernjs-cover.png\" width=\"300\" alt=\"Modern.js Logo\" /></a>\n</p>\n<p align=\"center\">\n现代 Web 工程体系\n <br/>\n <a href=\"https://modernjs.dev\" target=\"blank\">\n modernjs.dev\n </a>\n</p>\n<p align=\"center\">\n The meta-framework suite designed from scratch for frontend-focused modern web development\n</p>\n\n# Introduction\n\n> The doc site ([modernjs.dev](https://modernjs.dev)) and articles are only available in Chinese for now, we are planning to add English versions soon.\n\n- [Modern.js: Hello, World!](https://zhuanlan.zhihu.com/p/426707646)\n\n## Getting Started\n\n- [Quick Start](https://modernjs.dev/docs/start)\n- [Guides](https://modernjs.dev/docs/guides)\n- [API References](https://modernjs.dev/docs/apis)\n\n## Contributing\n\n- [Contributing Guide](https://github.com/modern-js-dev/modern.js/blob/main/CONTRIBUTING.md)\n"
80
101
  }
package/.eslintrc.js DELETED
@@ -1,8 +0,0 @@
1
- module.exports = {
2
- root: true,
3
- extends: ['@modern-js'],
4
- parserOptions: {
5
- tsconfigRootDir: __dirname,
6
- project: ['./tsconfig.json'],
7
- },
8
- };
@@ -1,12 +0,0 @@
1
- {
2
- "extends": "@modern-js/tsconfig/base",
3
- "compilerOptions": {
4
- "declaration": false,
5
- "jsx": "preserve",
6
- "baseUrl": "./",
7
- "isolatedModules": true,
8
- "sourceMap": true
9
- },
10
- "paths": {},
11
- "exclude": ["src/__test__/fixtures/**"]
12
- }
package/jest.config.js DELETED
@@ -1,8 +0,0 @@
1
- const sharedConfig = require('@scripts/jest-config');
2
-
3
- /** @type {import('@jest/types').Config.InitialOptions} */
4
- module.exports = {
5
- ...sharedConfig,
6
- testEnvironment: 'node',
7
- rootDir: __dirname,
8
- };
package/modern.config.js DELETED
@@ -1,2 +0,0 @@
1
- // https://modernjs.dev/docs/apis/config/overview
2
- module.exports = {};
package/src/constants.ts DELETED
@@ -1,31 +0,0 @@
1
- export const AGGRED_DIR = {
2
- mock: 'config/mock',
3
- server: 'server',
4
- api: 'api',
5
- shared: 'shared',
6
- lambda: 'lambda',
7
- };
8
-
9
- export enum ApiServerMode {
10
- func = 'function',
11
- frame = 'framework',
12
- }
13
-
14
- export const ERROR_DIGEST = {
15
- INIT: 'Server init error',
16
- ENOTF: 'Page could not be found',
17
- WARMUP: 'SSR warmup failed',
18
- EINTER: 'Internal server error',
19
- ERENDER: 'SSR render failed',
20
- EMICROINJ: 'Get micro-frontend info failed',
21
- };
22
-
23
- export const ERROR_PAGE_TEXT: Record<number, string> = {
24
- 404: 'This page could not be found.',
25
- 500: 'Internal Server Error.',
26
- };
27
-
28
- export const RUN_MODE = {
29
- FULL: 'full',
30
- TYPE: 'type',
31
- };
package/src/index.ts DELETED
@@ -1,19 +0,0 @@
1
- import { ModernServerOptions } from './type';
2
- import { Server } from './server';
3
-
4
- export { Server };
5
- export type { ServerConfig } from '@modern-js/server-core';
6
- export { ModernServer } from './server/modern-server';
7
- export { createProxyHandler } from './libs/proxy';
8
- export * from './type';
9
- export * from './constants';
10
-
11
- export default (options: ModernServerOptions): Promise<Server> => {
12
- if (options == null) {
13
- throw new Error('can not start mserver without options');
14
- }
15
-
16
- const server = new Server(options);
17
-
18
- return server.init();
19
- };
@@ -1,183 +0,0 @@
1
- import { IncomingMessage, ServerResponse } from 'http';
2
- import { URL } from 'url';
3
- import qs from 'querystring';
4
- import type {
5
- ModernServerContext as ModernServerContextInterface,
6
- Metrics,
7
- Logger,
8
- } from '@modern-js/types/server';
9
- import { toMessage } from '../../utils';
10
-
11
- export type ContextOptions = {
12
- logger?: Logger;
13
- metrics?: Metrics;
14
- };
15
-
16
- export class ModernServerContext implements ModernServerContextInterface {
17
- /**
18
- * http request
19
- */
20
- public req: IncomingMessage;
21
-
22
- /**
23
- * http response
24
- */
25
- public res: ServerResponse;
26
-
27
- /**
28
- * url params
29
- */
30
- public params: Record<string, string> = {};
31
-
32
- public logger: Logger;
33
-
34
- public metrics?: Metrics;
35
-
36
- public serverData: Record<string, any>;
37
-
38
- constructor(req: IncomingMessage, res: ServerResponse) {
39
- this.req = req;
40
- this.res = res;
41
- this.logger = req.logger;
42
- this.metrics = req.metrics;
43
- this.serverData = {};
44
-
45
- this.bind();
46
- }
47
-
48
- private bind() {
49
- const { req, res } = this as any;
50
- req.get = (key: string) => this.getReqHeader(key);
51
- res.set = (key: string, value: any) => this.res.setHeader(key, value);
52
- }
53
-
54
- public setParams(params: Record<string, string>) {
55
- this.params = params;
56
- }
57
-
58
- public setServerData(key: string, value: any) {
59
- this.serverData[key] = value;
60
- }
61
-
62
- public getReqHeader(key: string) {
63
- const { req } = this;
64
- const field = key.toLowerCase();
65
- switch (field) {
66
- case 'referer':
67
- case 'referrer':
68
- return req.headers.referrer || req.headers.referer || '';
69
- default:
70
- return req.headers[field] || '';
71
- }
72
- }
73
-
74
- /* request property */
75
- public get headers() {
76
- return this.req.headers;
77
- }
78
-
79
- public get method(): string {
80
- return this.req.method!;
81
- }
82
-
83
- public get url() {
84
- return this.req.url || '';
85
- }
86
-
87
- public set url(val) {
88
- this.req.url = val;
89
- }
90
-
91
- public get host() {
92
- let host = this.getReqHeader('X-Forwarded-Host');
93
- if (!host) {
94
- host = this.getReqHeader('Host');
95
- }
96
- return (host as string).split(/\s*,\s*/, 1)[0] || '';
97
- }
98
-
99
- public get protocol() {
100
- if ((this.req.socket as any).encrypted) {
101
- return 'https';
102
- }
103
-
104
- const proto = this.getReqHeader('X-Forwarded-Proto');
105
- return proto ? (proto as string).split(/\s*,\s*/, 1)[0] : 'http';
106
- }
107
-
108
- public get origin() {
109
- return `${this.protocol}://${this.host}`;
110
- }
111
-
112
- public get href() {
113
- return this.origin + this.url;
114
- }
115
-
116
- public get parsedURL() {
117
- const url = new URL(this.req.url!, this.origin);
118
- return url;
119
- }
120
-
121
- public get path() {
122
- return this.parsedURL.pathname;
123
- }
124
-
125
- public set path(p) {
126
- const url = new URL(this.req.url!, this.origin);
127
- // this should never happend
128
- if (!url || !p) {
129
- return;
130
- }
131
-
132
- if (url.pathname === p) {
133
- return;
134
- }
135
-
136
- url.pathname = p;
137
-
138
- this.url = url.toString();
139
- }
140
-
141
- public get querystring() {
142
- if (!this.req) {
143
- return '';
144
- }
145
- return this.parsedURL.search.replace(/^\?/, '') || '';
146
- }
147
-
148
- public get query() {
149
- const str = this.querystring;
150
- return qs.parse(str);
151
- }
152
-
153
- /* response property */
154
- public get status() {
155
- return this.res.statusCode;
156
- }
157
-
158
- public set status(statusCode) {
159
- this.res.statusCode = statusCode;
160
- }
161
-
162
- /**
163
- * 判断链接是否已经关闭
164
- */
165
- public resHasHandled(): boolean {
166
- return this.res.writableEnded;
167
- }
168
-
169
- public logInfo() {
170
- return {
171
- headers: this.headers,
172
- href: this.href,
173
- url: this.url,
174
- };
175
- }
176
-
177
- public error(dig: string, err: Error | string = '') {
178
- const message = toMessage(dig, err);
179
- const reqInfo = this.logInfo();
180
-
181
- this.logger.error(`${reqInfo.url} - ${message}`, reqInfo);
182
- }
183
- }
@@ -1,7 +0,0 @@
1
- import { IncomingMessage, ServerResponse } from 'http';
2
- import { ModernServerContext } from './context';
3
-
4
- export const createContext = (req: IncomingMessage, res: ServerResponse) =>
5
- new ModernServerContext(req, res);
6
-
7
- export { ModernServerContext };
@@ -1,42 +0,0 @@
1
- import { RouteMatchManager, RouteMatcher } from '../route';
2
-
3
- class RouteAPI {
4
- private readonly router: RouteMatchManager;
5
-
6
- private current: RouteMatcher;
7
-
8
- private readonly url: string;
9
-
10
- constructor(matched: RouteMatcher, router: RouteMatchManager, url: string) {
11
- this.current = matched;
12
- this.router = router;
13
- this.url = url;
14
- }
15
-
16
- public cur() {
17
- return this.current.generate(this.url);
18
- }
19
-
20
- public get(entryName: string) {
21
- const { router } = this;
22
- const matched = router.matchEntry(entryName);
23
- return matched ? matched.generate(this.url) : null;
24
- }
25
-
26
- public use(entryName: string) {
27
- const { router } = this;
28
- const matched = router.matchEntry(entryName);
29
- if (matched) {
30
- this.current = matched;
31
- return true;
32
- } else {
33
- return false;
34
- }
35
- }
36
- }
37
-
38
- export const createRouteAPI = (
39
- matched: RouteMatcher,
40
- router: RouteMatchManager,
41
- url: string,
42
- ) => new RouteAPI(matched, router, url);
@@ -1,53 +0,0 @@
1
- const RegList = {
2
- before: {
3
- head: '<head>',
4
- body: '<body>',
5
- },
6
- after: {
7
- head: '</head>',
8
- body: '</body>',
9
- },
10
- };
11
-
12
- class TemplateAPI {
13
- private content: string;
14
-
15
- constructor(content: string) {
16
- this.content = content;
17
- }
18
-
19
- public get() {
20
- return this.content;
21
- }
22
-
23
- public set(content: string) {
24
- this.content = content;
25
- }
26
-
27
- public prependHead(fragment: string) {
28
- const { head } = RegList.before;
29
- return this.replace(head, `${head}${fragment}`);
30
- }
31
-
32
- public appendHead(fragment: string) {
33
- const { head } = RegList.after;
34
- return this.replace(head, `${fragment}${head}`);
35
- }
36
-
37
- public prependBody(fragment: string) {
38
- const { body } = RegList.before;
39
- return this.replace(body, `${body}${fragment}`);
40
- }
41
-
42
- public appendBody(fragment: string) {
43
- const { body } = RegList.after;
44
- return this.replace(body, `${fragment}${body}`);
45
- }
46
-
47
- public replace(reg: RegExp | string, text: string) {
48
- this.content = this.content.replace(reg, text);
49
- return this;
50
- }
51
- }
52
-
53
- export const createTemplateAPI = (content: string) => new TemplateAPI(content);
@@ -1,59 +0,0 @@
1
- import * as path from 'path';
2
- import { compatRequire, fs, DEFAULT_SERVER_CONFIG } from '@modern-js/utils';
3
- import type { NormalizedConfig } from '@modern-js/core';
4
- import type { ServerConfig } from '@modern-js/server-core';
5
- import mergeDeep from 'merge-deep';
6
-
7
- export const getServerConfigPath = (
8
- distDirectory: string,
9
- serverConfigFile: string = DEFAULT_SERVER_CONFIG,
10
- ) => {
11
- const serverConfigPath = path.join(distDirectory, serverConfigFile);
12
- return `${serverConfigPath}.js`;
13
- };
14
-
15
- export const requireConfig = (serverConfigPath: string) => {
16
- if (fs.pathExistsSync(serverConfigPath)) {
17
- return compatRequire(serverConfigPath);
18
- }
19
-
20
- return {};
21
- };
22
-
23
- /**
24
- * 对配置进行合并,开发环境下,cliConfig 与 serverConfig 进行深合并
25
- * 生产环境下,resolvedConfig 与 serverConfig 进行深合并
26
- * resolvedConfigPath: 构建序列化后的 modern.config.js 文件路径
27
- */
28
- export const loadConfig = ({
29
- cliConfig,
30
- serverConfig,
31
- resolvedConfigPath,
32
- }: {
33
- cliConfig: NormalizedConfig;
34
- serverConfig: ServerConfig;
35
- resolvedConfigPath: string;
36
- }) => {
37
- let config = null;
38
- if (process.env.NODE_ENV === 'production') {
39
- const resolvedConfig = requireConfig(resolvedConfigPath);
40
- // cli config has a higher priority,because it's an argument passed in.
41
- config = mergeDeep(
42
- {
43
- ...resolvedConfig,
44
- plugins: [], // filter cli plugins
45
- },
46
- serverConfig,
47
- cliConfig,
48
- );
49
- } else {
50
- config = mergeDeep(
51
- {
52
- ...cliConfig,
53
- plugins: [],
54
- },
55
- serverConfig,
56
- );
57
- }
58
- return config;
59
- };
@@ -1,15 +0,0 @@
1
- import { Metrics } from '../type';
2
-
3
- const metrics: Metrics = {
4
- gauges() {
5
- // no impl
6
- },
7
- counter() {
8
- // no impl
9
- },
10
- timer() {
11
- // no impl
12
- },
13
- };
14
-
15
- export { metrics };
package/src/libs/proxy.ts DELETED
@@ -1,44 +0,0 @@
1
- import { createProxyMiddleware } from 'http-proxy-middleware';
2
- import { NextFunction, BffProxyOptions } from '@modern-js/types';
3
- import { formatProxyOptions } from '@modern-js/utils';
4
- import { debug } from '../utils';
5
- import { ModernServerContext } from './context';
6
-
7
- export type { BffProxyOptions };
8
-
9
- export const createProxyHandler = (proxyOptions?: BffProxyOptions) => {
10
- debug('createProxyHandler', proxyOptions);
11
- if (!proxyOptions) {
12
- return null;
13
- }
14
-
15
- // If it is not an array, it may be an object that uses the context attribute
16
- // or an object in the form of { source: ProxyDetail }
17
- const formatedProxy = formatProxyOptions(proxyOptions);
18
-
19
- const middlewares = formatedProxy.map(option => {
20
- const middleware = createProxyMiddleware(option.context!, option);
21
-
22
- // eslint-disable-next-line consistent-return
23
- return async (ctx: ModernServerContext, next: NextFunction) => {
24
- const { req, res } = ctx;
25
- const bypassUrl =
26
- typeof option.bypass === 'function'
27
- ? option.bypass(req, res, option)
28
- : null;
29
-
30
- // only false, no true
31
- if (typeof bypassUrl === 'boolean') {
32
- ctx.status = 404;
33
- return next();
34
- } else if (typeof bypassUrl === 'string') {
35
- ctx.url = bypassUrl;
36
- return next();
37
- }
38
-
39
- (middleware as any)(req, res, next);
40
- };
41
- });
42
-
43
- return middlewares;
44
- };