@dr.pogodin/react-utils 1.49.1 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/babel.scripts.config.js +19 -0
  2. package/build/development/client/getInj.js +18 -29
  3. package/build/development/client/getInj.js.map +1 -1
  4. package/build/development/client/index.js +11 -14
  5. package/build/development/client/index.js.map +1 -1
  6. package/build/development/client/init.js +9 -17
  7. package/build/development/client/init.js.map +1 -1
  8. package/build/development/index.js +26 -4
  9. package/build/development/index.js.map +1 -1
  10. package/build/development/server/Cache.js +15 -20
  11. package/build/development/server/Cache.js.map +1 -1
  12. package/build/development/server/index.js +142 -160
  13. package/build/development/server/index.js.map +1 -1
  14. package/build/development/server/renderer.js +150 -197
  15. package/build/development/server/renderer.js.map +1 -1
  16. package/build/development/server/server.js +63 -86
  17. package/build/development/server/server.js.map +1 -1
  18. package/build/development/server/utils/errors.js +72 -87
  19. package/build/development/server/utils/errors.js.map +1 -1
  20. package/build/development/shared/components/Button/index.js +8 -17
  21. package/build/development/shared/components/Button/index.js.map +1 -1
  22. package/build/development/shared/components/Checkbox/index.js +4 -4
  23. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  24. package/build/development/shared/components/GenericLink/index.js +54 -58
  25. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  26. package/build/development/shared/components/Input/index.js +16 -24
  27. package/build/development/shared/components/Input/index.js.map +1 -1
  28. package/build/development/shared/components/Link.js +2 -5
  29. package/build/development/shared/components/Link.js.map +1 -1
  30. package/build/development/shared/components/Modal/index.js +28 -41
  31. package/build/development/shared/components/Modal/index.js.map +1 -1
  32. package/build/development/shared/components/NavLink.js +2 -3
  33. package/build/development/shared/components/NavLink.js.map +1 -1
  34. package/build/development/shared/components/PageLayout/index.js +19 -20
  35. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  36. package/build/development/shared/components/TextArea/index.js +12 -28
  37. package/build/development/shared/components/TextArea/index.js.map +1 -1
  38. package/build/development/shared/components/Throbber/index.js +11 -12
  39. package/build/development/shared/components/Throbber/index.js.map +1 -1
  40. package/build/development/shared/components/WithTooltip/Tooltip.js +46 -68
  41. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  42. package/build/development/shared/components/WithTooltip/index.js +21 -28
  43. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  44. package/build/development/shared/components/YouTubeVideo/index.js +21 -25
  45. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  46. package/build/development/shared/components/index.js +1 -3
  47. package/build/development/shared/components/index.js.map +1 -1
  48. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -7
  49. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  50. package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -9
  51. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  52. package/build/development/shared/components/selectors/NativeDropdown/index.js +23 -27
  53. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  54. package/build/development/shared/components/selectors/Switch/index.js +4 -4
  55. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  56. package/build/development/shared/components/selectors/common.js +2 -5
  57. package/build/development/shared/components/selectors/common.js.map +1 -1
  58. package/build/development/shared/utils/config.js +11 -15
  59. package/build/development/shared/utils/config.js.map +1 -1
  60. package/build/development/shared/utils/globalState.js +1 -7
  61. package/build/development/shared/utils/globalState.js.map +1 -1
  62. package/build/development/shared/utils/index.js +2 -2
  63. package/build/development/shared/utils/index.js.map +1 -1
  64. package/build/development/shared/utils/isomorphy/buildInfo.js +15 -24
  65. package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
  66. package/build/development/shared/utils/isomorphy/environment-check.js +4 -9
  67. package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
  68. package/build/development/shared/utils/isomorphy/index.js +17 -23
  69. package/build/development/shared/utils/isomorphy/index.js.map +1 -1
  70. package/build/development/shared/utils/jest/E2eSsrEnv.js +48 -77
  71. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  72. package/build/development/shared/utils/jest/index.js +48 -72
  73. package/build/development/shared/utils/jest/index.js.map +1 -1
  74. package/build/development/shared/utils/splitComponent.js +67 -74
  75. package/build/development/shared/utils/splitComponent.js.map +1 -1
  76. package/build/development/shared/utils/time.js +25 -28
  77. package/build/development/shared/utils/time.js.map +1 -1
  78. package/build/development/shared/utils/webpack.js +22 -29
  79. package/build/development/shared/utils/webpack.js.map +1 -1
  80. package/build/production/client/getInj.js.map +1 -1
  81. package/build/production/client/index.js.map +1 -1
  82. package/build/production/index.js +26 -1
  83. package/build/production/index.js.map +1 -1
  84. package/build/production/server/Cache.js.map +1 -1
  85. package/build/production/server/index.js.map +1 -1
  86. package/build/production/server/renderer.js.map +1 -1
  87. package/build/production/server/server.js.map +1 -1
  88. package/build/production/shared/components/Button/index.js.map +1 -1
  89. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  90. package/build/production/shared/components/GenericLink/index.js +2 -2
  91. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  92. package/build/production/shared/components/Input/index.js.map +1 -1
  93. package/build/production/shared/components/Link.js.map +1 -1
  94. package/build/production/shared/components/Modal/index.js.map +1 -1
  95. package/build/production/shared/components/NavLink.js.map +1 -1
  96. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  97. package/build/production/shared/components/TextArea/index.js.map +1 -1
  98. package/build/production/shared/components/Throbber/index.js.map +1 -1
  99. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  100. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  101. package/build/production/shared/components/index.js.map +1 -1
  102. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  103. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  104. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  105. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  106. package/build/production/shared/utils/config.js.map +1 -1
  107. package/build/production/shared/utils/index.js.map +1 -1
  108. package/build/production/shared/utils/jest/index.js.map +1 -1
  109. package/build/production/shared/utils/splitComponent.js +20 -3
  110. package/build/production/shared/utils/splitComponent.js.map +1 -1
  111. package/build/production/shared/utils/time.js.map +1 -1
  112. package/build/production/shared/utils/webpack.js.map +1 -1
  113. package/build/types-code/shared/components/GenericLink/index.d.ts +0 -1
  114. package/build/web/client/getInj.js +10 -70
  115. package/build/web/client/getInj.js.map +1 -1
  116. package/build/web/client/index.js +2 -27
  117. package/build/web/client/index.js.map +1 -1
  118. package/build/web/client/init.js +10 -44
  119. package/build/web/client/init.js.map +1 -1
  120. package/build/web/index.js +26 -6
  121. package/build/web/index.js.map +1 -1
  122. package/build/web/server/Cache.js +3 -41
  123. package/build/web/server/Cache.js.map +1 -1
  124. package/build/web/server/index.js +7 -78
  125. package/build/web/server/index.js.map +1 -1
  126. package/build/web/server/renderer.js +61 -420
  127. package/build/web/server/renderer.js.map +1 -1
  128. package/build/web/server/server.js +38 -212
  129. package/build/web/server/server.js.map +1 -1
  130. package/build/web/server/utils/errors.js +9 -48
  131. package/build/web/server/utils/errors.js.map +1 -1
  132. package/build/web/server/utils/index.js +1 -2
  133. package/build/web/server/utils/index.js.map +1 -1
  134. package/build/web/shared/components/Button/index.js +12 -101
  135. package/build/web/shared/components/Button/index.js.map +1 -1
  136. package/build/web/shared/components/Checkbox/index.js +1 -40
  137. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  138. package/build/web/shared/components/Checkbox/theme.scss +1 -0
  139. package/build/web/shared/components/GenericLink/index.js +12 -65
  140. package/build/web/shared/components/GenericLink/index.js.map +1 -1
  141. package/build/web/shared/components/GenericLink/style.scss +1 -0
  142. package/build/web/shared/components/Input/index.js +11 -69
  143. package/build/web/shared/components/Input/index.js.map +1 -1
  144. package/build/web/shared/components/Link.js +2 -12
  145. package/build/web/shared/components/Link.js.map +1 -1
  146. package/build/web/shared/components/Modal/index.js +10 -130
  147. package/build/web/shared/components/Modal/index.js.map +1 -1
  148. package/build/web/shared/components/NavLink.js +2 -10
  149. package/build/web/shared/components/NavLink.js.map +1 -1
  150. package/build/web/shared/components/PageLayout/index.js +2 -27
  151. package/build/web/shared/components/PageLayout/index.js.map +1 -1
  152. package/build/web/shared/components/TextArea/index.js +21 -106
  153. package/build/web/shared/components/TextArea/index.js.map +1 -1
  154. package/build/web/shared/components/Throbber/index.js +2 -24
  155. package/build/web/shared/components/Throbber/index.js.map +1 -1
  156. package/build/web/shared/components/WithTooltip/Tooltip.js +16 -145
  157. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
  158. package/build/web/shared/components/WithTooltip/index.js +12 -104
  159. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  160. package/build/web/shared/components/YouTubeVideo/index.js +5 -43
  161. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  162. package/build/web/shared/components/index.js +1 -15
  163. package/build/web/shared/components/index.js.map +1 -1
  164. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +6 -81
  165. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  166. package/build/web/shared/components/selectors/CustomDropdown/index.js +7 -122
  167. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  168. package/build/web/shared/components/selectors/NativeDropdown/index.js +7 -68
  169. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  170. package/build/web/shared/components/selectors/Switch/index.js +1 -49
  171. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  172. package/build/web/shared/components/selectors/common.js +1 -10
  173. package/build/web/shared/components/selectors/common.js.map +1 -1
  174. package/build/web/shared/components/selectors/index.js +1 -3
  175. package/build/web/shared/components/selectors/index.js.map +1 -1
  176. package/build/web/shared/utils/config.js +6 -40
  177. package/build/web/shared/utils/config.js.map +1 -1
  178. package/build/web/shared/utils/globalState.js +2 -11
  179. package/build/web/shared/utils/globalState.js.map +1 -1
  180. package/build/web/shared/utils/index.js +1 -9
  181. package/build/web/shared/utils/index.js.map +1 -1
  182. package/build/web/shared/utils/isomorphy/buildInfo.js +4 -25
  183. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -1
  184. package/build/web/shared/utils/isomorphy/environment-check.js +3 -9
  185. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -1
  186. package/build/web/shared/utils/isomorphy/index.js +5 -27
  187. package/build/web/shared/utils/isomorphy/index.js.map +1 -1
  188. package/build/web/shared/utils/jest/E2eSsrEnv.js +51 -221
  189. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  190. package/build/web/shared/utils/jest/global.js +1 -3
  191. package/build/web/shared/utils/jest/global.js.map +1 -1
  192. package/build/web/shared/utils/jest/index.js +27 -146
  193. package/build/web/shared/utils/jest/index.js.map +1 -1
  194. package/build/web/shared/utils/splitComponent.js +34 -197
  195. package/build/web/shared/utils/splitComponent.js.map +1 -1
  196. package/build/web/shared/utils/time.js +5 -69
  197. package/build/web/shared/utils/time.js.map +1 -1
  198. package/build/web/shared/utils/webpack.js +6 -53
  199. package/build/web/shared/utils/webpack.js.map +1 -1
  200. package/config/babel/webpack.js +1 -1
  201. package/eslint.config.mjs +1 -0
  202. package/package.json +5 -8
  203. package/bin/build.js +0 -236
  204. package/config/webpack/lib-base.d.ts +0 -22
  205. package/config/webpack/lib-base.js +0 -167
  206. package/config/webpack/lib-development.d.ts +0 -5
  207. package/config/webpack/lib-development.js +0 -35
  208. package/config/webpack/lib-production.d.ts +0 -5
  209. package/config/webpack/lib-production.js +0 -42
  210. package/webpack.config.ts +0 -49
