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