@dr.pogodin/react-utils 1.42.0 → 1.42.1
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/babel.config.js +3 -0
- package/bin/build.js +5 -8
- package/bin/setup.js +2 -1
- package/build/development/client/getInj.js +7 -2
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +1 -2
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js +16 -13
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +4 -1
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js +5 -9
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +14 -11
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +36 -40
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +19 -12
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/shared/components/Button/index.js +2 -3
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +3 -1
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +13 -6
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +5 -1
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js +5 -6
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/MetaTags.js +31 -24
- package/build/development/shared/components/MetaTags.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +13 -6
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +6 -6
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +6 -3
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +35 -39
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +27 -21
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +4 -3
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +4 -5
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -9
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +3 -5
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +21 -20
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/config.js +6 -3
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js +6 -0
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/development/shared/utils/isomorphy/environment-check.js +6 -1
- package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/development/shared/utils/isomorphy/index.js +1 -3
- package/build/development/shared/utils/isomorphy/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +26 -17
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/global.js +0 -7
- package/build/development/shared/utils/jest/global.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +15 -4
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +37 -19
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +3 -3
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/shared/utils/webpack.js +11 -11
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/development/web.bundle.js +30 -30
- package/build/production/client/getInj.js +4 -2
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +2 -2
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +4 -2
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +2 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js +1 -2
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +9 -5
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +24 -21
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +13 -8
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.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/GenericLink/index.js +6 -4
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +3 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js +3 -1
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/MetaTags.js +5 -2
- package/build/production/shared/components/MetaTags.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +6 -2
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +4 -1
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +4 -4
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +37 -38
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +4 -4
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +3 -2
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
- 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/production/shared/utils/config.js +6 -4
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js +4 -1
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/production/shared/utils/isomorphy/environment-check.js +5 -1
- package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/production/shared/utils/isomorphy/index.js +1 -3
- package/build/production/shared/utils/isomorphy/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +15 -8
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/global.js +1 -1
- package/build/production/shared/utils/jest/global.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +13 -5
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +16 -8
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +2 -2
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js +5 -2
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/production/web.bundle.js +1 -1
- package/build/production/web.bundle.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +1 -1
- package/build/types-code/client/index.d.ts +2 -2
- package/build/types-code/client/init.d.ts +1 -1
- package/build/types-code/index.d.ts +6 -5
- package/build/types-code/server/Cache.d.ts +1 -2
- package/build/types-code/server/index.d.ts +4 -5
- package/build/types-code/server/renderer.d.ts +8 -10
- package/build/types-code/server/server.d.ts +3 -5
- package/build/types-code/server/utils/errors.d.ts +1 -1
- package/build/types-code/shared/components/Button/index.d.ts +2 -2
- package/build/types-code/shared/components/TextArea/index.d.ts +3 -3
- package/build/types-code/shared/components/WithTooltip/Tooltip.d.ts +7 -1
- package/build/types-code/shared/components/index.d.ts +12 -12
- package/build/types-code/shared/utils/config.d.ts +1 -1
- package/build/types-code/shared/utils/globalState.d.ts +3 -6
- package/build/types-code/shared/utils/isomorphy/index.d.ts +1 -3
- package/build/types-code/shared/utils/jest/E2eSsrEnv.d.ts +1 -1
- package/build/types-code/shared/utils/jest/global.d.ts +4 -4
- package/build/types-code/shared/utils/jest/index.d.ts +2 -2
- package/build/types-code/shared/utils/webpack.d.ts +1 -1
- package/config/babel/node-ssr.d.ts +3 -2
- package/config/babel/node-ssr.js +5 -7
- package/config/babel/webpack.d.ts +3 -11
- package/config/babel/webpack.js +15 -15
- package/config/eslint/default.mjs +32 -0
- package/config/jest/default.js +10 -6
- package/config/jest/resolver.js +2 -0
- package/config/jest/setup.js +2 -2
- package/config/stylelint/default.js +3 -0
- package/config/webpack/app-base.d.ts +0 -6
- package/config/webpack/app-base.js +64 -70
- package/config/webpack/app-development.d.ts +2 -2
- package/config/webpack/app-development.js +8 -12
- package/config/webpack/app-production.js +1 -0
- package/config/webpack/lib-base.js +20 -18
- package/config/webpack/lib-development.js +1 -0
- package/config/webpack/lib-production.js +1 -0
- package/config/workbox/default.js +2 -5
- package/dev-styles.js +1 -0
- package/eslint.config.mjs +13 -0
- package/node-entry.js +7 -2
- package/null.js +1 -0
- package/package.json +17 -25
- package/prod-styles.js +1 -0
- package/src/client/getInj.ts +8 -3
- package/src/client/index.tsx +4 -4
- package/src/client/init.ts +18 -15
- package/src/index.ts +8 -3
- package/src/server/Cache.ts +7 -15
- package/src/server/index.ts +30 -21
- package/src/server/renderer.tsx +76 -66
- package/src/server/server.ts +38 -20
- package/src/server/utils/errors.ts +6 -3
- package/src/shared/components/Button/index.tsx +4 -5
- package/src/shared/components/Checkbox/index.tsx +10 -7
- package/src/shared/components/GenericLink/index.tsx +14 -7
- package/src/shared/components/Input/index.tsx +4 -1
- package/src/shared/components/Link.tsx +9 -5
- package/src/shared/components/MetaTags.tsx +21 -15
- package/src/shared/components/Modal/index.tsx +12 -11
- package/src/shared/components/NavLink.tsx +10 -5
- package/src/shared/components/TextArea/index.tsx +17 -9
- package/src/shared/components/WithTooltip/{Tooltip.tsx → Tooltip.ts} +35 -39
- package/src/shared/components/WithTooltip/index.tsx +36 -30
- package/src/shared/components/YouTubeVideo/index.tsx +10 -6
- package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +5 -6
- package/src/shared/components/selectors/CustomDropdown/index.tsx +10 -14
- package/src/shared/components/selectors/NativeDropdown/index.tsx +5 -7
- package/src/shared/components/selectors/Switch/index.tsx +19 -17
- package/src/shared/utils/config.ts +12 -5
- package/src/shared/utils/globalState.ts +8 -5
- package/src/shared/utils/isomorphy/buildInfo.ts +1 -1
- package/src/shared/utils/isomorphy/environment-check.ts +5 -1
- package/src/shared/utils/isomorphy/index.ts +4 -6
- package/src/shared/utils/jest/E2eSsrEnv.ts +64 -39
- package/src/shared/utils/jest/global.ts +6 -8
- package/src/shared/utils/jest/{index.tsx → index.ts} +25 -12
- package/src/shared/utils/splitComponent.tsx +44 -25
- package/src/shared/utils/time.ts +16 -9
- package/src/shared/utils/webpack.ts +19 -14
- package/webpack.config.ts +36 -10
- package/config/eslint/default.json +0 -30
- package/config/eslint/jest.json +0 -19
- package/config/eslint/typescript.js +0 -46
|
@@ -10,7 +10,6 @@ exports.isBrotliAcceptable = isBrotliAcceptable;
|
|
|
10
10
|
exports.newDefaultLogger = newDefaultLogger;
|
|
11
11
|
var _fs = _interopRequireDefault(require("fs"));
|
|
12
12
|
var _path = _interopRequireDefault(require("path"));
|
|
13
|
-
require("react");
|
|
14
13
|
var _stream = require("stream");
|
|
15
14
|
var _zlib = require("zlib");
|
|
16
15
|
var _winston = _interopRequireDefault(require("winston"));
|
|
@@ -24,8 +23,6 @@ var _reactHelmet = require("@dr.pogodin/react-helmet");
|
|
|
24
23
|
var _reactRouter = require("react-router");
|
|
25
24
|
var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
|
|
26
25
|
var _buildInfo = require("../shared/utils/isomorphy/buildInfo");
|
|
27
|
-
require("../shared/utils/globalState");
|
|
28
|
-
require("webpack");
|
|
29
26
|
var _Cache = _interopRequireDefault(require("./Cache"));
|
|
30
27
|
var _jsxRuntime = require("react/jsx-runtime");
|
|
31
28
|
/**
|
|
@@ -37,7 +34,11 @@ const sanitizedConfig = (0, _lodash.omit)(_config.default, 'SECRET');
|
|
|
37
34
|
// Note: These type definitions for logger are copied from Winston logger,
|
|
38
35
|
// then simplified to make it easier to fit an alternative logger into this
|
|
39
36
|
// interface.
|
|
40
|
-
// eslint-disable-next-line @typescript-eslint/
|
|
37
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
38
|
+
|
|
39
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
40
|
+
|
|
41
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
41
42
|
let SCRIPT_LOCATIONS = exports.SCRIPT_LOCATIONS = /*#__PURE__*/function (SCRIPT_LOCATIONS) {
|
|
42
43
|
SCRIPT_LOCATIONS["BODY_OPEN"] = "BODY_OPEN";
|
|
43
44
|
SCRIPT_LOCATIONS["DEFAULT"] = "DEFAULT";
|
|
@@ -48,7 +49,7 @@ class ServerSsrContext extends _reactGlobalState.SsrContext {
|
|
|
48
49
|
chunks = [];
|
|
49
50
|
status = 200;
|
|
50
51
|
constructor(req, chunkGroups, initialState) {
|
|
51
|
-
super((0, _lodash.cloneDeep)(initialState)
|
|
52
|
+
super((0, _lodash.cloneDeep)(initialState) ?? {});
|
|
52
53
|
this.chunkGroups = chunkGroups;
|
|
53
54
|
this.req = req;
|
|
54
55
|
}
|
|
@@ -81,7 +82,8 @@ function readChunkGroupsJson(buildDir) {
|
|
|
81
82
|
let res;
|
|
82
83
|
try {
|
|
83
84
|
res = JSON.parse(_fs.default.readFileSync(url, 'utf8'));
|
|
84
|
-
} catch
|
|
85
|
+
} catch {
|
|
86
|
+
// TODO: Should we message the error here somehow?
|
|
85
87
|
res = null;
|
|
86
88
|
}
|
|
87
89
|
return res;
|
|
@@ -95,7 +97,7 @@ function readChunkGroupsJson(buildDir) {
|
|
|
95
97
|
* 1. cipher - a new Cipher, ready for encryption;
|
|
96
98
|
* 2. iv - initial vector used by the cipher.
|
|
97
99
|
*/
|
|
98
|
-
function prepareCipher(key) {
|
|
100
|
+
async function prepareCipher(key) {
|
|
99
101
|
return new Promise((resolve, reject) => {
|
|
100
102
|
_nodeForge.default.random.getBytes(32, (err, iv) => {
|
|
101
103
|
if (err) reject(err);else {
|
|
@@ -115,21 +117,16 @@ function prepareCipher(key) {
|
|
|
115
117
|
/**
|
|
116
118
|
* Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
|
|
117
119
|
* are acceptable to the caller.
|
|
118
|
-
* @param
|
|
119
|
-
* @return {boolean}
|
|
120
|
-
* @ignore
|
|
120
|
+
* @param req
|
|
121
121
|
*/
|
|
122
122
|
function isBrotliAcceptable(req) {
|
|
123
123
|
const acceptable = req.get('accept-encoding');
|
|
124
124
|
if (acceptable) {
|
|
125
125
|
const ops = acceptable.split(',');
|
|
126
|
-
for (
|
|
127
|
-
const
|
|
128
|
-
if (
|
|
129
|
-
|
|
130
|
-
if ((type === '*' || type === 'br') && (!priority || parseFloat(priority) > 0)) {
|
|
131
|
-
return true;
|
|
132
|
-
}
|
|
126
|
+
for (const op of ops) {
|
|
127
|
+
const [type, priority] = op.trim().split(';q=');
|
|
128
|
+
if ((type === '*' || type === 'br') && (!priority || parseFloat(priority) > 0)) {
|
|
129
|
+
return true;
|
|
133
130
|
}
|
|
134
131
|
}
|
|
135
132
|
}
|
|
@@ -156,14 +153,11 @@ function groupExtraScripts(scripts = []) {
|
|
|
156
153
|
[SCRIPT_LOCATIONS.DEFAULT]: '',
|
|
157
154
|
[SCRIPT_LOCATIONS.HEAD_OPEN]: ''
|
|
158
155
|
};
|
|
159
|
-
for (
|
|
160
|
-
const script = scripts[i];
|
|
156
|
+
for (const script of scripts) {
|
|
161
157
|
if ((0, _lodash.isString)(script)) {
|
|
162
158
|
if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;
|
|
163
|
-
} else if (script
|
|
164
|
-
if (res[script.location]
|
|
165
|
-
res[script.location] += script.code;
|
|
166
|
-
} else throw Error(`Invalid location "${script.location}"`);
|
|
159
|
+
} else if (script.code) {
|
|
160
|
+
if (script.location in res) res[script.location] += script.code;else throw Error(`Invalid location "${script.location}"`);
|
|
167
161
|
}
|
|
168
162
|
}
|
|
169
163
|
return res;
|
|
@@ -183,7 +177,6 @@ function newDefaultLogger({
|
|
|
183
177
|
transports
|
|
184
178
|
} = _winston.default;
|
|
185
179
|
return _winston.default.createLogger({
|
|
186
|
-
level: defaultLogLevel,
|
|
187
180
|
format: format.combine(format.splat(), format.timestamp(), format.colorize(), format.printf(({
|
|
188
181
|
level,
|
|
189
182
|
message,
|
|
@@ -198,6 +191,7 @@ function newDefaultLogger({
|
|
|
198
191
|
if (stack) res += `\n${stack}`;
|
|
199
192
|
return res;
|
|
200
193
|
})),
|
|
194
|
+
level: defaultLogLevel,
|
|
201
195
|
transports: [new transports.Console()]
|
|
202
196
|
});
|
|
203
197
|
}
|
|
@@ -234,7 +228,7 @@ function newDefaultLogger({
|
|
|
234
228
|
*/
|
|
235
229
|
function factory(webpackConfig, options) {
|
|
236
230
|
const ops = (0, _lodash.defaults)((0, _lodash.clone)(options), {
|
|
237
|
-
beforeRender: () => Promise.resolve({}),
|
|
231
|
+
beforeRender: async () => Promise.resolve({}),
|
|
238
232
|
maxSsrRounds: 10,
|
|
239
233
|
ssrTimeout: 1000,
|
|
240
234
|
staticCacheSize: 1.e7
|
|
@@ -243,12 +237,10 @@ function factory(webpackConfig, options) {
|
|
|
243
237
|
// Note: in normal use the default logger is created and set in the root
|
|
244
238
|
// server function, and this initialization is for testing uses, where
|
|
245
239
|
// renderer is imported directly.
|
|
246
|
-
|
|
247
|
-
ops.
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
}
|
|
251
|
-
const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);
|
|
240
|
+
ops.logger ??= newDefaultLogger({
|
|
241
|
+
defaultLogLevel: ops.defaultLoggerLogLevel
|
|
242
|
+
});
|
|
243
|
+
const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context);
|
|
252
244
|
(0, _buildInfo.setBuildInfo)(buildInfo);
|
|
253
245
|
|
|
254
246
|
// publicPath from webpack.output has a trailing slash at the end.
|
|
@@ -257,8 +249,14 @@ function factory(webpackConfig, options) {
|
|
|
257
249
|
path: outputPath
|
|
258
250
|
} = webpackConfig.output;
|
|
259
251
|
const manifestLink = _fs.default.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : '';
|
|
252
|
+
|
|
253
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
254
|
+
|
|
260
255
|
const cache = ops.staticCacheController ? new _Cache.default(ops.staticCacheSize) : null;
|
|
261
256
|
const CHUNK_GROUPS = readChunkGroupsJson(outputPath);
|
|
257
|
+
|
|
258
|
+
// TODO: Look at it later.
|
|
259
|
+
// eslint-disable-next-line complexity
|
|
262
260
|
return async (req, res, next) => {
|
|
263
261
|
try {
|
|
264
262
|
// Ensures any caches always revalidate HTML markup before reuse.
|
|
@@ -289,6 +287,8 @@ function factory(webpackConfig, options) {
|
|
|
289
287
|
// .replaceAll() method instead relying on reg. expression for
|
|
290
288
|
// global matching.
|
|
291
289
|
const regex = new RegExp(buffer.nonce, 'g');
|
|
290
|
+
|
|
291
|
+
// TODO: It should be implemented more careful.
|
|
292
292
|
h = h.replace(regex, req.nonce);
|
|
293
293
|
}
|
|
294
294
|
if (status !== 200) res.status(status);
|
|
@@ -322,9 +322,9 @@ function factory(webpackConfig, options) {
|
|
|
322
322
|
chunkGroups = (0, _lodash.mapValues)(webpackStats.toJson({
|
|
323
323
|
all: false,
|
|
324
324
|
chunkGroups: true
|
|
325
|
-
}).namedChunkGroups, item => item.assets
|
|
325
|
+
}).namedChunkGroups, item => item.assets?.map(({
|
|
326
326
|
name
|
|
327
|
-
}) => name));
|
|
327
|
+
}) => name) ?? []);
|
|
328
328
|
} else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;else chunkGroups = {};
|
|
329
329
|
|
|
330
330
|
/* Optional server-side rendering. */
|
|
@@ -369,15 +369,11 @@ function factory(webpackConfig, options) {
|
|
|
369
369
|
let ssrRound = 0;
|
|
370
370
|
let bailed = false;
|
|
371
371
|
for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {
|
|
372
|
-
stream = await renderPass();
|
|
373
|
-
|
|
372
|
+
stream = await renderPass();
|
|
374
373
|
if (!ssrContext.dirty) break;
|
|
375
|
-
|
|
376
|
-
/* eslint-disable no-await-in-loop */
|
|
377
374
|
const timeout = ops.ssrTimeout + ssrStart - Date.now();
|
|
378
375
|
bailed = timeout <= 0 || !(await Promise.race([Promise.allSettled(ssrContext.pending), (0, _jsUtils.timer)(timeout).then(() => false)]));
|
|
379
376
|
if (bailed) break;
|
|
380
|
-
/* eslint-enable no-await-in-loop */
|
|
381
377
|
}
|
|
382
378
|
let logMsg;
|
|
383
379
|
if (ssrContext.dirty) {
|
|
@@ -406,7 +402,7 @@ function factory(webpackConfig, options) {
|
|
|
406
402
|
* better than injection of a plain text. */
|
|
407
403
|
const payload = (0, _serializeJavascript.default)({
|
|
408
404
|
CHUNK_GROUPS: chunkGroups,
|
|
409
|
-
CONFIG: configToInject
|
|
405
|
+
CONFIG: configToInject ?? sanitizedConfig,
|
|
410
406
|
ISTATE: ssrContext.state
|
|
411
407
|
}, {
|
|
412
408
|
ignoreFunction: true,
|
|
@@ -476,7 +472,7 @@ function factory(webpackConfig, options) {
|
|
|
476
472
|
(0, _zlib.brotliCompress)(html, (error, buffer) => {
|
|
477
473
|
const b = buffer;
|
|
478
474
|
if (error) failed(error);else {
|
|
479
|
-
b.nonce = req.nonce;
|
|
475
|
+
b.nonce = req.nonce;
|
|
480
476
|
cache.add({
|
|
481
477
|
buffer: b,
|
|
482
478
|
status
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","names":["_fs","_interopRequireDefault","require","_path","_stream","_zlib","_winston","_reactGlobalState","_jsUtils","_lodash","_config","_nodeForge","_static","_reactHelmet","_reactRouter","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","exports","ServerSsrContext","SsrContext","chunks","status","constructor","req","chunkGroups","initialState","cloneDeep","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","get","ops","split","i","length","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","isString","code","location","undefined","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","level","combine","splat","timestamp","colorize","printf","message","stack","rest","Object","keys","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","helmetContext","prelude","prerenderToNodeStream","jsx","GlobalStateProvider","state","children","StaticRouter","HelmetProvider","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","ready","pipe","Writable","destroy","write","chunk","_","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport type { Request, RequestHandler } from 'express';\nimport { type ComponentType } from 'react';\nimport { Writable } from 'stream';\nimport { brotliCompress, brotliDecompress } from 'zlib';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport { type ChunkGroupsT, type SsrContextT } from 'utils/globalState';\n\nimport { type Configuration } from 'webpack';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\ninterface LogMethodI {\n (level: string, message: string, ...meta: any[]): void;\n}\ninterface LeveledLogMethodI {\n (message: string, ...meta: any[]): void;\n}\n\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) || ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8'));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8'));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req: Request) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const op = ops[i];\n if (op) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script?.code) {\n if (res[script.location] !== undefined) {\n res[script.location] += script.code;\n } else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}) {\n const { format, transports } = winston;\n return winston.createLogger({\n level: defaultLogLevel,\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: any;\n};\n\nexport type BeforeRenderT =\n(req: Request, config: ConfigT) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n }\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n interface BufferWithNonce extends Buffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, (req as any).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender!(req, sanitizedConfig as any),\n prepareCipher(buildInfo.key) as Promise<any>,\n ]);\n\n let helmet: any;\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }: { name: string }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {};\n const { prelude } = await prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: (error) => { throw error; } },\n );\n ({ helmet } = helmetContext as any);\n\n return prelude;\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n /* eslint-enable no-await-in-loop */\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon ? (\n '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n ) : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n const b = buffer as BufferWithNonce;\n if (error) failed(error);\n else {\n b.nonce = (req as any).nonce; // eslint-disable-line no-param-reassign\n cache!.add({ buffer: b, status }, cacheRef!.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,GAAA,GAA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IM,KAAK,EAAEF,MAAM,CAACE,KAAK,CAAC,CAAC,KACpB;cACHqF,CAAC,CAAC/E,KAAK,GAAI9G,GAAG,CAAS8G,KAAK,CAAC,CAAC;cAC9BtB,KAAK,CAAE2F,GAAG,CAAC;gBAAEjF,MAAM,EAAE2F,CAAC;gBAAE/L;cAAO,CAAC,EAAEkG,QAAQ,CAAE9E,GAAG,EAAEgF,MAAM,CAAChE,MAAM,CAAC;cAC/DmE,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACAtF,GAAG,CAACqF,IAAI,CAACK,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdZ,IAAI,CAACY,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"renderer.js","names":["_fs","_interopRequireDefault","require","_path","_stream","_zlib","_winston","_reactGlobalState","_jsUtils","_lodash","_config","_nodeForge","_static","_reactHelmet","_reactRouter","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","exports","ServerSsrContext","SsrContext","chunks","status","constructor","req","chunkGroups","initialState","cloneDeep","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","Promise","reject","forge","random","getBytes","err","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","get","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","isString","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","helmetContext","prelude","prerenderToNodeStream","jsx","GlobalStateProvider","state","children","StaticRouter","HelmetProvider","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","ready","pipe","Writable","destroy","write","chunk","_","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport { Writable } from 'stream';\nimport { brotliCompress, brotliDecompress } from 'zlib';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { HelmetProvider, type HelmetDataContext } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport type { Configuration, Stats } from 'webpack';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nasync function prepareCipher(key: string): Promise<{\n cipher: forge.cipher.BlockCipher;\n iv: string;\n}> {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT =\n(req: Request, config: ConfigT) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends Buffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n const { prelude } = await prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: (error) => {\n throw error;\n } },\n );\n ({ helmet } = helmetContext);\n\n return prelude;\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n const b = buffer as BufferWithNonce;\n if (error) failed(error);\n else {\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,GAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,KAAA,GAAAF,sBAAA,CAAAC,OAAA;AAIA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,KAAA,GAAAH,OAAA;AACA,IAAAI,QAAA,GAAAL,sBAAA,CAAAC,OAAA;AAEA,IAAAK,iBAAA,GAAAL,OAAA;AACA,IAAAM,QAAA,GAAAN,OAAA;AAEA,IAAAO,OAAA,GAAAP,OAAA;AAUA,IAAAQ,OAAA,GAAAT,sBAAA,CAAAC,OAAA;AACA,IAAAS,UAAA,GAAAV,sBAAA,CAAAC,OAAA;AAEA,IAAAU,OAAA,GAAAV,OAAA;AACA,IAAAW,YAAA,GAAAX,OAAA;AACA,IAAAY,YAAA,GAAAZ,OAAA;AACA,IAAAa,oBAAA,GAAAd,sBAAA,CAAAC,OAAA;AACA,IAAAc,UAAA,GAAAd,OAAA;AAMA,IAAAe,MAAA,GAAAhB,sBAAA,CAAAC,OAAA;AAA4B,IAA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AACjB,MAAM,CAACA,MAAM,CAAC;MAEtC,IAAIgG,QAAQ,IAAIhG,MAAM,GAAG,GAAG,EAAE;QAC5B;QACA;QACA,MAAM,IAAIoB,OAAO,CAAO,CAACiF,IAAI,EAAEC,MAAM,KAAK;UACxC,IAAAsF,oBAAc,EAACnF,IAAI,EAAE,CAACD,KAAK,EAAEN,MAAM,KAAK;YACtC,MAAM2F,CAAC,GAAG3F,MAAyB;YACnC,IAAIM,KAAK,EAAEF,MAAM,CAACE,KAAK,CAAC,CAAC,KACpB;cACHqF,CAAC,CAAC/E,KAAK,GAAI5G,GAAG,CAEX4G,KAAK;cACRtB,KAAK,CAAE2F,GAAG,CAAC;gBAAEjF,MAAM,EAAE2F,CAAC;gBAAE7L;cAAO,CAAC,EAAEgG,QAAQ,CAAC7E,GAAG,EAAE+E,MAAM,CAAC/B,MAAM,CAAC;cAC9DkC,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACApF,GAAG,CAACmF,IAAI,CAACK,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdZ,IAAI,CAACY,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -18,13 +18,14 @@ var _helmet = _interopRequireDefault(require("helmet"));
|
|
|
18
18
|
var _morgan = _interopRequireDefault(require("morgan"));
|
|
19
19
|
var _requestIp = _interopRequireDefault(require("request-ip"));
|
|
20
20
|
var _uuid = require("uuid");
|
|
21
|
-
require("webpack");
|
|
22
21
|
var _renderer = _interopRequireDefault(require("./renderer"));
|
|
23
22
|
var _errors = require("./utils/errors");
|
|
24
23
|
/**
|
|
25
24
|
* Creation of standard ExpressJS server for ReactJS apps.
|
|
26
25
|
*/
|
|
27
26
|
|
|
27
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
28
|
+
|
|
28
29
|
/**
|
|
29
30
|
* Default Content Security Policy settings.
|
|
30
31
|
* @ignore
|
|
@@ -86,9 +87,10 @@ async function factory(webpackConfig, options) {
|
|
|
86
87
|
if (schema === 'http') {
|
|
87
88
|
let url = `https://${req.headers.host}`;
|
|
88
89
|
if (req.originalUrl !== '/') url += req.originalUrl;
|
|
89
|
-
|
|
90
|
+
res.redirect(url);
|
|
91
|
+
return;
|
|
90
92
|
}
|
|
91
|
-
|
|
93
|
+
next();
|
|
92
94
|
});
|
|
93
95
|
}
|
|
94
96
|
server.use((0, _compression.default)());
|
|
@@ -148,27 +150,32 @@ async function factory(webpackConfig, options) {
|
|
|
148
150
|
// to be served from the root, to have all web app pages in its scope.
|
|
149
151
|
// Thus, this setup to serve it. Probably, need some more configuration
|
|
150
152
|
// for special cases, but this will do for now.
|
|
151
|
-
server.get('/__service-worker.js', _express.default.static(webpackConfig.output?.path
|
|
153
|
+
server.get('/__service-worker.js', _express.default.static(webpackConfig.output?.path ?? '', {
|
|
152
154
|
setHeaders: res => res.set('Cache-Control', 'no-cache')
|
|
153
155
|
}));
|
|
154
156
|
|
|
155
157
|
/* Setup of Hot Module Reloading for development environment.
|
|
156
158
|
* These dependencies are not used, nor installed for production use,
|
|
157
159
|
* hence we should violate some import-related lint rules. */
|
|
158
|
-
/* eslint-disable global-require */
|
|
159
160
|
/* eslint-disable import/no-extraneous-dependencies */
|
|
160
|
-
/* eslint-disable import/no-unresolved */
|
|
161
161
|
if (options.devMode) {
|
|
162
162
|
// This is a workaround for SASS bug:
|
|
163
163
|
// https://github.com/dart-lang/sdk/issues/27979
|
|
164
164
|
// which manifests itself sometimes when webpack dev middleware is used
|
|
165
165
|
// (in dev mode), and app modules are imported in some unfortunate ways.
|
|
166
|
+
// TODO: Double-check, what is going on here.
|
|
167
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
166
168
|
if (!global.location) {
|
|
167
169
|
global.location = {
|
|
168
170
|
href: `${(0, _url.pathToFileURL)(process.cwd()).href}${_path.sep}`
|
|
169
171
|
};
|
|
170
172
|
}
|
|
173
|
+
|
|
174
|
+
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
171
175
|
const webpack = require('webpack');
|
|
176
|
+
|
|
177
|
+
// TODO: Figure out the exact type for options, don't wanna waste time on it
|
|
178
|
+
// right now.
|
|
172
179
|
const webpackDevMiddleware = require('webpack-dev-middleware');
|
|
173
180
|
const webpackHotMiddleware = require('webpack-hot-middleware');
|
|
174
181
|
const compiler = webpack(webpackConfig);
|
|
@@ -178,9 +185,7 @@ async function factory(webpackConfig, options) {
|
|
|
178
185
|
}));
|
|
179
186
|
server.use(webpackHotMiddleware(compiler));
|
|
180
187
|
}
|
|
181
|
-
/* eslint-enable global-require */
|
|
182
188
|
/* eslint-enable import/no-extraneous-dependencies */
|
|
183
|
-
/* eslint-enable import/no-unresolved */
|
|
184
189
|
|
|
185
190
|
server.use(publicPath, _express.default.static(webpackConfig.output.path));
|
|
186
191
|
if (options.onExpressJsSetup) {
|
|
@@ -210,18 +215,20 @@ async function factory(webpackConfig, options) {
|
|
|
210
215
|
server.use((error, req, res, next) => {
|
|
211
216
|
// TODO: This is needed to correctly handled any errors thrown after
|
|
212
217
|
// sending initial response to the client.
|
|
213
|
-
if (res.headersSent)
|
|
214
|
-
|
|
218
|
+
if (res.headersSent) {
|
|
219
|
+
next(error);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const status = error.status ?? _errors.CODES.INTERNAL_SERVER_ERROR;
|
|
215
223
|
const serverSide = status >= _errors.CODES.INTERNAL_SERVER_ERROR;
|
|
216
224
|
|
|
217
225
|
// Log server-side errors always, client-side at debug level only.
|
|
218
|
-
options.logger.log(serverSide ? 'error' : 'debug', error);
|
|
226
|
+
options.logger.log(serverSide ? 'error' : 'debug', error.toString());
|
|
219
227
|
let message = error.message || (0, _errors.getErrorForCode)(status);
|
|
220
228
|
if (serverSide && process.env.NODE_ENV === 'production') {
|
|
221
229
|
message = _errors.ERRORS.INTERNAL_SERVER_ERROR;
|
|
222
230
|
}
|
|
223
231
|
res.status(status).send(message);
|
|
224
|
-
return undefined;
|
|
225
232
|
});
|
|
226
233
|
}
|
|
227
234
|
return server;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV","undefined"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\nimport { type Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?: (server: ServerT) => boolean | Promise<boolean | void> | void;\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n) {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path || '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: any,\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) return next(error);\n\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n return undefined;\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,KAAA,GAAAC,OAAA;AACA,IAAAC,IAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAMA,IAAAG,YAAA,GAAAC,sBAAA,CAAAJ,OAAA;AACA,IAAAK,aAAA,GAAAD,sBAAA,CAAAJ,OAAA;AACA,IAAAM,MAAA,GAAAF,sBAAA,CAAAJ,OAAA;AAEA,IAAAO,QAAA,GAAAH,sBAAA,CAAAJ,OAAA;AAOA,IAAAQ,aAAA,GAAAJ,sBAAA,CAAAJ,OAAA;AACA,IAAAS,OAAA,GAAAL,sBAAA,CAAAJ,OAAA;AACA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J,KAAK,CAAC;MAE1D,IAAIM,OAAO,GAAGN,KAAK,CAACM,OAAO,IAAI,IAAAC,uBAAe,EAACL,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAInB,OAAO,CAACuB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDH,OAAO,GAAGX,cAAM,CAACQ,qBAAqB;MACxC;MAEAlE,GAAG,CAACiE,MAAM,CAACA,MAAM,CAAC,CAAC7C,IAAI,CAACiD,OAAO,CAAC;MAChC,OAAOI,SAAS;IAClB,CAAC,CAAC;EACJ;EAEA,OAAOhF,MAAM;AACf","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type RequestHandler,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Compiler, Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const webpack = require('webpack') as (ops: Configuration) => Compiler;\n\n // TODO: Figure out the exact type for options, don't wanna waste time on it\n // right now.\n const webpackDevMiddleware = require('webpack-dev-middleware') as\n (c: Compiler, ops: unknown) => RequestHandler;\n\n const webpackHotMiddleware = require('webpack-hot-middleware') as\n (c: Compiler) => RequestHandler;\n\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,KAAA,GAAAC,OAAA;AACA,IAAAC,IAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAMA,IAAAG,YAAA,GAAAC,sBAAA,CAAAJ,OAAA;AACA,IAAAK,aAAA,GAAAD,sBAAA,CAAAJ,OAAA;AACA,IAAAM,MAAA,GAAAF,sBAAA,CAAAJ,OAAA;AAEA,IAAAO,QAAA,GAAAH,sBAAA,CAAAJ,OAAA;AAQA,IAAAQ,aAAA,GAAAJ,sBAAA,CAAAJ,OAAA;AACA,IAAAS,OAAA,GAAAL,sBAAA,CAAAJ,OAAA;AACA,IAAAU,OAAA,GAAAN,sBAAA,CAAAJ,OAAA;AACA,IAAAW,UAAA,GAAAP,sBAAA,CAAAJ,OAAA;AACA,IAAAY,KAAA,GAAAZ,OAAA;AAIA,IAAAa,SAAA,GAAAT,sBAAA,CAAAJ,OAAA;AAKA,IAAAc,OAAA,GAAAd,OAAA;AAtCA;AACA;AACA;;AA8CA;;AAMA;AACA;AACA;AACA;AACA,MAAMe,kBAAkB,GAAG;EACzBC,UAAU,EAAE,IAAAC,iBAAS,EACnBC,eAAM,CAACC,qBAAqB,CAACC,oBAAoB,CAAC,CAAC;EAEnD;EACA;EACA;EACA;EACCC,KAAK,IAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,IAAKA,IAAI,KAAK,QAAQ,CAC3E;AACF,CAAC;AACDR,kBAAkB,CAACC,UAAU,CAAC,WAAW,CAAC,GAAG,CAC3C,QAAQ;AAER;AACA;AACA,uBAAuB,CACxB;AAED;EACE,MAAMA,UAAU,GAAGD,kBAAkB,CAACC,UAAU,CAAC,YAAY,CAAC;EAC9D,IAAIA,UAAU,EAAEA,UAAU,CAACQ,IAAI,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BAA6B,GAAG,MAAM3E,OAAO,CAAC4E,oBAAoB,CAACrE,MAAM,CAAC;EAC5E;;EAEA;EACA,IAAI,CAACoE,6BAA6B,EAAE;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACApE,MAAM,CAACK,GAAG,CAAC,CACTiE,KAEC,EACDhE,GAAY,EACZC,GAAa,EACbC,IAAkB,KACf;MACH;MACA;MACA,IAAID,GAAG,CAACgE,WAAW,EAAE;QACnB/D,IAAI,CAAC8D,KAAK,CAAC;QACX;MACF;MAEA,MAAME,MAAM,GAAGF,KAAK,CAACE,MAAM,IAAIL,aAAK,CAACM,qBAAqB;MAC1D,MAAMC,UAAU,GAAGF,MAAM,IAAKL,aAAK,CAACM,qBAAgC;;MAEpE;MACAhF,OAAO,CAACU,MAAM,CAAEwE,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAI,IAAAC,uBAAe,EAACN,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAInB,OAAO,CAACwB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDH,OAAO,GAAGZ,cAAM,CAACQ,qBAAqB;MACxC;MAEAlE,GAAG,CAACiE,MAAM,CAACA,MAAM,CAAC,CAAC7C,IAAI,CAACkD,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAO7E,MAAM;AACf","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","ErrorWithStatus","Error","status","CODES","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message: string
|
|
1
|
+
{"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","ErrorWithStatus","Error","status","CODES","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(\n message: string,\n statusCode = CODES.INTERNAL_SERVER_ERROR,\n): ErrorWithStatus {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * Throws an error with given message and HTTP status code.\n */\nexport function fail(\n message: string,\n statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,\n): Error {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param value\n * @param schema\n * @param [message] Error message.\n * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n */\nexport function assert(\n value: unknown,\n schema: joi.AnySchema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n): void {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAAA,gBAAA,GAAAC,OAAA;AAMA,IAAAC,IAAA,GAAAC,sBAAA,CAAAF,OAAA;AAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA,MAAMG,eAAe,SAASC,KAAK,CAAC;EAClCC,MAAM,GAAWC,4BAAK,CAACC,qBAAqB;AAC9C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,QAAQA,CACtBC,OAAe,EACfC,UAAU,GAAGJ,4BAAK,CAACC,qBAAqB,EACvB;EACjB,MAAMI,KAAK,GAAG,IAAIR,eAAe,CAACM,OAAO,CAAC;EAC1CE,KAAK,CAACN,MAAM,GAAGK,UAAU;EACzB,OAAOC,KAAK;AACd;;AAEA;AACA;AACA;AACO,SAASC,IAAIA,CAClBH,OAAe,EACfC,UAAiB,GAAGJ,4BAAK,CAACC,qBAAqB,EACxC;EACP,MAAMC,QAAQ,CAACC,OAAO,EAAEC,UAAU,CAAC;AACrC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,MAAMA,CACpBC,KAAc,EACdC,MAAqB,EACrBN,OAAO,GAAG,EAAE,EACZC,UAAU,GAAGJ,4BAAK,CAACU,WAAW,EACxB;EACN,MAAM;IAAEL;EAAM,CAAC,GAAGI,MAAM,CAACE,QAAQ,CAACH,KAAK,EAAE;IAAEI,UAAU,EAAE;EAAM,CAAC,CAAC;EAC/D,IAAIP,KAAK,EAAE;IACTC,IAAI,CAACH,OAAO,CAACU,MAAM,CAACV,OAAO,GAAG,IAAI,GAAG,EAAE,EAAEE,KAAK,CAACF,OAAO,CAAC,EAAEC,UAAU,CAAC;EACtE;AACF","ignoreList":[]}
|