@@ -16,26 +16,24 @@ import "core-js/modules/es.set.is-disjoint-from.v2.js";
16
16
  import "core-js/modules/es.set.is-subset-of.v2.js";
17
17
  import "core-js/modules/es.set.is-superset-of.v2.js";
18
18
  import "core-js/modules/es.set.symmetric-difference.v2.js";
19
- import "core-js/modules/es.set.union.v2.js";
20
- /**
21
- * ExpressJS middleware for server-side rendering of a ReactJS app.
22
- */
23
-
24
- import { Buffer } from 'node:buffer';
25
- import { createCipheriv, randomBytes } from 'node:crypto';
26
- import fs from 'node:fs';
27
- import path from 'node:path';
28
- import { Writable } from 'node:stream';
29
- import { brotliCompress, brotliDecompress } from 'node:zlib';
30
- import config from 'config';
31
- import { cloneDeep, defaults, get, mapValues } from 'lodash-es';
32
- import { prerenderToNodeStream } from 'react-dom/static';
33
- import { StaticRouter } from 'react-router';
34
- import serializeJs from 'serialize-javascript';
35
- import winston from 'winston';
36
- import { timer } from '@dr.pogodin/js-utils';
37
- import { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';
38
- import { HelmetProvider } from '@dr.pogodin/react-helmet';
19
+ import "core-js/modules/es.set.union.v2.js"; /**
20
+ * ExpressJS middleware for server-side rendering of a ReactJS app.
21
+ */
22
+ import { Buffer } from "node:buffer";
23
+ import { createCipheriv, randomBytes } from "node:crypto";
24
+ import fs from "node:fs";
25
+ import path from "node:path";
26
+ import { Writable } from "node:stream";
27
+ import { brotliCompress, brotliDecompress } from "node:zlib";
28
+ import config from "config";
29
+ import { cloneDeep, defaults, get, mapValues } from "lodash-es";
30
+ import { prerenderToNodeStream } from "react-dom/static";
31
+ import { StaticRouter } from "react-router";
32
+ import serializeJs from "serialize-javascript";
33
+ import winston from "winston";
34
+ import { timer } from "@dr.pogodin/js-utils";
35
+ import { GlobalStateProvider, SsrContext } from "@dr.pogodin/react-global-state";
36
+ import { HelmetProvider } from "@dr.pogodin/react-helmet";
39
37
  import { setBuildInfo } from "../shared/utils/isomorphy/buildInfo.js";
40
38
  import Cache from "./Cache.js"; // @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
41
39
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -43,17 +41,12 @@ import { jsx as _jsx } from "react/jsx-runtime";
43
41
  const {
44
42
  SECRET,
45
43
  ...sanitizedConfig
46
- } = config.util.toObject(config);
47
-
48
- // Note: These type definitions for logger are copied from Winston logger,
44
+ } = config.util.toObject(config); // Note: These type definitions for logger are copied from Winston logger,
49
45
  // then simplified to make it easier to fit an alternative logger into this
