@umijs/server 4.0.0-beta.9 → 4.0.0-canary-20240513.3

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017-present ChenCheng (sorrycc@gmail.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
+ export { createServerRoutes } from './routes';
1
2
  export * from './server';
package/dist/index.js CHANGED
@@ -1,13 +1,32 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
11
8
  };
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- __exportStar(require("./server"), exports);
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ createServerRoutes: () => import_routes.createServerRoutes
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+ var import_routes = require("./routes");
27
+ __reExport(src_exports, require("./server"), module.exports);
28
+ // Annotate the CommonJS export names for ESM import in node:
29
+ 0 && (module.exports = {
30
+ createServerRoutes,
31
+ ...require("./server")
32
+ });
package/dist/routes.d.ts CHANGED
@@ -1,12 +1,15 @@
1
- import { IRoute, IRoutesById } from './types';
1
+ import { IRoute, IRouteCustom, IRoutesById } from './types';
2
2
  export declare function createServerRoutes(opts: {
3
3
  routesById: IRoutesById;
4
4
  parentId?: string;
5
- }): {
5
+ createRoute?: (opts: {
6
+ route: IRoute;
7
+ }) => IRouteCustom;
8
+ }): (IRouteCustom | {
6
9
  id: string;
7
10
  path: string | undefined;
8
11
  index: boolean | undefined;
9
- }[];
12
+ })[];
10
13
  export declare function createServerRoute(opts: {
11
14
  route: IRoute;
12
15
  }): {
package/dist/routes.js CHANGED
@@ -1,32 +1,55 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createServerRoute = exports.createServerRoutes = void 0;
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/routes.ts
20
+ var routes_exports = {};
21
+ __export(routes_exports, {
22
+ createServerRoute: () => createServerRoute,
23
+ createServerRoutes: () => createServerRoutes
24
+ });
25
+ module.exports = __toCommonJS(routes_exports);
4
26
  function createServerRoutes(opts) {
5
- const { routesById, parentId } = opts;
6
- return Object.keys(routesById)
7
- .filter((id) => routesById[id].parentId === parentId)
8
- .map((id) => {
9
- const route = createServerRoute({
10
- route: routesById[id],
11
- });
12
- const children = createServerRoutes({
13
- routesById,
14
- parentId: route.id,
15
- });
16
- if (children.length > 0) {
17
- // @ts-ignore
18
- route.children = children;
19
- }
20
- return route;
27
+ const { routesById, parentId, createRoute } = opts;
28
+ const createRouteFn = createRoute || createServerRoute;
29
+ return Object.keys(routesById).filter((id) => routesById[id].parentId === parentId).map((id) => {
30
+ const route = createRouteFn({
31
+ route: routesById[id]
21
32
  });
33
+ const children = createServerRoutes({
34
+ routesById,
35
+ parentId: route.id
36
+ });
37
+ if (children.length > 0) {
38
+ route.children = children;
39
+ }
40
+ return route;
41
+ });
22
42
  }
23
- exports.createServerRoutes = createServerRoutes;
24
43
  function createServerRoute(opts) {
25
- const { route } = opts;
26
- return {
27
- id: route.id,
28
- path: route.path,
29
- index: route.index,
30
- };
44
+ const { route } = opts;
45
+ return {
46
+ id: route.id,
47
+ path: route.path,
48
+ index: route.index
49
+ };
31
50
  }
32
- exports.createServerRoute = createServerRoute;
51
+ // Annotate the CommonJS export names for ESM import in node:
52
+ 0 && (module.exports = {
53
+ createServerRoute,
54
+ createServerRoutes
55
+ });
package/dist/scripts.js CHANGED
@@ -1,33 +1,61 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
4
10
  };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.normalizeScript = exports.normalizeScripts = void 0;
7
- const assert_1 = __importDefault(require("assert"));
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/scripts.ts
30
+ var scripts_exports = {};
31
+ __export(scripts_exports, {
32
+ normalizeScript: () => normalizeScript,
33
+ normalizeScripts: () => normalizeScripts
34
+ });
35
+ module.exports = __toCommonJS(scripts_exports);
36
+ var import_assert = __toESM(require("assert"));
8
37
  function normalizeScripts(scripts) {
9
- return scripts.map(normalizeScript);
38
+ return scripts.map(normalizeScript);
10
39
  }
11
- exports.normalizeScripts = normalizeScripts;
12
- const RE_URL = /^(http:|https:)?\/\//;
40
+ var RE_URL = /^(http:|https:)?\/\//;
13
41
  function normalizeScript(script) {
14
- if (typeof script === 'string') {
15
- const isUrl = RE_URL.test(script) ||
16
- script.startsWith('/') ||
17
- script.startsWith('./') ||
18
- script.startsWith('../');
19
- return isUrl
20
- ? {
21
- src: script,
22
- }
23
- : { content: script };
24
- }
25
- else if (typeof script === 'object') {
26
- (0, assert_1.default)(typeof script.src === 'string' || typeof script.content === 'string', `Script must have either a "src" or a "content" property.`);
27
- return script;
28
- }
29
- else {
30
- throw new Error(`Invalid script type: ${typeof script}`);
31
- }
42
+ if (typeof script === "string") {
43
+ const isUrl = RE_URL.test(script) || script.startsWith("/") && !script.startsWith("/*") || script.startsWith("./") || script.startsWith("../");
44
+ return isUrl ? {
45
+ src: script
46
+ } : { content: script };
47
+ } else if (typeof script === "object") {
48
+ (0, import_assert.default)(
49
+ typeof script.src === "string" || typeof script.content === "string",
50
+ `Script must have either a "src" or a "content" property.`
51
+ );
52
+ return script;
53
+ } else {
54
+ throw new Error(`Invalid script type: ${typeof script}`);
55
+ }
32
56
  }
33
- exports.normalizeScript = normalizeScript;
57
+ // Annotate the CommonJS export names for ESM import in node:
58
+ 0 && (module.exports = {
59
+ normalizeScript,
60
+ normalizeScripts
61
+ });
package/dist/server.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { RequestHandler } from 'express';
2
- interface IOpts {
1
+ import type { RequestHandler } from '@umijs/bundler-utils/compiled/express';
2
+ export interface IOpts {
3
+ base: string;
3
4
  routes: Record<string, {
4
5
  path: string;
5
6
  file: string;
@@ -9,16 +10,18 @@ interface IOpts {
9
10
  links?: Record<string, string>[];
10
11
  metas?: Record<string, string>[];
11
12
  styles?: (Record<string, string> | string)[];
12
- favicon?: string;
13
+ favicons?: string[];
14
+ title?: string;
13
15
  headScripts?: (Record<string, string> | string)[];
14
16
  scripts?: (Record<string, string> | string)[];
17
+ mountElementId?: string;
15
18
  esmScript?: boolean;
16
19
  modifyHTML?: (html: string, args: {
17
20
  path?: string;
18
21
  }) => Promise<string>;
22
+ historyType?: 'hash' | 'browser';
19
23
  }
20
24
  export declare function getMarkup(opts: Omit<IOpts, 'routes'> & {
21
25
  path?: string;
22
26
  }): Promise<string>;
23
27
  export declare function createRequestHandler(opts: IOpts): RequestHandler;
24
- export {};
package/dist/server.js CHANGED
@@ -1,113 +1,153 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
13
18
  };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.createRequestHandler = exports.getMarkup = void 0;
16
- const react_1 = __importDefault(require("react"));
17
- const server_1 = __importDefault(require("react-dom/server"));
18
- const react_router_dom_1 = require("react-router-dom");
19
- const routes_1 = require("./routes");
20
- const scripts_1 = require("./scripts");
21
- const styles_1 = require("./styles");
22
- function getMarkup(opts) {
23
- return __awaiter(this, void 0, void 0, function* () {
24
- // TODO: use real component
25
- let markup = server_1.default.renderToString(react_1.default.createElement('div', { id: 'root' }));
26
- function propsToString(opts) {
27
- return Object.keys(opts.props)
28
- .filter((key) => !(opts.filters || []).includes(key))
29
- .map((key) => `${key}=${JSON.stringify(opts.props[key])}`)
30
- .join(' ');
31
- }
32
- function getScriptContent(script) {
33
- const attrs = propsToString({
34
- props: script,
35
- filters: ['src', 'content'],
36
- });
37
- return script.src
38
- ? `<script${opts.esmScript ? ' type="module"' : ''} ${attrs} src="${script.src}"></script>`
39
- : `<script${opts.esmScript ? ' type="module"' : ''} ${attrs}>${script.content}</script>`;
40
- }
41
- function getStyleContent(style) {
42
- const attrs = propsToString({
43
- props: style,
44
- filters: ['src', 'content'],
45
- });
46
- return style.src
47
- ? `<link rel="stylesheet" ${attrs} src="${style.src}" />`
48
- : `<style ${attrs}>${style.content}</style>`;
49
- }
50
- function getTagContent(opts) {
51
- const attrs = propsToString({
52
- props: opts.attrs,
53
- });
54
- return `<${opts.tagName} ${attrs} />`;
55
- }
56
- const favicon = opts.favicon
57
- ? `<link rel="shortcut icon" href="${opts.favicon}">`
58
- : '';
59
- const metas = (opts.metas || []).map((meta) => getTagContent({ attrs: meta, tagName: 'meta' }));
60
- const links = (opts.links || []).map((link) => getTagContent({ attrs: link, tagName: 'link' }));
61
- const styles = (0, styles_1.normalizeStyles)(opts.styles || []).map(getStyleContent);
62
- const headScripts = (0, scripts_1.normalizeScripts)(opts.headScripts || []).map(getScriptContent);
63
- const scripts = (0, scripts_1.normalizeScripts)(opts.scripts || []).map(getScriptContent);
64
- markup = [
65
- `<!DOCTYPE html>
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/server.ts
30
+ var server_exports = {};
31
+ __export(server_exports, {
32
+ createRequestHandler: () => createRequestHandler,
33
+ getMarkup: () => getMarkup
34
+ });
35
+ module.exports = __toCommonJS(server_exports);
36
+ var import_react = __toESM(require("react"));
37
+ var import_server = __toESM(require("react-dom/server"));
38
+ var import_scripts = require("./scripts");
39
+ var import_styles = require("./styles");
40
+ async function getMarkup(opts) {
41
+ let markup = import_server.default.renderToString(
42
+ import_react.default.createElement("div", { id: opts.mountElementId || "root" })
43
+ );
44
+ function propsToString(opts2) {
45
+ return Object.keys(opts2.props).filter((key) => {
46
+ const isValidBoolean = opts2.props[key] !== false;
47
+ return !(opts2.filters || []).includes(key) && isValidBoolean;
48
+ }).map((key) => {
49
+ const value = opts2.props[key];
50
+ if (value === true) {
51
+ return `${key}`;
52
+ }
53
+ return `${key}=${JSON.stringify(value)}`;
54
+ }).join(" ");
55
+ }
56
+ function getScriptContent(script) {
57
+ const attrs = propsToString({
58
+ props: script,
59
+ filters: ["src", "content"]
60
+ });
61
+ const isEsmScript = opts.esmScript && !("type" in script);
62
+ return script.src ? `<script${isEsmScript ? ' type="module"' : ""} ${attrs} src="${script.src}"></script>` : `<script${isEsmScript ? ' type="module"' : ""} ${attrs}>${script.content}</script>`;
63
+ }
64
+ function getStyleContent(style) {
65
+ const attrs = propsToString({
66
+ props: style,
67
+ filters: ["src", "content"]
68
+ });
69
+ return style.src ? `<link rel="stylesheet" ${attrs} href="${style.src}" />` : `<style ${attrs}>${style.content}</style>`;
70
+ }
71
+ function getTagContent(opts2) {
72
+ const attrs = propsToString({
73
+ props: opts2.attrs
74
+ });
75
+ return `<${opts2.tagName} ${attrs} />`;
76
+ }
77
+ function withDefaultMetas(metas2 = []) {
78
+ const hasAttr = (key, value) => metas2.some((m) => {
79
+ var _a;
80
+ return value ? ((_a = m[key]) == null ? void 0 : _a.toLowerCase()) === value.toLowerCase() : m[key];
81
+ });
82
+ return [
83
+ !hasAttr("charset") && { charset: "utf-8" },
84
+ !hasAttr("name", "viewport") && {
85
+ name: "viewport",
86
+ content: "width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
87
+ },
88
+ !hasAttr("http-equiv", "X-UA-Compatible") && {
89
+ "http-equiv": "X-UA-Compatible",
90
+ content: "ie=edge"
91
+ },
92
+ ...metas2
93
+ ].filter(Boolean);
94
+ }
95
+ const favicons = [];
96
+ if (Array.isArray(opts.favicons)) {
97
+ opts.favicons.forEach((e) => {
98
+ favicons.push(`<link rel="shortcut icon" href="${e}">`);
99
+ });
100
+ }
101
+ const title = opts.title ? `<title>${opts.title}</title>` : "";
102
+ const metas = withDefaultMetas(opts.metas).map(
103
+ (meta) => getTagContent({ attrs: meta, tagName: "meta" })
104
+ );
105
+ const links = (opts.links || []).map(
106
+ (link) => getTagContent({ attrs: link, tagName: "link" })
107
+ );
108
+ const styles = (0, import_styles.normalizeStyles)(opts.styles || []).map(getStyleContent);
109
+ const headScripts = (0, import_scripts.normalizeScripts)(opts.headScripts || []).map(
110
+ getScriptContent
111
+ );
112
+ const scripts = (0, import_scripts.normalizeScripts)(opts.scripts || []).map(getScriptContent);
113
+ markup = [
114
+ `<!DOCTYPE html>
66
115
  <html>
67
- <head>
68
- <meta charset="UTF-8" />
69
- <meta
70
- name="viewport"
71
- content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
72
- />
73
- <meta http-equiv="X-UA-Compatible" content="ie=edge" />`,
74
- metas.join('\n'),
75
- favicon,
76
- links.join('\n'),
77
- styles.join('\n'),
78
- headScripts.join('\n'),
79
- `</head>
116
+ <head>`,
117
+ metas.join("\n"),
118
+ favicons.join("\n"),
119
+ title,
120
+ links.join("\n"),
121
+ styles.join("\n"),
122
+ headScripts.join("\n"),
123
+ `</head>
80
124
  <body>`,
81
- markup,
82
- scripts.join('\n'),
83
- `</body>
84
- </html>`,
85
- ]
86
- .filter(Boolean)
87
- .join('\n');
88
- if (opts.modifyHTML) {
89
- markup = yield opts.modifyHTML(markup, { path: opts.path });
90
- }
91
- return markup;
92
- });
125
+ markup,
126
+ scripts.join("\n"),
127
+ `</body>
128
+ </html>`
129
+ ].filter(Boolean).join("\n");
130
+ if (opts.modifyHTML) {
131
+ markup = await opts.modifyHTML(markup, { path: opts.path });
132
+ }
133
+ return markup;
93
134
  }
94
- exports.getMarkup = getMarkup;
95
135
  function createRequestHandler(opts) {
96
- return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
97
- // 匹配路由,不匹配走 next()
98
- // TODO: cache
99
- const routes = (0, routes_1.createServerRoutes)({
100
- routesById: opts.routes,
101
- });
102
- const matches = (0, react_router_dom_1.matchRoutes)(routes, req.path);
103
- if (matches) {
104
- res.set('Content-Type', 'text/html');
105
- const markup = yield getMarkup(Object.assign(Object.assign({}, opts), { path: req.path }));
106
- res.end(markup);
107
- }
108
- else {
109
- next();
110
- }
111
- });
136
+ return async (req, res, next) => {
137
+ var _a;
138
+ if (opts.historyType === "browser" && opts.base !== "/" && req.path === "/" && process.env.DEV_SERVER_REDIRECT !== "none") {
139
+ res.redirect(opts.base);
140
+ } else if (((_a = req.headers.accept) == null ? void 0 : _a.includes("text/html")) || req.headers.accept === "*/*" || req.path === opts.base) {
141
+ res.set("Content-Type", "text/html");
142
+ const markup = await getMarkup({ ...opts, path: req.path });
143
+ res.end(markup);
144
+ } else {
145
+ next();
146
+ }
147
+ };
112
148
  }
113
- exports.createRequestHandler = createRequestHandler;
149
+ // Annotate the CommonJS export names for ESM import in node:
150
+ 0 && (module.exports = {
151
+ createRequestHandler,
152
+ getMarkup
153
+ });
package/dist/ssr.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ /// <reference lib="webworker" />
2
+ import type { RequestHandler } from '@umijs/bundler-utils/compiled/express';
3
+ import React from 'react';
4
+ import type { IhtmlPageOpts, UmiRequest } from './types';
5
+ interface RouteLoaders {
6
+ [key: string]: () => Promise<any>;
7
+ }
8
+ export declare type ServerInsertedHTMLHook = (callbacks: () => React.ReactNode) => void;
9
+ interface CreateRequestServerlessOptions {
10
+ /**
11
+ * folder path for `build-manifest.json`
12
+ */
13
+ sourceDir?: string;
14
+ }
15
+ interface CreateRequestHandlerOptions extends CreateRequestServerlessOptions {
16
+ routesWithServerLoader: RouteLoaders;
17
+ pluginManager: any;
18
+ manifest: ((sourceDir?: string) => {
19
+ assets: Record<string, string>;
20
+ }) | {
21
+ assets: Record<string, string>;
22
+ };
23
+ getRoutes: (PluginManager: any) => any;
24
+ getClientRootComponent: (PluginManager: any) => any;
25
+ createHistory: (opts: any) => any;
26
+ helmetContext?: any;
27
+ ServerInsertedHTMLContext: React.Context<ServerInsertedHTMLHook | null>;
28
+ htmlPageOpts: IhtmlPageOpts;
29
+ renderFromRoot: boolean;
30
+ __SPECIAL_HTML_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: boolean;
31
+ mountElementId: string;
32
+ }
33
+ export declare function createMarkupGenerator(opts: CreateRequestHandlerOptions): (url: string) => Promise<unknown>;
34
+ declare type IExpressRequestHandlerArgs = Parameters<RequestHandler>;
35
+ declare type IWorkerRequestHandlerArgs = [
36
+ ev: FetchEvent,
37
+ opts?: {
38
+ modifyResponse?: (res: Response) => Promise<Response> | Response;
39
+ }
40
+ ];
41
+ export default function createRequestHandler(opts: CreateRequestHandlerOptions): (...args: IExpressRequestHandlerArgs | IWorkerRequestHandlerArgs) => Promise<void>;
42
+ export declare function createUmiHandler(opts: CreateRequestHandlerOptions): (req: UmiRequest, params?: CreateRequestHandlerOptions) => Promise<NodeJS.ReadableStream>;
43
+ export declare function createUmiServerLoader(opts: CreateRequestHandlerOptions): (req: UmiRequest) => Promise<any>;
44
+ export declare function createAppRootElement(opts: CreateRequestHandlerOptions): (...args: IExpressRequestHandlerArgs | IWorkerRequestHandlerArgs) => Promise<() => React.ReactElement<any, string | React.JSXElementConstructor<any>> | undefined>;
45
+ export {};