@dr.pogodin/react-utils 1.47.0-alpha.7 → 1.47.0-alpha.9
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/build/development/client/index.js +1 -1
- package/build/development/client/index.js.map +1 -1
- package/build/development/index.js +1 -11
- package/build/development/index.js.map +1 -1
- package/build/development/server/index.js +3 -6
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/utils/index.js +1 -1
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +1 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +1 -1
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +1 -1
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +1 -1
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +1 -1
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +1 -1
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +1 -1
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +1 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +1 -1
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/client/index.js +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/index.js +2 -6
- package/build/production/index.js.map +1 -1
- package/build/production/server/index.js +3 -3
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/utils/index.js +1 -1
- package/build/production/server/utils/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +1 -1
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +1 -1
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +1 -1
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +1 -1
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +0 -6
- package/build/types-code/server/index.d.ts +4 -9
- package/build/types-code/server/utils/index.d.ts +1 -1
- package/build/web/client/index.js +1 -1
- package/build/web/client/index.js.map +1 -1
- package/build/web/index.js +0 -12
- package/build/web/index.js.map +1 -1
- package/build/web/server/index.js +3 -6
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/utils/index.js +1 -1
- package/build/web/server/utils/index.js.map +1 -1
- package/build/web/shared/components/Button/index.js +1 -1
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +1 -1
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +1 -1
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +1 -1
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/PageLayout/index.js +1 -1
- package/build/web/shared/components/PageLayout/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/Throbber/index.js +1 -1
- package/build/web/shared/components/Throbber/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +1 -1
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +1 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/package.json +17 -6
- package/src/client/getInj.ts +0 -71
- package/src/client/index.tsx +0 -45
- package/src/client/init.ts +0 -52
- package/src/index.ts +0 -75
- package/src/server/Cache.ts +0 -61
- package/src/server/index.ts +0 -243
- package/src/server/renderer.tsx +0 -635
- package/src/server/server.ts +0 -330
- package/src/server/utils/errors.ts +0 -122
- package/src/server/utils/index.ts +0 -3
- package/src/shared/components/Button/index.tsx +0 -130
- package/src/shared/components/Button/style.scss +0 -54
- package/src/shared/components/Checkbox/index.tsx +0 -53
- package/src/shared/components/Checkbox/theme.scss +0 -63
- package/src/shared/components/GenericLink/index.tsx +0 -141
- package/src/shared/components/GenericLink/style.scss +0 -3
- package/src/shared/components/Input/index.tsx +0 -96
- package/src/shared/components/Input/theme.scss +0 -52
- package/src/shared/components/Link.tsx +0 -25
- package/src/shared/components/Modal/base-theme.scss +0 -38
- package/src/shared/components/Modal/index.tsx +0 -177
- package/src/shared/components/Modal/styles.scss +0 -3
- package/src/shared/components/NavLink.tsx +0 -18
- package/src/shared/components/PageLayout/base-theme.scss +0 -30
- package/src/shared/components/PageLayout/index.tsx +0 -51
- package/src/shared/components/TextArea/index.tsx +0 -139
- package/src/shared/components/TextArea/style.scss +0 -68
- package/src/shared/components/Throbber/index.tsx +0 -28
- package/src/shared/components/Throbber/theme.scss +0 -26
- package/src/shared/components/WithTooltip/Tooltip.tsx +0 -274
- package/src/shared/components/WithTooltip/default-theme.scss +0 -36
- package/src/shared/components/WithTooltip/index.tsx +0 -186
- package/src/shared/components/YouTubeVideo/base.scss +0 -15
- package/src/shared/components/YouTubeVideo/index.tsx +0 -73
- package/src/shared/components/YouTubeVideo/throbber.scss +0 -11
- package/src/shared/components/index.ts +0 -20
- package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
- package/src/shared/components/selectors/CustomDropdown/Options/style.scss +0 -6
- package/src/shared/components/selectors/CustomDropdown/index.tsx +0 -146
- package/src/shared/components/selectors/CustomDropdown/theme.scss +0 -118
- package/src/shared/components/selectors/NativeDropdown/index.tsx +0 -90
- package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -81
- package/src/shared/components/selectors/Switch/index.tsx +0 -74
- package/src/shared/components/selectors/Switch/theme.scss +0 -39
- package/src/shared/components/selectors/common.ts +0 -57
- package/src/shared/components/selectors/index.ts +0 -8
- package/src/shared/utils/config.ts +0 -59
- package/src/shared/utils/globalState.ts +0 -44
- package/src/shared/utils/index.ts +0 -45
- package/src/shared/utils/isomorphy/buildInfo.ts +0 -50
- package/src/shared/utils/isomorphy/environment-check.ts +0 -18
- package/src/shared/utils/isomorphy/index.ts +0 -36
- package/src/shared/utils/jest/E2eSsrEnv.ts +0 -304
- package/src/shared/utils/jest/global.ts +0 -17
- package/src/shared/utils/jest/index.ts +0 -215
- package/src/shared/utils/splitComponent.tsx +0 -284
- package/src/shared/utils/time.ts +0 -101
- package/src/shared/utils/webpack.ts +0 -80
- package/src/styles/_global/reset.css +0 -52
- package/src/styles/_mixins/fonts.scss +0 -40
- package/src/styles/_mixins/media.scss +0 -150
- package/src/styles/_mixins/typography.scss +0 -83
- package/src/styles/global.scss +0 -11
- package/src/styles/mixins.scss +0 -6
package/src/server/renderer.tsx
DELETED
|
@@ -1,635 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ExpressJS middleware for server-side rendering of a ReactJS app.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { Buffer } from 'node:buffer';
|
|
6
|
-
import { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';
|
|
7
|
-
import fs from 'node:fs';
|
|
8
|
-
import path from 'node:path';
|
|
9
|
-
import { Writable } from 'node:stream';
|
|
10
|
-
import { brotliCompress, brotliDecompress } from 'node:zlib';
|
|
11
|
-
|
|
12
|
-
import type { Request, RequestHandler } from 'express';
|
|
13
|
-
import type { ComponentType } from 'react';
|
|
14
|
-
import type { Configuration, Stats } from 'webpack';
|
|
15
|
-
import winston from 'winston';
|
|
16
|
-
|
|
17
|
-
import { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';
|
|
18
|
-
import { timer } from '@dr.pogodin/js-utils';
|
|
19
|
-
|
|
20
|
-
import {
|
|
21
|
-
cloneDeep,
|
|
22
|
-
defaults,
|
|
23
|
-
get,
|
|
24
|
-
mapValues,
|
|
25
|
-
} from 'lodash-es';
|
|
26
|
-
|
|
27
|
-
import config from 'config';
|
|
28
|
-
|
|
29
|
-
import { prerenderToNodeStream } from 'react-dom/static';
|
|
30
|
-
import { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';
|
|
31
|
-
import { StaticRouter } from 'react-router';
|
|
32
|
-
import serializeJs from 'serialize-javascript';
|
|
33
|
-
import { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';
|
|
34
|
-
|
|
35
|
-
import type { ChunkGroupsT, SsrContextT } from 'utils/globalState';
|
|
36
|
-
|
|
37
|
-
import Cache from './Cache';
|
|
38
|
-
|
|
39
|
-
// @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
|
|
40
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
41
|
-
const { SECRET, ...sanitizedConfig } = config;
|
|
42
|
-
|
|
43
|
-
// Note: These type definitions for logger are copied from Winston logger,
|
|
44
|
-
// then simplified to make it easier to fit an alternative logger into this
|
|
45
|
-
// interface.
|
|
46
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
47
|
-
interface LogMethodI {
|
|
48
|
-
// eslint-disable-next-line @typescript-eslint/prefer-function-type
|
|
49
|
-
(level: string, message: string, ...meta: unknown[]): void;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
53
|
-
interface LeveledLogMethodI {
|
|
54
|
-
// eslint-disable-next-line @typescript-eslint/prefer-function-type
|
|
55
|
-
(message: string, ...meta: unknown[]): void;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
59
|
-
export interface LoggerI {
|
|
60
|
-
debug: LeveledLogMethodI;
|
|
61
|
-
error: LeveledLogMethodI;
|
|
62
|
-
info: LeveledLogMethodI;
|
|
63
|
-
log: LogMethodI;
|
|
64
|
-
warn: LeveledLogMethodI;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export enum SCRIPT_LOCATIONS {
|
|
68
|
-
BODY_OPEN = 'BODY_OPEN',
|
|
69
|
-
DEFAULT = 'DEFAULT',
|
|
70
|
-
HEAD_OPEN = 'HEAD_OPEN',
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export class ServerSsrContext<StateT>
|
|
74
|
-
extends SsrContext<StateT>
|
|
75
|
-
implements SsrContextT<StateT> {
|
|
76
|
-
chunkGroups: ChunkGroupsT;
|
|
77
|
-
|
|
78
|
-
chunks: string[] = [];
|
|
79
|
-
|
|
80
|
-
redirectTo?: string;
|
|
81
|
-
|
|
82
|
-
req: Request;
|
|
83
|
-
|
|
84
|
-
status: number = 200;
|
|
85
|
-
|
|
86
|
-
constructor(
|
|
87
|
-
req: Request,
|
|
88
|
-
chunkGroups: ChunkGroupsT,
|
|
89
|
-
initialState?: StateT,
|
|
90
|
-
) {
|
|
91
|
-
super(cloneDeep(initialState) ?? ({} as StateT));
|
|
92
|
-
this.chunkGroups = chunkGroups;
|
|
93
|
-
this.req = req;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
type ScriptT = {
|
|
98
|
-
code: string;
|
|
99
|
-
location: SCRIPT_LOCATIONS;
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Reads build-time information about the app. This information is generated
|
|
104
|
-
* by our standard Webpack config for apps, and it is written into
|
|
105
|
-
* ".build-info" file in the context folder specified in Webpack config.
|
|
106
|
-
* At the moment, that file contains build timestamp and a random 32-bit key,
|
|
107
|
-
* suitable for cryptographical use.
|
|
108
|
-
* @param context Webpack context path used during the build.
|
|
109
|
-
* @return Resolves to the build-time information.
|
|
110
|
-
*/
|
|
111
|
-
function getBuildInfo(context: string) {
|
|
112
|
-
const url = path.resolve(context, '.build-info');
|
|
113
|
-
return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Attempts to read from disk the named chunk groups mapping generated
|
|
118
|
-
* by Webpack during the compilation.
|
|
119
|
-
* It will not work for development builds, where these stats should be captured
|
|
120
|
-
* via compilator callback.
|
|
121
|
-
* @param buildDir
|
|
122
|
-
* @return
|
|
123
|
-
*/
|
|
124
|
-
function readChunkGroupsJson(buildDir: string) {
|
|
125
|
-
const url = path.resolve(buildDir, '__chunk_groups__.json');
|
|
126
|
-
let res;
|
|
127
|
-
try {
|
|
128
|
-
res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;
|
|
129
|
-
} catch {
|
|
130
|
-
// TODO: Should we message the error here somehow?
|
|
131
|
-
res = null;
|
|
132
|
-
}
|
|
133
|
-
return res;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Prepares a new Cipher for data encryption.
|
|
138
|
-
* @param key Encryption key (32-bit random, Base64-encoded key is expected).
|
|
139
|
-
* @return Returns a tuple of:
|
|
140
|
-
* 1. cipher - a new Cipher, ready for encryption;
|
|
141
|
-
* 2. iv - initial vector used by the cipher.
|
|
142
|
-
*/
|
|
143
|
-
function prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {
|
|
144
|
-
const iv = randomBytes(16);
|
|
145
|
-
const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);
|
|
146
|
-
return [cipher, iv];
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
|
|
151
|
-
* are acceptable to the caller.
|
|
152
|
-
* @param req
|
|
153
|
-
*/
|
|
154
|
-
export function isBrotliAcceptable(req: Request): boolean {
|
|
155
|
-
const acceptable = req.get('accept-encoding');
|
|
156
|
-
if (acceptable) {
|
|
157
|
-
const ops = acceptable.split(',');
|
|
158
|
-
for (const op of ops) {
|
|
159
|
-
const [type, priority] = op.trim().split(';q=');
|
|
160
|
-
if ((type === '*' || type === 'br')
|
|
161
|
-
&& (!priority || parseFloat(priority) > 0)) {
|
|
162
|
-
return true;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
return false;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Given an array of extra script strings / objects, it returns an object with
|
|
171
|
-
* arrays of scripts to inject in different HTML template locations. During
|
|
172
|
-
* the script groupping it also filters out any empty scripts.
|
|
173
|
-
* @param {({
|
|
174
|
-
* code: string;
|
|
175
|
-
* location: string;
|
|
176
|
-
* }|string)[]} [scripts=[]]
|
|
177
|
-
* @return {{
|
|
178
|
-
* BODY_OPEN: string[];
|
|
179
|
-
* DEFAULT: string[];
|
|
180
|
-
* HEAD_OPEN: string[];
|
|
181
|
-
* }}
|
|
182
|
-
*/
|
|
183
|
-
function groupExtraScripts(scripts: Array<string | ScriptT> = []) {
|
|
184
|
-
const res = {
|
|
185
|
-
[SCRIPT_LOCATIONS.BODY_OPEN]: '',
|
|
186
|
-
[SCRIPT_LOCATIONS.DEFAULT]: '',
|
|
187
|
-
[SCRIPT_LOCATIONS.HEAD_OPEN]: '',
|
|
188
|
-
};
|
|
189
|
-
for (const script of scripts) {
|
|
190
|
-
if (typeof script === 'string') {
|
|
191
|
-
if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;
|
|
192
|
-
} else if (script.code) {
|
|
193
|
-
if (script.location in res) res[script.location] += script.code;
|
|
194
|
-
else throw Error(`Invalid location "${script.location}"`);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
return res;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Creates a new default (Winston) logger.
|
|
202
|
-
* @param {object} [options={}]
|
|
203
|
-
* @param {string} [options.defaultLogLevel='info']
|
|
204
|
-
* @return {object}
|
|
205
|
-
*/
|
|
206
|
-
export function newDefaultLogger({
|
|
207
|
-
defaultLogLevel = 'info',
|
|
208
|
-
} = {}): winston.Logger {
|
|
209
|
-
const { format, transports } = winston;
|
|
210
|
-
return winston.createLogger({
|
|
211
|
-
format: format.combine(
|
|
212
|
-
format.splat(),
|
|
213
|
-
format.timestamp(),
|
|
214
|
-
format.colorize(),
|
|
215
|
-
format.printf(
|
|
216
|
-
({
|
|
217
|
-
level,
|
|
218
|
-
message,
|
|
219
|
-
timestamp,
|
|
220
|
-
stack,
|
|
221
|
-
...rest
|
|
222
|
-
}) => {
|
|
223
|
-
let res = `${level}\t(at ${timestamp as string}):\t${message as string}`;
|
|
224
|
-
if (Object.keys(rest).length) {
|
|
225
|
-
res += `\n${JSON.stringify(rest, null, 2)}`;
|
|
226
|
-
}
|
|
227
|
-
if (stack) res += `\n${stack as string}`;
|
|
228
|
-
return res;
|
|
229
|
-
},
|
|
230
|
-
),
|
|
231
|
-
),
|
|
232
|
-
level: defaultLogLevel,
|
|
233
|
-
transports: [new transports.Console()],
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
export type ConfigT = {
|
|
238
|
-
[key: string]: ConfigT | string;
|
|
239
|
-
};
|
|
240
|
-
|
|
241
|
-
export type BeforeRenderResT = {
|
|
242
|
-
configToInject?: ConfigT;
|
|
243
|
-
extraScripts?: Array<ScriptT | string>;
|
|
244
|
-
initialState?: unknown;
|
|
245
|
-
};
|
|
246
|
-
|
|
247
|
-
export type BeforeRenderT = (
|
|
248
|
-
req: Request,
|
|
249
|
-
config: ConfigT,
|
|
250
|
-
) => BeforeRenderResT | Promise<BeforeRenderResT>;
|
|
251
|
-
|
|
252
|
-
type CacheRefT = {
|
|
253
|
-
key: string;
|
|
254
|
-
maxage?: number;
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
export type OptionsT = {
|
|
258
|
-
Application?: ComponentType;
|
|
259
|
-
beforeRender?: BeforeRenderT;
|
|
260
|
-
buildInfo?: BuildInfoT;
|
|
261
|
-
defaultLoggerLogLevel?: string;
|
|
262
|
-
favicon?: string;
|
|
263
|
-
logger?: LoggerI;
|
|
264
|
-
maxSsrRounds?: number;
|
|
265
|
-
noCsp?: boolean;
|
|
266
|
-
staticCacheSize?: number;
|
|
267
|
-
ssrTimeout?: number;
|
|
268
|
-
staticCacheController?: (req: Request) => CacheRefT | null | undefined;
|
|
269
|
-
};
|
|
270
|
-
|
|
271
|
-
/**
|
|
272
|
-
* Creates the middleware.
|
|
273
|
-
* @param webpackConfig
|
|
274
|
-
* @param options Additional options:
|
|
275
|
-
* @param [options.Application] The root ReactJS component of
|
|
276
|
-
* the app to use for the server-side rendering. When not provided
|
|
277
|
-
* the server-side rendering is disabled.
|
|
278
|
-
* @param [options.buildInfo] "Build info" object to use. If provided,
|
|
279
|
-
* it will be used, instead of trying to load from the filesystem the one
|
|
280
|
-
* generated by the Webpack build. It is intended for test environments,
|
|
281
|
-
* where passing this stuff via file system is no bueno.
|
|
282
|
-
* @param [options.favicon] `true` will include favicon
|
|
283
|
-
* link into the rendered HTML templates.
|
|
284
|
-
* @param [options.noCsp] `true` means that no
|
|
285
|
-
* Content-Security-Policy (CSP) is used by server, thus the renderer
|
|
286
|
-
* may cut a few corners.
|
|
287
|
-
* @param [options.maxSsrRounds=10] Maximum number of SSR rounds.
|
|
288
|
-
* @param [options.ssrTimeout=1000] SSR timeout in milliseconds,
|
|
289
|
-
* defaults to 1 second.
|
|
290
|
-
* @param [options.staticCacheSize=1.e7] The maximum
|
|
291
|
-
* static cache size in bytes. Defaults to ~10 MB.
|
|
292
|
-
* @param [options.staticCacheController] When given, it activates,
|
|
293
|
-
* and controls the static caching of generated HTML markup. When this function
|
|
294
|
-
* is provided, on each incoming request it is triggered with the request
|
|
295
|
-
* passed in as the argument. To attempt to serve the response from the cache
|
|
296
|
-
* it should return the object with the following fields:
|
|
297
|
-
* - `key: string` – the cache key for the response;
|
|
298
|
-
* - `maxage?: number` – the maximum age of cached result in ms.
|
|
299
|
-
* If undefined - infinite age is assumed.
|
|
300
|
-
* @return Created middleware.
|
|
301
|
-
*/
|
|
302
|
-
export default function factory(
|
|
303
|
-
webpackConfig: Configuration,
|
|
304
|
-
options: OptionsT,
|
|
305
|
-
): RequestHandler {
|
|
306
|
-
const ops: OptionsT = defaults({ ...options }, {
|
|
307
|
-
beforeRender: async () => Promise.resolve({}),
|
|
308
|
-
maxSsrRounds: 10,
|
|
309
|
-
ssrTimeout: 1000,
|
|
310
|
-
staticCacheSize: 1.e7,
|
|
311
|
-
});
|
|
312
|
-
|
|
313
|
-
// Note: in normal use the default logger is created and set in the root
|
|
314
|
-
// server function, and this initialization is for testing uses, where
|
|
315
|
-
// renderer is imported directly.
|
|
316
|
-
ops.logger ??= newDefaultLogger({
|
|
317
|
-
defaultLogLevel: ops.defaultLoggerLogLevel,
|
|
318
|
-
});
|
|
319
|
-
|
|
320
|
-
const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);
|
|
321
|
-
setBuildInfo(buildInfo);
|
|
322
|
-
|
|
323
|
-
// publicPath from webpack.output has a trailing slash at the end.
|
|
324
|
-
const { publicPath, path: outputPath } = webpackConfig.output!;
|
|
325
|
-
|
|
326
|
-
const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)
|
|
327
|
-
? `<link rel="manifest" href="${publicPath as string}manifest.json">` : '';
|
|
328
|
-
|
|
329
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
330
|
-
interface BufferWithNonce extends ArrayBuffer {
|
|
331
|
-
nonce: string;
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
const cache = ops.staticCacheController
|
|
335
|
-
? new Cache<{
|
|
336
|
-
buffer: BufferWithNonce;
|
|
337
|
-
status: number;
|
|
338
|
-
}>(ops.staticCacheSize!)
|
|
339
|
-
: null;
|
|
340
|
-
|
|
341
|
-
const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);
|
|
342
|
-
|
|
343
|
-
// TODO: Look at it later.
|
|
344
|
-
// eslint-disable-next-line complexity
|
|
345
|
-
return async (req, res, next) => {
|
|
346
|
-
try {
|
|
347
|
-
// Ensures any caches always revalidate HTML markup before reuse.
|
|
348
|
-
res.set('Cache-Control', 'no-cache');
|
|
349
|
-
|
|
350
|
-
res.cookie('csrfToken', req.csrfToken());
|
|
351
|
-
|
|
352
|
-
let cacheRef: CacheRefT | null | undefined;
|
|
353
|
-
if (cache) {
|
|
354
|
-
cacheRef = ops.staticCacheController!(req);
|
|
355
|
-
if (cacheRef) {
|
|
356
|
-
const data = cache.get(cacheRef);
|
|
357
|
-
if (data !== null) {
|
|
358
|
-
const { buffer, status } = data;
|
|
359
|
-
if (ops.noCsp && isBrotliAcceptable(req)) {
|
|
360
|
-
res.set('Content-Type', 'text/html');
|
|
361
|
-
res.set('Content-Encoding', 'br');
|
|
362
|
-
if (status !== 200) res.status(status);
|
|
363
|
-
res.send(buffer);
|
|
364
|
-
} else {
|
|
365
|
-
await new Promise<void>((done, failed) => {
|
|
366
|
-
brotliDecompress(buffer, (error, html) => {
|
|
367
|
-
if (error) failed(error);
|
|
368
|
-
else {
|
|
369
|
-
let h = html.toString();
|
|
370
|
-
if (!ops.noCsp) {
|
|
371
|
-
// TODO: Starting from Node v15 we'll be able to use string's
|
|
372
|
-
// .replaceAll() method instead relying on reg. expression for
|
|
373
|
-
// global matching.
|
|
374
|
-
const regex = new RegExp(buffer.nonce, 'g');
|
|
375
|
-
|
|
376
|
-
// TODO: It should be implemented more careful.
|
|
377
|
-
h = h.replace(regex, (req as unknown as {
|
|
378
|
-
nonce: string;
|
|
379
|
-
}).nonce);
|
|
380
|
-
}
|
|
381
|
-
if (status !== 200) res.status(status);
|
|
382
|
-
res.send(h);
|
|
383
|
-
done();
|
|
384
|
-
}
|
|
385
|
-
});
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);
|
|
394
|
-
const { configToInject, extraScripts, initialState } = await brr;
|
|
395
|
-
|
|
396
|
-
const [cipher, iv] = prepareCipher(buildInfo.key);
|
|
397
|
-
|
|
398
|
-
let helmet: HelmetDataContext['helmet'];
|
|
399
|
-
|
|
400
|
-
// Gets the mapping between code chunk names and their asset files.
|
|
401
|
-
// These data come from the Webpack compilation, either from the stats
|
|
402
|
-
// attached to the request (in dev mode), or from a file output during
|
|
403
|
-
// the build (in prod mode).
|
|
404
|
-
let chunkGroups: ChunkGroupsT;
|
|
405
|
-
const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;
|
|
406
|
-
if (webpackStats) {
|
|
407
|
-
chunkGroups = mapValues(
|
|
408
|
-
webpackStats.toJson({
|
|
409
|
-
all: false,
|
|
410
|
-
chunkGroups: true,
|
|
411
|
-
}).namedChunkGroups,
|
|
412
|
-
(item) => item.assets?.map(({ name }: { name: string }) => name)
|
|
413
|
-
?? [],
|
|
414
|
-
);
|
|
415
|
-
} else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;
|
|
416
|
-
else chunkGroups = {};
|
|
417
|
-
|
|
418
|
-
/* Optional server-side rendering. */
|
|
419
|
-
const App = ops.Application;
|
|
420
|
-
let appHtmlMarkup: string = '';
|
|
421
|
-
const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);
|
|
422
|
-
let stream: NodeJS.ReadableStream;
|
|
423
|
-
if (App) {
|
|
424
|
-
const ssrStart = Date.now();
|
|
425
|
-
|
|
426
|
-
// TODO: Somehow, without it TS does not realise that
|
|
427
|
-
// App has been checked to exist.
|
|
428
|
-
const App2 = App;
|
|
429
|
-
|
|
430
|
-
const renderPass = async () => new Promise<NodeJS.ReadableStream>(
|
|
431
|
-
(resolveArg, rejectArg) => {
|
|
432
|
-
ssrContext.chunks = [];
|
|
433
|
-
|
|
434
|
-
// NOTE: JS does not have problems if resolve() and reject() methods
|
|
435
|
-
// of a Promise are called multiple times, with different arguments;
|
|
436
|
-
// it only respects the first call, and ignores subsequent ones.
|
|
437
|
-
// We, however, really want to assert that here, to safeguard against
|
|
438
|
-
// any future problems due to unexpected internal changes in React,
|
|
439
|
-
// if any.
|
|
440
|
-
let error: unknown;
|
|
441
|
-
|
|
442
|
-
const resolve = (arg: NodeJS.ReadableStream) => {
|
|
443
|
-
if (error !== undefined) throw Error('Internal error');
|
|
444
|
-
error = null;
|
|
445
|
-
resolveArg(arg);
|
|
446
|
-
};
|
|
447
|
-
|
|
448
|
-
const reject = (arg: unknown) => {
|
|
449
|
-
if (error !== undefined && error !== arg) {
|
|
450
|
-
throw Error('Internal error');
|
|
451
|
-
}
|
|
452
|
-
error = arg;
|
|
453
|
-
rejectArg(arg as Error);
|
|
454
|
-
};
|
|
455
|
-
|
|
456
|
-
// TODO: prerenderToNodeStream has (abort) "signal" option,
|
|
457
|
-
// and we should wire it up to the SSR timeout below.
|
|
458
|
-
const helmetContext = {} as HelmetDataContext;
|
|
459
|
-
void prerenderToNodeStream(
|
|
460
|
-
<GlobalStateProvider
|
|
461
|
-
initialState={ssrContext.state}
|
|
462
|
-
ssrContext={ssrContext}
|
|
463
|
-
>
|
|
464
|
-
<StaticRouter location={req.url}>
|
|
465
|
-
<HelmetProvider context={helmetContext}>
|
|
466
|
-
<App2 />
|
|
467
|
-
</HelmetProvider>
|
|
468
|
-
</StaticRouter>
|
|
469
|
-
</GlobalStateProvider>,
|
|
470
|
-
{ onError: reject },
|
|
471
|
-
).then((result) => {
|
|
472
|
-
({ helmet } = helmetContext);
|
|
473
|
-
resolve(result.prelude);
|
|
474
|
-
}).catch(reject);
|
|
475
|
-
},
|
|
476
|
-
);
|
|
477
|
-
|
|
478
|
-
let ssrRound = 0;
|
|
479
|
-
let bailed = false;
|
|
480
|
-
for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {
|
|
481
|
-
stream = await renderPass();
|
|
482
|
-
|
|
483
|
-
if (!ssrContext.dirty) break;
|
|
484
|
-
|
|
485
|
-
const timeout = ops.ssrTimeout! + ssrStart - Date.now();
|
|
486
|
-
bailed = timeout <= 0 || !await Promise.race([
|
|
487
|
-
Promise.allSettled(ssrContext.pending),
|
|
488
|
-
timer(timeout).then(() => false),
|
|
489
|
-
]);
|
|
490
|
-
if (bailed) break;
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
let logMsg;
|
|
494
|
-
if (ssrContext.dirty) {
|
|
495
|
-
// NOTE: In the case of incomplete SSR one more round is necessary
|
|
496
|
-
// to ensure the correct hydration when some pending promises have
|
|
497
|
-
// resolved and placed their data into the initial global state.
|
|
498
|
-
stream = await renderPass();
|
|
499
|
-
|
|
500
|
-
logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`
|
|
501
|
-
: `SSR bailed out after ${ops.maxSsrRounds} round(s)`;
|
|
502
|
-
} else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;
|
|
503
|
-
|
|
504
|
-
ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);
|
|
505
|
-
|
|
506
|
-
if (ssrContext.redirectTo) {
|
|
507
|
-
res.redirect(ssrContext.status, ssrContext.redirectTo);
|
|
508
|
-
return;
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
await new Promise((ready) => {
|
|
512
|
-
stream!.pipe(new Writable({
|
|
513
|
-
destroy: ready,
|
|
514
|
-
write: (chunk: { toString: () => string }, _, done) => {
|
|
515
|
-
appHtmlMarkup += chunk.toString();
|
|
516
|
-
done();
|
|
517
|
-
},
|
|
518
|
-
}));
|
|
519
|
-
});
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
/* Encrypts data to be injected into HTML.
|
|
523
|
-
* Keep in mind, that this encryption is no way secure: as the JS bundle
|
|
524
|
-
* contains decryption key and is able to decode it at the client side.
|
|
525
|
-
* Hovewer, for a number of reasons, encryption of injected data is still
|
|
526
|
-
* better than injection of a plain text. */
|
|
527
|
-
const payload = serializeJs({
|
|
528
|
-
CHUNK_GROUPS: chunkGroups,
|
|
529
|
-
CONFIG: configToInject ?? sanitizedConfig,
|
|
530
|
-
ISTATE: ssrContext.state,
|
|
531
|
-
}, {
|
|
532
|
-
ignoreFunction: true,
|
|
533
|
-
unsafe: true,
|
|
534
|
-
});
|
|
535
|
-
|
|
536
|
-
const INJ = Buffer.concat([
|
|
537
|
-
iv,
|
|
538
|
-
cipher.update(payload, 'utf8'),
|
|
539
|
-
cipher.final(),
|
|
540
|
-
]).toString('base64');
|
|
541
|
-
|
|
542
|
-
const chunkSet = new Set<string>();
|
|
543
|
-
|
|
544
|
-
// TODO: "main" chunk has to be added explicitly,
|
|
545
|
-
// because unlike all other chunks they are not managed by <CodeSplit>
|
|
546
|
-
// component, thus they are not added to the ssrContext.chunks
|
|
547
|
-
// automatically. Actually, names of these entry chunks should be
|
|
548
|
-
// read from Wepback config, as the end user may customize them,
|
|
549
|
-
// remove or add other entry points, but it requires additional
|
|
550
|
-
// efforts to figure out how to automatically order them right,
|
|
551
|
-
// thus for now this handles the default config.
|
|
552
|
-
[
|
|
553
|
-
'main',
|
|
554
|
-
...ssrContext.chunks,
|
|
555
|
-
].forEach((chunk) => {
|
|
556
|
-
const assets = chunkGroups[chunk];
|
|
557
|
-
if (assets) assets.forEach((asset) => chunkSet.add(asset));
|
|
558
|
-
});
|
|
559
|
-
|
|
560
|
-
let styleChunkString = '';
|
|
561
|
-
let scriptChunkString = '';
|
|
562
|
-
chunkSet.forEach((chunk) => {
|
|
563
|
-
if (chunk.endsWith('.css')) {
|
|
564
|
-
styleChunkString += `<link href="${publicPath as string}${chunk}" rel="stylesheet">`;
|
|
565
|
-
} else if (
|
|
566
|
-
chunk.endsWith('.js')
|
|
567
|
-
// In dev mode HMR adds JS updates into asset arrays,
|
|
568
|
-
// and they (updates) should be ignored.
|
|
569
|
-
&& !chunk.endsWith('.hot-update.js')
|
|
570
|
-
) {
|
|
571
|
-
scriptChunkString += `<script src="${publicPath as string}${chunk}" type="application/javascript"></script>`;
|
|
572
|
-
}
|
|
573
|
-
});
|
|
574
|
-
|
|
575
|
-
const grouppedExtraScripts = groupExtraScripts(extraScripts);
|
|
576
|
-
|
|
577
|
-
const faviconLink = ops.favicon
|
|
578
|
-
? '<link rel="shortcut icon" href="/favicon.ico">'
|
|
579
|
-
: '';
|
|
580
|
-
|
|
581
|
-
const html = `<!DOCTYPE html>
|
|
582
|
-
<html lang="en">
|
|
583
|
-
<head>
|
|
584
|
-
${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}
|
|
585
|
-
${helmet?.title.toString() ?? ''}
|
|
586
|
-
${helmet?.meta.toString() ?? ''}
|
|
587
|
-
<meta name="theme-color" content="#FFFFFF">
|
|
588
|
-
${manifestLink}
|
|
589
|
-
${helmet?.link.toString() ?? ''}${styleChunkString}
|
|
590
|
-
${faviconLink}
|
|
591
|
-
<meta charset="utf-8">
|
|
592
|
-
<meta
|
|
593
|
-
content="width=device-width,initial-scale=1.0"
|
|
594
|
-
name="viewport"
|
|
595
|
-
>
|
|
596
|
-
<meta itemprop="drpruinj" content="${INJ}">
|
|
597
|
-
</head>
|
|
598
|
-
<body>
|
|
599
|
-
${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}
|
|
600
|
-
<div id="react-view">${appHtmlMarkup}</div>
|
|
601
|
-
${scriptChunkString}
|
|
602
|
-
${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}
|
|
603
|
-
</body>
|
|
604
|
-
</html>`;
|
|
605
|
-
|
|
606
|
-
const status = ssrContext.status || 200;
|
|
607
|
-
if (status !== 200) res.status(status);
|
|
608
|
-
|
|
609
|
-
if (cacheRef && status < 500) {
|
|
610
|
-
// Note: waiting for the caching to complete is not strictly necessary,
|
|
611
|
-
// but it greately simplifies testing, and error reporting.
|
|
612
|
-
await new Promise<void>((done, failed) => {
|
|
613
|
-
brotliCompress(html, (error, buffer) => {
|
|
614
|
-
if (error) failed(error);
|
|
615
|
-
else {
|
|
616
|
-
const b = buffer as unknown as BufferWithNonce;
|
|
617
|
-
b.nonce = (req as unknown as {
|
|
618
|
-
nonce: string;
|
|
619
|
-
}).nonce;
|
|
620
|
-
cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);
|
|
621
|
-
done();
|
|
622
|
-
}
|
|
623
|
-
});
|
|
624
|
-
});
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
// Note: as caching code above may throw in some cases, sending response
|
|
628
|
-
// before it completes will likely hide the error, making it difficult
|
|
629
|
-
// to debug. Thus, at least for now, lets send response after it.
|
|
630
|
-
res.send(html);
|
|
631
|
-
} catch (error) {
|
|
632
|
-
next(error);
|
|
633
|
-
}
|
|
634
|
-
};
|
|
635
|
-
}
|