50
46
  // interface.
51
47
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
52
-
53
48
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
54
-
55
49
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
56
-
57
50
  export let SCRIPT_LOCATIONS = /*#__PURE__*/function (SCRIPT_LOCATIONS) {
58
51
  SCRIPT_LOCATIONS["BODY_OPEN"] = "BODY_OPEN";
59
52
  SCRIPT_LOCATIONS["DEFAULT"] = "DEFAULT";
@@ -68,111 +61,100 @@ export class ServerSsrContext extends SsrContext {
68
61
  this.chunkGroups = chunkGroups;
69
62
  this.req = req;
70
63
  }
71
- }
72
- /**
73
- * Reads build-time information about the app. This information is generated
74
- * by our standard Webpack config for apps, and it is written into
75
- * ".build-info" file in the context folder specified in Webpack config.
76
- * At the moment, that file contains build timestamp and a random 32-bit key,
77
- * suitable for cryptographical use.
78
- * @param context Webpack context path used during the build.
79
- * @return Resolves to the build-time information.
80
- */
64
+ } /**
65
+ * Reads build-time information about the app. This information is generated
66
+ * by our standard Webpack config for apps, and it is written into
67
+ * ".build-info" file in the context folder specified in Webpack config.
68
+ * At the moment, that file contains build timestamp and a random 32-bit key,
69
+ * suitable for cryptographical use.
70
+ * @param context Webpack context path used during the build.
71
+ * @return Resolves to the build-time information.
72
+ */
81
73
  function getBuildInfo(context) {
82
- const url = path.resolve(context, '.build-info');
83
- return JSON.parse(fs.readFileSync(url, 'utf8'));
84
- }
85
-
86
- /**
87
- * Attempts to read from disk the named chunk groups mapping generated
88
- * by Webpack during the compilation.
89
- * It will not work for development builds, where these stats should be captured
90
- * via compilator callback.
91
- * @param buildDir
92
- * @return
93
- */
74
+ const url = path.resolve(context, ".build-info");
75
+ return JSON.parse(fs.readFileSync(url, "utf8"));
76
+ } /**
77
+ * Attempts to read from disk the named chunk groups mapping generated
78
+ * by Webpack during the compilation.
79
+ * It will not work for development builds, where these stats should be captured
80
+ * via compilator callback.
81
+ * @param buildDir
82
+ * @return
83
+ */
94
84
  function readChunkGroupsJson(buildDir) {
95
- const url = path.resolve(buildDir, '__chunk_groups__.json');
85
+ const url = path.resolve(buildDir, "__chunk_groups__.json");
96
86
  let res;
97
87
  try {
98
- res = JSON.parse(fs.readFileSync(url, 'utf8'));
88
+ res = JSON.parse(fs.readFileSync(url, "utf8"));
99
89
  } catch {
100
90
  // TODO: Should we message the error here somehow?
101
91
  res = null;
102
92
  }
103
93
  return res;
104
- }
105
-
106
- /**
107
- * Prepares a new Cipher for data encryption.
108
- * @param key Encryption key (32-bit random, Base64-encoded key is expected).
109
- * @return Returns a tuple of:
110
- * 1. cipher - a new Cipher, ready for encryption;
111
- * 2. iv - initial vector used by the cipher.
112
- */
94
+ } /**
95
+ * Prepares a new Cipher for data encryption.
96
+ * @param key Encryption key (32-bit random, Base64-encoded key is expected).
97
+ * @return Returns a tuple of:
98
+ * 1. cipher - a new Cipher, ready for encryption;
99
+ * 2. iv - initial vector used by the cipher.
100
+ */
113
101
  function prepareCipher(key) {
114
102
  const iv = randomBytes(16);
115
- const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);
103
+ const cipher = createCipheriv("AES-256-CBC", Buffer.from(key, "base64"), iv);
116
104
  return [cipher, iv];
117
- }
118
-
119
- /**
120
- * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
121
- * are acceptable to the caller.
122
- * @param req
123
- */
105
+ } /**
106
+ * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
107
+ * are acceptable to the caller.
108
+ * @param req
109
+ */
124
110
  export function isBrotliAcceptable(req) {
125
- const acceptable = req.get('accept-encoding');
111
+ const acceptable = req.get("accept-encoding");
126
112
  if (acceptable) {
127
- const ops = acceptable.split(',');
113
+ const ops = acceptable.split(",");
128
114
  for (const op of ops) {
129
- const [type, priority] = op.trim().split(';q=');
130
- if ((type === '*' || type === 'br') && (!priority || parseFloat(priority) > 0)) {
115
+ const [type, priority] = op.trim().split(";q=");
116
+ if ((type === "*" || type === "br") && (!priority || parseFloat(priority) > 0)) {
131
117
  return true;
132
118
  }
133
119
  }
134
120
  }
135
121
  return false;
136
- }
137
-
138
- /**
139
- * Given an array of extra script strings / objects, it returns an object with
140
- * arrays of scripts to inject in different HTML template locations. During
141
- * the script groupping it also filters out any empty scripts.
142
- * @param {({
143
- * code: string;
144
- * location: string;
145
- * }|string)[]} [scripts=[]]
146
- * @return {{
147
- * BODY_OPEN: string[];
148
- * DEFAULT: string[];
149
- * HEAD_OPEN: string[];
150
- * }}
151
- */
122
+ } /**
123
+ * Given an array of extra script strings / objects, it returns an object with
124
+ * arrays of scripts to inject in different HTML template locations. During
125
+ * the script groupping it also filters out any empty scripts.
126
+ * @param {({
127
+ * code: string;
128
+ * location: string;
129
+ * }|string)[]} [scripts=[]]
130
+ * @return {{
131
+ * BODY_OPEN: string[];
132
+ * DEFAULT: string[];
133
+ * HEAD_OPEN: string[];
134
+ * }}
135
+ */
152
136
  function groupExtraScripts(scripts = []) {
153
137
  const res = {
154
- [SCRIPT_LOCATIONS.BODY_OPEN]: '',
155
- [SCRIPT_LOCATIONS.DEFAULT]: '',
156
- [SCRIPT_LOCATIONS.HEAD_OPEN]: ''
138
+ [SCRIPT_LOCATIONS.BODY_OPEN]: "",
139
+ [SCRIPT_LOCATIONS.DEFAULT]: "",
140
+ [SCRIPT_LOCATIONS.HEAD_OPEN]: ""
157
141
  };
158
142
  for (const script of scripts) {
159
- if (typeof script === 'string') {
143
+ if (typeof script === "string") {
160
144
  if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;
161
145
  } else if (script.code) {
162
146
  if (script.location in res) res[script.location] += script.code;else throw Error(`Invalid location "${script.location}"`);
163
147
  }
164
148
  }
165
149
  return res;
166
- }
167
-
168
- /**
169
- * Creates a new default (Winston) logger.
170
- * @param {object} [options={}]
171
- * @param {string} [options.defaultLogLevel='info']
172
- * @return {object}
173
- */
150
+ } /**
151
+ * Creates a new default (Winston) logger.
152
+ * @param {object} [options={}]
153
+ * @param {string} [options.defaultLogLevel='info']
154
+ * @return {object}
155
+ */
174
156
  export function newDefaultLogger({
175
- defaultLogLevel = 'info'
157
+ defaultLogLevel = "info"
176
158
  } = {}) {
177
159
  const {
178
160
  format,
@@ -196,38 +178,37 @@ export function newDefaultLogger({
196
178
  level: defaultLogLevel,
197
179
  transports: [new transports.Console()]
198
180
  });
199
- }
200
- /**
201
- * Creates the middleware.
202
- * @param webpackConfig
203
- * @param options Additional options:
204
- * @param [options.Application] The root ReactJS component of
205
- * the app to use for the server-side rendering. When not provided
206
- * the server-side rendering is disabled.
207
- * @param [options.buildInfo] "Build info" object to use. If provided,
208
- * it will be used, instead of trying to load from the filesystem the one
209
- * generated by the Webpack build. It is intended for test environments,
210
- * where passing this stuff via file system is no bueno.
211
- * @param [options.favicon] `true` will include favicon
212
- * link into the rendered HTML templates.
213
- * @param [options.noCsp] `true` means that no
214
- * Content-Security-Policy (CSP) is used by server, thus the renderer
215
- * may cut a few corners.
216
- * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.
217
- * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,
218
- * defaults to 1 second.
219
- * @param [options.staticCacheSize=1.e7] The maximum
220
- * static cache size in bytes. Defaults to ~10 MB.
221
- * @param [options.staticCacheController] When given, it activates,
222
- * and controls the static caching of generated HTML markup. When this function
223
- * is provided, on each incoming request it is triggered with the request
224
- * passed in as the argument. To attempt to serve the response from the cache
225
- * it should return the object with the following fields:
226
- * - `key: string` – the cache key for the response;
227
- * - `maxage?: number` – the maximum age of cached result in ms.
228
- * If undefined - infinite age is assumed.
229
- * @return Created middleware.
230
- */
181
+ } /**
182
+ * Creates the middleware.
183
+ * @param webpackConfig
184
+ * @param options Additional options:
185
+ * @param [options.Application] The root ReactJS component of
186
+ * the app to use for the server-side rendering. When not provided
187
+ * the server-side rendering is disabled.
188
+ * @param [options.buildInfo] "Build info" object to use. If provided,
189
+ * it will be used, instead of trying to load from the filesystem the one
190
+ * generated by the Webpack build. It is intended for test environments,
191
+ * where passing this stuff via file system is no bueno.
192
+ * @param [options.favicon] `true` will include favicon
193
+ * link into the rendered HTML templates.
194
+ * @param [options.noCsp] `true` means that no
195
+ * Content-Security-Policy (CSP) is used by server, thus the renderer
196
+ * may cut a few corners.
197
+ * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.
198
+ * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,
199
+ * defaults to 1 second.
200
+ * @param [options.staticCacheSize=1.e7] The maximum
201
+ * static cache size in bytes. Defaults to ~10 MB.
202
+ * @param [options.staticCacheController] When given, it activates,
203
+ * and controls the static caching of generated HTML markup. When this function
204
+ * is provided, on each incoming request it is triggered with the request
205
+ * passed in as the argument. To attempt to serve the response from the cache
206
+ * it should return the object with the following fields:
207
+ * - `key: string` – the cache key for the response;
208
+ * - `maxage?: number` – the maximum age of cached result in ms.
209
+ * If undefined - infinite age is assumed.
210
+ * @return Created middleware.
211
+ */
231
212
  export default function factory(webpackConfig, options) {
232
213
  const ops = defaults({
233
214
  ...options
@@ -236,36 +217,27 @@ export default function factory(webpackConfig, options) {
236
217
  maxSsrRounds: 10,
237
218
  ssrTimeout: 1000,
238
219
  staticCacheSize: 1.e7
239
- });
240
-
241
- // Note: in normal use the default logger is created and set in the root
220
+ }); // Note: in normal use the default logger is created and set in the root
242
221
  // server function, and this initialization is for testing uses, where
243
222
  // renderer is imported directly.
244
223
  ops.logger ??= newDefaultLogger({
245
224
  defaultLogLevel: ops.defaultLoggerLogLevel
246
225
  });
247
226
  const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context);
248
- setBuildInfo(buildInfo);
249
-
250
- // publicPath from webpack.output has a trailing slash at the end.
227
+ setBuildInfo(buildInfo); // publicPath from webpack.output has a trailing slash at the end.
251
228
  const {
252
229
  path: outputPath,
253
230
  publicPath
254
231
  } = webpackConfig.output;
255
- const manifestLink = fs.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : '';
256
-
257
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
258
-
232
+ const manifestLink = fs.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : ""; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
259
233
  const cache = ops.staticCacheController ? new Cache(ops.staticCacheSize) : null;
260
- const CHUNK_GROUPS = readChunkGroupsJson(outputPath);
261
-
262
- // TODO: Look at it later.
234
+ const CHUNK_GROUPS = readChunkGroupsJson(outputPath); // TODO: Look at it later.
263
235
  // eslint-disable-next-line complexity
264
236
  return async (req, res, next) => {
265
237
  try {
266
238
  // Ensures any caches always revalidate HTML markup before reuse.
267
- res.set('Cache-Control', 'no-cache');
268
- res.cookie('csrfToken', req.csrfToken());
239
+ res.set("Cache-Control", "no-cache");
240
+ res.cookie("csrfToken", req.csrfToken());
269
241
  let cacheRef;
270
242
  if (cache) {
271
243
  cacheRef = ops.staticCacheController(req);
@@ -277,8 +249,8 @@ export default function factory(webpackConfig, options) {
277
249
  status
278
250
  } = data;
279
251
  if (ops.noCsp && isBrotliAcceptable(req)) {
280
- res.set('Content-Type', 'text/html');
281
- res.set('Content-Encoding', 'br');
252
+ res.set("Content-Type", "text/html");
253
+ res.set("Content-Encoding", "br");
282
254
  if (status !== 200) res.status(status);
283
255
  res.send(buffer);
284
256
  } else {
@@ -290,9 +262,7 @@ export default function factory(webpackConfig, options) {
290
262
  // TODO: Starting from Node v15 we'll be able to use string's
291
263
  // .replaceAll() method instead relying on reg. expression for
292
264
  // global matching.
293
- const regex = new RegExp(buffer.nonce, 'g');
294
-
295
- // TODO: It should be implemented more careful.
265
+ const regex = new RegExp(buffer.nonce, "g"); // TODO: It should be implemented more careful.
296
266
  h = h.replace(regex, req.nonce);
297
267
  }
298
268
  if (status !== 200) res.status(status);
@@ -313,14 +283,12 @@ export default function factory(webpackConfig, options) {
313
283
  initialState
314
284
  } = await brr;
315
285
  const [cipher, iv] = prepareCipher(buildInfo.key);
316
- let helmet;
317
-
318
- // Gets the mapping between code chunk names and their asset files.
286
+ let helmet; // Gets the mapping between code chunk names and their asset files.
319
287
  // These data come from the Webpack compilation, either from the stats
320
288
  // attached to the request (in dev mode), or from a file output during
321
289
  // the build (in prod mode).
322
290
  let chunkGroups;
323
- const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');
291
+ const webpackStats = get(res.locals, "webpack.devMiddleware.stats");
324
292
  if (webpackStats) {
325
293
  chunkGroups = mapValues(webpackStats.toJson({
326
294
  all: false,
@@ -328,23 +296,17 @@ export default function factory(webpackConfig, options) {
328
296
  }).namedChunkGroups, item => item.assets?.map(({
329
297
  name
330
298
  }) => name) ?? []);
331
- } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;else chunkGroups = {};
332
-
333
- /* Optional server-side rendering. */
299
+ } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;else chunkGroups = {}; /* Optional server-side rendering. */
334
300
  const App = ops.Application;
335
- let appHtmlMarkup = '';
301
+ let appHtmlMarkup = "";
336
302
  const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);
337
303
  let stream;
338
304
  if (App) {
339
- const ssrStart = Date.now();
340
-
341
- // TODO: Somehow, without it TS does not realise that
305
+ const ssrStart = Date.now(); // TODO: Somehow, without it TS does not realise that
342
306
  // App has been checked to exist.
343
307
  const App2 = App;
344
308
  const renderPass = async () => new Promise((resolveArg, rejectArg) => {
345
- ssrContext.chunks = [];
346
-
347
- // NOTE: JS does not have problems if resolve() and reject() methods
309
+ ssrContext.chunks = []; // NOTE: JS does not have problems if resolve() and reject() methods
348
310
  // of a Promise are called multiple times, with different arguments;
349
311
  // it only respects the first call, and ignores subsequent ones.
350
312
  // We, however, really want to assert that here, to safeguard against
@@ -352,19 +314,17 @@ export default function factory(webpackConfig, options) {
352
314
  // if any.
353
315
  let error;
354
316
  const resolve = arg => {
355
- if (error !== undefined) throw Error('Internal error');
317
+ if (error !== undefined) throw Error("Internal error");
356
318
  error = null;
357
319
  resolveArg(arg);
358
320
  };
359
321
  const reject = arg => {
360
322
  if (error !== undefined && error !== arg) {
361
- throw Error('Internal error');
323
+ throw Error("Internal error");
362
324
  }
363
325
  error = arg;
364
326
  rejectArg(arg);
365
- };
366
-
367
- // TODO: prerenderToNodeStream has (abort) "signal" option,
327
+ }; // TODO: prerenderToNodeStream has (abort) "signal" option,
368
328
  // and we should wire it up to the SSR timeout below.
369
329
  const helmetContext = {};
370
330
  void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider, {
@@ -403,7 +363,7 @@ export default function factory(webpackConfig, options) {
403
363
  stream = await renderPass();
404
364
  logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)` : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;
405
365
  } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;
406
- ops.logger.log(ssrContext.dirty ? 'warn' : 'info', logMsg);
366
+ ops.logger.log(ssrContext.dirty ? "warn" : "info", logMsg);
407
367
  if (ssrContext.redirectTo) {
408
368
  res.redirect(ssrContext.status, ssrContext.redirectTo);
409
369
  return;
@@ -417,13 +377,11 @@ export default function factory(webpackConfig, options) {
417
377
  }
418
378
  }));
419
379
  });
420
- }
421
-
422
- /* Encrypts data to be injected into HTML.
423
- * Keep in mind, that this encryption is no way secure: as the JS bundle
424
- * contains decryption key and is able to decode it at the client side.
425
- * Hovewer, for a number of reasons, encryption of injected data is still
426
- * better than injection of a plain text. */
380
+ } /* Encrypts data to be injected into HTML.
381
+ * Keep in mind, that this encryption is no way secure: as the JS bundle
382
+ * contains decryption key and is able to decode it at the client side.
383
+ * Hovewer, for a number of reasons, encryption of injected data is still
384
+ * better than injection of a plain text. */
427
385
  const payload = serializeJs({
428
386
  CHUNK_GROUPS: chunkGroups,
429
387
  CONFIG: configToInject ?? sanitizedConfig,
@@ -432,10 +390,8 @@ export default function factory(webpackConfig, options) {
432
390
  ignoreFunction: true,
433
391
  unsafe: true
434
392
  });
435
- const INJ = Buffer.concat([iv, cipher.update(payload, 'utf8'), cipher.final()]).toString('base64');
436
- const chunkSet = new Set();
437
-
438
- // TODO: "main" chunk has to be added explicitly,
393
+ const INJ = Buffer.concat([iv, cipher.update(payload, "utf8"), cipher.final()]).toString("base64");
394
+ const chunkSet = new Set(); // TODO: "main" chunk has to be added explicitly,
439
395
  // because unlike all other chunks they are not managed by <CodeSplit>
440
396
  // component, thus they are not added to the ssrContext.chunks
441
397
  // automatically. Actually, names of these entry chunks should be
@@ -443,7 +399,7 @@ export default function factory(webpackConfig, options) {
443
399
  // remove or add other entry points, but it requires additional
444
400
  // efforts to figure out how to automatically order them right,
445
401
  // thus for now this handles the default config.
446
- ['main', ...ssrContext.chunks].forEach(chunk => {
402
+ ["main", ...ssrContext.chunks].forEach(chunk => {
447
403
  const assets = chunkGroups[chunk];
448
404
  if (assets) {
449
405
  assets.forEach(asset => {
@@ -451,29 +407,28 @@ export default function factory(webpackConfig, options) {
451
407
  });
452
408
  }
453
409
  });
454
- let styleChunkString = '';
455
- let scriptChunkString = '';
410
+ let styleChunkString = "";
411
+ let scriptChunkString = "";
456
412
  chunkSet.forEach(chunk => {
457
- if (chunk.endsWith('.css')) {
413
+ if (chunk.endsWith(".css")) {
458
414
  styleChunkString += `<link href="${publicPath}${chunk}" rel="stylesheet">`;
459
- } else if (chunk.endsWith('.js')
460
- // In dev mode HMR adds JS updates into asset arrays,
415
+ } else if (chunk.endsWith(".js") // In dev mode HMR adds JS updates into asset arrays,
461
416
  // and they (updates) should be ignored.
462
- && !chunk.endsWith('.hot-update.js')) {
417
+ && !chunk.endsWith(".hot-update.js")) {
463
418
  scriptChunkString += `<script src="${publicPath}${chunk}" type="application/javascript"></script>`;
464
419
  }
465
420
  });
466
421
  const grouppedExtraScripts = groupExtraScripts(extraScripts);
467
- const faviconLink = ops.favicon ? '<link rel="shortcut icon" href="/favicon.ico">' : '';
422
+ const faviconLink = ops.favicon ? "<link rel=\"shortcut icon\" href=\"/favicon.ico\">" : "";
468
423
  const html = `<!DOCTYPE html>
469
424
  <html lang="en">
470
425
  <head>
471
426
  ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}
472
- ${helmet?.title.toString() ?? ''}
473
- ${helmet?.meta.toString() ?? ''}
427
+ ${helmet?.title.toString() ?? ""}
428
+ ${helmet?.meta.toString() ?? ""}
474
429
  <meta name="theme-color" content="#FFFFFF">
475
430
  ${manifestLink}
476
- ${helmet?.link.toString() ?? ''}${styleChunkString}
431
+ ${helmet?.link.toString() ?? ""}${styleChunkString}
477
432
  ${faviconLink}
478
433
  <meta charset="utf-8">
479
434
  <meta
@@ -507,9 +462,7 @@ export default function factory(webpackConfig, options) {
507
462
  }
508
463
  });
509
464
  });
510
- }
511
-
512
- // Note: as caching code above may throw in some cases, sending response
465
+ } // Note: as caching code above may throw in some cases, sending response
513
466
  // before it completes will likely hide the error, making it difficult
514
467
  // to debug. Thus, at least for now, lets send response after it.
515
468
  res.send(html);