@dr.pogodin/react-utils 1.46.2 → 1.47.0-alpha.11

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 (332) hide show
  1. package/babel.config.js +1 -0
  2. package/babel.libweb.config.js +16 -0
  3. package/babel.module.config.js +11 -0
  4. package/bin/build.js +21 -11
  5. package/bin/setup.js +11 -9
  6. package/build/development/client/getInj.js +57 -44
  7. package/build/development/client/getInj.js.map +1 -1
  8. package/build/development/client/index.js +15 -21
  9. package/build/development/client/index.js.map +1 -1
  10. package/build/development/client/init.js +2 -6
  11. package/build/development/client/init.js.map +1 -1
  12. package/build/development/index.js +3 -177
  13. package/build/development/index.js.map +1 -1
  14. package/build/development/server/Cache.js +1 -8
  15. package/build/development/server/Cache.js.map +1 -1
  16. package/build/development/server/index.js +22 -45
  17. package/build/development/server/index.js.map +1 -1
  18. package/build/development/server/renderer.js +84 -86
  19. package/build/development/server/renderer.js.map +1 -1
  20. package/build/development/server/server.js +58 -60
  21. package/build/development/server/server.js.map +1 -1
  22. package/build/development/server/utils/errors.js +8 -31
  23. package/build/development/server/utils/errors.js.map +1 -1
  24. package/build/development/server/utils/index.js +2 -9
  25. package/build/development/server/utils/index.js.map +1 -1
  26. package/build/development/shared/components/Button/index.js +15 -22
  27. package/build/development/shared/components/Button/index.js.map +1 -1
  28. package/build/development/shared/components/Checkbox/index.js +14 -21
  29. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  30. package/build/development/shared/components/GenericLink/index.js +9 -11
  31. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  32. package/build/development/shared/components/Input/index.js +21 -27
  33. package/build/development/shared/components/Input/index.js.map +1 -1
  34. package/build/development/shared/components/Link.js +6 -13
  35. package/build/development/shared/components/Link.js.map +1 -1
  36. package/build/development/shared/components/Modal/index.js +24 -28
  37. package/build/development/shared/components/Modal/index.js.map +1 -1
  38. package/build/development/shared/components/NavLink.js +6 -13
  39. package/build/development/shared/components/NavLink.js.map +1 -1
  40. package/build/development/shared/components/PageLayout/index.js +13 -20
  41. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  42. package/build/development/shared/components/TextArea/index.js +28 -31
  43. package/build/development/shared/components/TextArea/index.js.map +1 -1
  44. package/build/development/shared/components/Throbber/index.js +13 -20
  45. package/build/development/shared/components/Throbber/index.js.map +1 -1
  46. package/build/development/shared/components/WithTooltip/Tooltip.js +13 -18
  47. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  48. package/build/development/shared/components/WithTooltip/index.js +23 -30
  49. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  50. package/build/development/shared/components/YouTubeVideo/index.js +19 -26
  51. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  52. package/build/development/shared/components/index.js +16 -130
  53. package/build/development/shared/components/index.js.map +1 -1
  54. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +19 -20
  55. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  56. package/build/development/shared/components/selectors/CustomDropdown/index.js +35 -39
  57. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  58. package/build/development/shared/components/selectors/NativeDropdown/index.js +31 -31
  59. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  60. package/build/development/shared/components/selectors/Switch/index.js +19 -24
  61. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  62. package/build/development/shared/components/selectors/common.js +1 -7
  63. package/build/development/shared/components/selectors/common.js.map +1 -1
  64. package/build/development/shared/components/selectors/index.js +3 -27
  65. package/build/development/shared/components/selectors/index.js.map +1 -1
  66. package/build/development/shared/utils/config.js +40 -21
  67. package/build/development/shared/utils/config.js.map +1 -1
  68. package/build/development/shared/utils/globalState.js +3 -8
  69. package/build/development/shared/utils/globalState.js.map +1 -1
  70. package/build/development/shared/utils/index.js +12 -89
  71. package/build/development/shared/utils/index.js.map +1 -1
  72. package/build/development/shared/utils/isomorphy/buildInfo.js +2 -9
  73. package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
  74. package/build/development/shared/utils/isomorphy/environment-check.js +2 -8
  75. package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
  76. package/build/development/shared/utils/isomorphy/index.js +7 -32
  77. package/build/development/shared/utils/isomorphy/index.js.map +1 -1
  78. package/build/development/shared/utils/jest/E2eSsrEnv.js +34 -37
  79. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  80. package/build/development/shared/utils/jest/global.js +1 -7
  81. package/build/development/shared/utils/jest/global.js.map +1 -1
  82. package/build/development/shared/utils/jest/index.js +20 -44
  83. package/build/development/shared/utils/jest/index.js.map +1 -1
  84. package/build/development/shared/utils/splitComponent.js +54 -45
  85. package/build/development/shared/utils/splitComponent.js.map +1 -1
  86. package/build/development/shared/utils/time.js +22 -31
  87. package/build/development/shared/utils/time.js.map +1 -1
  88. package/build/development/shared/utils/webpack.js +17 -16
  89. package/build/development/shared/utils/webpack.js.map +1 -1
  90. package/build/production/client/getInj.js +13 -11
  91. package/build/production/client/getInj.js.map +1 -1
  92. package/build/production/client/index.js +3 -3
  93. package/build/production/client/index.js.map +1 -1
  94. package/build/production/client/init.js +2 -2
  95. package/build/production/client/init.js.map +1 -1
  96. package/build/production/index.js +2 -3
  97. package/build/production/index.js.map +1 -1
  98. package/build/production/server/Cache.js +3 -3
  99. package/build/production/server/Cache.js.map +1 -1
  100. package/build/production/server/index.js +8 -8
  101. package/build/production/server/index.js.map +1 -1
  102. package/build/production/server/renderer.js +24 -25
  103. package/build/production/server/renderer.js.map +1 -1
  104. package/build/production/server/server.js +9 -11
  105. package/build/production/server/server.js.map +1 -1
  106. package/build/production/server/utils/errors.js +9 -9
  107. package/build/production/server/utils/errors.js.map +1 -1
  108. package/build/production/server/utils/index.js +2 -1
  109. package/build/production/server/utils/index.js.map +1 -1
  110. package/build/production/shared/components/Button/index.js +4 -4
  111. package/build/production/shared/components/Button/index.js.map +1 -1
  112. package/build/production/shared/components/Checkbox/index.js +1 -1
  113. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  114. package/build/production/shared/components/GenericLink/index.js +4 -4
  115. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  116. package/build/production/shared/components/Input/index.js +5 -5
  117. package/build/production/shared/components/Input/index.js.map +1 -1
  118. package/build/production/shared/components/Link.js +3 -3
  119. package/build/production/shared/components/Link.js.map +1 -1
  120. package/build/production/shared/components/Modal/index.js +7 -7
  121. package/build/production/shared/components/Modal/index.js.map +1 -1
  122. package/build/production/shared/components/NavLink.js +2 -2
  123. package/build/production/shared/components/NavLink.js.map +1 -1
  124. package/build/production/shared/components/PageLayout/index.js +2 -2
  125. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  126. package/build/production/shared/components/TextArea/index.js +5 -5
  127. package/build/production/shared/components/TextArea/index.js.map +1 -1
  128. package/build/production/shared/components/Throbber/index.js +2 -2
  129. package/build/production/shared/components/Throbber/index.js.map +1 -1
  130. package/build/production/shared/components/WithTooltip/Tooltip.js +4 -4
  131. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  132. package/build/production/shared/components/WithTooltip/index.js +4 -4
  133. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  134. package/build/production/shared/components/YouTubeVideo/index.js +4 -4
  135. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  136. package/build/production/shared/components/index.js +3 -1
  137. package/build/production/shared/components/index.js.map +1 -1
  138. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +2 -2
  139. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  140. package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
  141. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  142. package/build/production/shared/components/selectors/NativeDropdown/index.js +4 -4
  143. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  144. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  145. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  146. package/build/production/shared/components/selectors/common.js +2 -2
  147. package/build/production/shared/components/selectors/common.js.map +1 -1
  148. package/build/production/shared/components/selectors/index.js +1 -1
  149. package/build/production/shared/components/selectors/index.js.map +1 -1
  150. package/build/production/shared/utils/config.js +8 -6
  151. package/build/production/shared/utils/config.js.map +1 -1
  152. package/build/production/shared/utils/globalState.js +2 -2
  153. package/build/production/shared/utils/globalState.js.map +1 -1
  154. package/build/production/shared/utils/index.js +1 -1
  155. package/build/production/shared/utils/index.js.map +1 -1
  156. package/build/production/shared/utils/isomorphy/buildInfo.js +3 -3
  157. package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
  158. package/build/production/shared/utils/isomorphy/environment-check.js +3 -3
  159. package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
  160. package/build/production/shared/utils/isomorphy/index.js +4 -4
  161. package/build/production/shared/utils/isomorphy/index.js.map +1 -1
  162. package/build/production/shared/utils/jest/E2eSsrEnv.js +16 -15
  163. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  164. package/build/production/shared/utils/jest/global.js +1 -1
  165. package/build/production/shared/utils/jest/global.js.map +1 -1
  166. package/build/production/shared/utils/jest/index.js +11 -11
  167. package/build/production/shared/utils/jest/index.js.map +1 -1
  168. package/build/production/shared/utils/splitComponent.js +11 -22
  169. package/build/production/shared/utils/splitComponent.js.map +1 -1
  170. package/build/production/shared/utils/time.js +3 -3
  171. package/build/production/shared/utils/time.js.map +1 -1
  172. package/build/production/shared/utils/webpack.js +6 -6
  173. package/build/production/shared/utils/webpack.js.map +1 -1
  174. package/build/types-code/client/getInj.d.ts +1 -2
  175. package/build/types-code/client/index.d.ts +1 -1
  176. package/build/types-code/index.d.ts +1 -7
  177. package/build/types-code/server/index.d.ts +6 -11
  178. package/build/types-code/server/utils/index.d.ts +1 -1
  179. package/build/types-code/shared/utils/config.d.ts +4 -2
  180. package/build/types-code/shared/utils/index.d.ts +2 -2
  181. package/build/types-code/shared/utils/splitComponent.d.ts +6 -4
  182. package/build/web/client/getInj.js +65 -0
  183. package/build/web/client/getInj.js.map +1 -0
  184. package/{src/client/index.tsx → build/web/client/index.js} +13 -24
  185. package/build/web/client/index.js.map +1 -0
  186. package/{src/client/init.ts → build/web/client/init.js} +9 -14
  187. package/build/web/client/init.js.map +1 -0
  188. package/build/web/index.js +11 -0
  189. package/build/web/index.js.map +1 -0
  190. package/{src/server/Cache.ts → build/web/server/Cache.js} +15 -22
  191. package/build/web/server/Cache.js.map +1 -0
  192. package/{src/server/index.ts → build/web/server/index.js} +32 -81
  193. package/build/web/server/index.js.map +1 -0
  194. package/{src/server/renderer.tsx → build/web/server/renderer.js} +188 -333
  195. package/build/web/server/renderer.js.map +1 -0
  196. package/{src/server/server.ts → build/web/server/server.js} +82 -182
  197. package/build/web/server/server.js.map +1 -0
  198. package/{src/server/utils/errors.ts → build/web/server/utils/errors.js} +6 -25
  199. package/build/web/server/utils/errors.js.map +1 -0
  200. package/build/web/server/utils/index.js +4 -0
  201. package/build/web/server/utils/index.js.map +1 -0
  202. package/build/web/shared/components/Button/index.js +90 -0
  203. package/build/web/shared/components/Button/index.js.map +1 -0
  204. package/build/web/shared/components/Checkbox/index.js +35 -0
  205. package/build/web/shared/components/Checkbox/index.js.map +1 -0
  206. package/{src/shared/components/GenericLink/index.tsx → build/web/shared/components/GenericLink/index.js} +44 -78
  207. package/build/web/shared/components/GenericLink/index.js.map +1 -0
  208. package/build/web/shared/components/Input/index.js +71 -0
  209. package/build/web/shared/components/Input/index.js.map +1 -0
  210. package/build/web/shared/components/Link.js +20 -0
  211. package/build/web/shared/components/Link.js.map +1 -0
  212. package/{src → build/web}/shared/components/Modal/base-theme.scss +1 -1
  213. package/build/web/shared/components/Modal/index.js +128 -0
  214. package/build/web/shared/components/Modal/index.js.map +1 -0
  215. package/build/web/shared/components/NavLink.js +13 -0
  216. package/build/web/shared/components/NavLink.js.map +1 -0
  217. package/{src → build/web}/shared/components/PageLayout/base-theme.scss +1 -1
  218. package/{src/shared/components/PageLayout/index.tsx → build/web/shared/components/PageLayout/index.js} +20 -33
  219. package/build/web/shared/components/PageLayout/index.js.map +1 -0
  220. package/build/web/shared/components/TextArea/index.js +106 -0
  221. package/build/web/shared/components/TextArea/index.js.map +1 -0
  222. package/build/web/shared/components/Throbber/index.js +26 -0
  223. package/build/web/shared/components/Throbber/index.js.map +1 -0
  224. package/{src/shared/components/WithTooltip/Tooltip.tsx → build/web/shared/components/WithTooltip/Tooltip.js} +61 -109
  225. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -0
  226. package/build/web/shared/components/WithTooltip/index.js +117 -0
  227. package/build/web/shared/components/WithTooltip/index.js.map +1 -0
  228. package/{src/shared/components/YouTubeVideo/index.tsx → build/web/shared/components/YouTubeVideo/index.js} +23 -40
  229. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -0
  230. package/build/web/shared/components/index.js +18 -0
  231. package/build/web/shared/components/index.js.map +1 -0
  232. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +82 -0
  233. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -0
  234. package/{src/shared/components/selectors/CustomDropdown/index.tsx → build/web/shared/components/selectors/CustomDropdown/index.js} +56 -80
  235. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -0
  236. package/{src/shared/components/selectors/NativeDropdown/index.tsx → build/web/shared/components/selectors/NativeDropdown/index.js} +39 -44
  237. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -0
  238. package/build/web/shared/components/selectors/Switch/index.js +50 -0
  239. package/build/web/shared/components/selectors/Switch/index.js.map +1 -0
  240. package/build/web/shared/components/selectors/common.js +12 -0
  241. package/build/web/shared/components/selectors/common.js.map +1 -0
  242. package/build/web/shared/components/selectors/index.js +4 -0
  243. package/build/web/shared/components/selectors/index.js.map +1 -0
  244. package/build/web/shared/utils/config.js +45 -0
  245. package/build/web/shared/utils/config.js.map +1 -0
  246. package/build/web/shared/utils/globalState.js +15 -0
  247. package/build/web/shared/utils/globalState.js.map +1 -0
  248. package/build/web/shared/utils/index.js +13 -0
  249. package/build/web/shared/utils/index.js.map +1 -0
  250. package/{src/shared/utils/isomorphy/buildInfo.ts → build/web/shared/utils/isomorphy/buildInfo.js} +4 -10
  251. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -0
  252. package/build/web/shared/utils/isomorphy/environment-check.js +17 -0
  253. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -0
  254. package/{src/shared/utils/isomorphy/index.ts → build/web/shared/utils/isomorphy/index.js} +6 -6
  255. package/build/web/shared/utils/isomorphy/index.js.map +1 -0
  256. package/{src/shared/utils/jest/E2eSsrEnv.ts → build/web/shared/utils/jest/E2eSsrEnv.js} +73 -140
  257. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -0
  258. package/build/web/shared/utils/jest/global.js +4 -0
  259. package/build/web/shared/utils/jest/global.js.map +1 -0
  260. package/{src/shared/utils/jest/index.ts → build/web/shared/utils/jest/index.js} +33 -83
  261. package/build/web/shared/utils/jest/index.js.map +1 -0
  262. package/{src/shared/utils/splitComponent.tsx → build/web/shared/utils/splitComponent.js} +77 -124
  263. package/build/web/shared/utils/splitComponent.js.map +1 -0
  264. package/{src/shared/utils/time.ts → build/web/shared/utils/time.js} +21 -37
  265. package/build/web/shared/utils/time.js.map +1 -0
  266. package/build/web/shared/utils/webpack.js +67 -0
  267. package/build/web/shared/utils/webpack.js.map +1 -0
  268. package/config/babel/node-ssr.js +12 -3
  269. package/config/babel/webpack.js +6 -1
  270. package/config/jest/default.js +8 -2
  271. package/config/jest/setup.js +8 -1
  272. package/config/webpack/app-base.js +25 -14
  273. package/config/webpack/app-development.js +2 -2
  274. package/config/webpack/lib-base.js +1 -2
  275. package/package.json +41 -42
  276. package/types.d.ts +1 -6
  277. package/build/development/__chunk_groups__.json +0 -6
  278. package/build/development/style.css +0 -909
  279. package/build/development/web.bundle.js +0 -752
  280. package/build/production/__chunk_groups__.json +0 -6
  281. package/build/production/style.css +0 -2
  282. package/build/production/style.css.map +0 -1
  283. package/build/production/web.bundle.js +0 -3
  284. package/build/production/web.bundle.js.LICENSE.txt +0 -9
  285. package/build/production/web.bundle.js.map +0 -1
  286. package/dev-styles.js +0 -1
  287. package/node-entry.js +0 -15
  288. package/null.js +0 -1
  289. package/prod-styles.js +0 -1
  290. package/src/client/getInj.ts +0 -51
  291. package/src/index.ts +0 -73
  292. package/src/server/utils/index.ts +0 -3
  293. package/src/shared/components/Button/index.tsx +0 -130
  294. package/src/shared/components/Checkbox/index.tsx +0 -53
  295. package/src/shared/components/Input/index.tsx +0 -96
  296. package/src/shared/components/Link.tsx +0 -25
  297. package/src/shared/components/Modal/index.tsx +0 -177
  298. package/src/shared/components/NavLink.tsx +0 -18
  299. package/src/shared/components/TextArea/index.tsx +0 -139
  300. package/src/shared/components/Throbber/index.tsx +0 -28
  301. package/src/shared/components/WithTooltip/index.tsx +0 -186
  302. package/src/shared/components/index.ts +0 -20
  303. package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
  304. package/src/shared/components/selectors/Switch/index.tsx +0 -74
  305. package/src/shared/components/selectors/common.ts +0 -57
  306. package/src/shared/components/selectors/index.ts +0 -8
  307. package/src/shared/utils/config.ts +0 -28
  308. package/src/shared/utils/globalState.ts +0 -44
  309. package/src/shared/utils/index.ts +0 -45
  310. package/src/shared/utils/isomorphy/environment-check.ts +0 -18
  311. package/src/shared/utils/jest/global.ts +0 -17
  312. package/src/shared/utils/webpack.ts +0 -74
  313. /package/{src → build/web}/shared/components/Button/style.scss +0 -0
  314. /package/{src → build/web}/shared/components/Checkbox/theme.scss +0 -0
  315. /package/{src → build/web}/shared/components/GenericLink/style.scss +0 -0
  316. /package/{src → build/web}/shared/components/Input/theme.scss +0 -0
  317. /package/{src → build/web}/shared/components/Modal/styles.scss +0 -0
  318. /package/{src → build/web}/shared/components/TextArea/style.scss +0 -0
  319. /package/{src → build/web}/shared/components/Throbber/theme.scss +0 -0
  320. /package/{src → build/web}/shared/components/WithTooltip/default-theme.scss +0 -0
  321. /package/{src → build/web}/shared/components/YouTubeVideo/base.scss +0 -0
  322. /package/{src → build/web}/shared/components/YouTubeVideo/throbber.scss +0 -0
  323. /package/{src → build/web}/shared/components/selectors/CustomDropdown/Options/style.scss +0 -0
  324. /package/{src → build/web}/shared/components/selectors/CustomDropdown/theme.scss +0 -0
  325. /package/{src → build/web}/shared/components/selectors/NativeDropdown/theme.scss +0 -0
  326. /package/{src → build/web}/shared/components/selectors/Switch/theme.scss +0 -0
  327. /package/{src → build/web}/styles/_global/reset.css +0 -0
  328. /package/{src → build/web}/styles/_mixins/fonts.scss +0 -0
  329. /package/{src → build/web}/styles/_mixins/media.scss +0 -0
  330. /package/{src → build/web}/styles/_mixins/typography.scss +0 -0
  331. /package/{src → build/web}/styles/global.scss +0 -0
  332. /package/{src → build/web}/styles/mixins.scss +0 -0
@@ -1,12 +1,14 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ServerSsrContext=exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _nodeFs=_interopRequireDefault(require("node:fs"));var _nodePath=_interopRequireDefault(require("node:path"));var _nodeStream=require("node:stream");var _nodeZlib=require("node:zlib");var _winston=_interopRequireDefault(require("winston"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _jsUtils=require("@dr.pogodin/js-utils");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _static=require("react-dom/static");var _reactHelmet=require("@dr.pogodin/react-helmet");var _reactRouter=require("react-router");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _buildInfo=require("../shared/utils/isomorphy/buildInfo");var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
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.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";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.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";/**
2
2
  * ExpressJS middleware for server-side rendering of a ReactJS app.
3
- */const sanitizedConfig=(0,_lodash.omit)(_config.default,"SECRET");// Note: These type definitions for logger are copied from Winston logger,
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 winston from"winston";import{GlobalStateProvider,SsrContext}from"@dr.pogodin/react-global-state";import{timer}from"@dr.pogodin/js-utils";import{cloneDeep,defaults,get,mapValues}from"lodash-es";import config from"config";import{prerenderToNodeStream}from"react-dom/static";import{HelmetProvider}from"@dr.pogodin/react-helmet";import{StaticRouter}from"react-router";import serializeJs from"serialize-javascript";import{setBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";import Cache from"./Cache.js";// @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
4
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5
+ import{jsx as _jsx}from"react/jsx-runtime";const{SECRET,...sanitizedConfig}=config;// Note: These type definitions for logger are copied from Winston logger,
4
6
  // then simplified to make it easier to fit an alternative logger into this
5
7
  // interface.
6
8
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
7
9
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
8
10
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
9
- let SCRIPT_LOCATIONS=exports.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}({});class ServerSsrContext extends _reactGlobalState.SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super((0,_lodash.cloneDeep)(initialState)??{});this.chunkGroups=chunkGroups;this.req=req}}exports.ServerSsrContext=ServerSsrContext;/**
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}}/**
10
12
  * Reads build-time information about the app. This information is generated
11
13
  * by our standard Webpack config for apps, and it is written into
12
14
  * ".build-info" file in the context folder specified in Webpack config.
@@ -14,26 +16,25 @@ let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCAT
14
16
  * suitable for cryptographical use.
15
17
  * @param context Webpack context path used during the build.
16
18
  * @return Resolves to the build-time information.
17
- */function getBuildInfo(context){const url=_nodePath.default.resolve(context,".build-info");return JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}/**
19
+ */function getBuildInfo(context){const url=path.resolve(context,".build-info");return JSON.parse(fs.readFileSync(url,"utf8"))}/**
18
20
  * Attempts to read from disk the named chunk groups mapping generated
19
21
  * by Webpack during the compilation.
20
22
  * It will not work for development builds, where these stats should be captured
21
23
  * via compilator callback.
22
24
  * @param buildDir
23
25
  * @return
24
- */function readChunkGroupsJson(buildDir){const url=_nodePath.default.resolve(buildDir,"__chunk_groups__.json");let res;try{res=JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}catch{// TODO: Should we message the error here somehow?
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?
25
27
  res=null}return res}/**
26
28
  * Prepares a new Cipher for data encryption.
27
- * @param key Encryption key (32-bit random key is expected, see
28
- * node-forge documentation, in case of doubts).
29
- * @return Resolves to the object with two fields:
29
+ * @param key Encryption key (32-bit random, Base64-encoded key is expected).
30
+ * @return Returns a tuple of:
30
31
  * 1. cipher - a new Cipher, ready for encryption;
31
32
  * 2. iv - initial vector used by the cipher.
32
- */async function prepareCipher(key){return new Promise((resolve,reject)=>{_nodeForge.default.random.getBytes(32,(err,iv)=>{if(err)reject(err);else{const cipher=_nodeForge.default.cipher.createCipher("AES-CBC",key);cipher.start({iv});resolve({cipher,iv})}})})}/**
33
+ */function prepareCipher(key){const iv=randomBytes(16);const cipher=createCipheriv("AES-256-CBC",Buffer.from(key,"base64"),iv);return[cipher,iv]}/**
33
34
  * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
34
35
  * are acceptable to the caller.
35
36
  * @param req
36
- */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}/**
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}/**
37
38
  * Given an array of extra script strings / objects, it returns an object with
38
39
  * arrays of scripts to inject in different HTML template locations. During
39
40
  * the script groupping it also filters out any empty scripts.
@@ -46,12 +47,12 @@ res=null}return res}/**
46
47
  * DEFAULT: string[];
47
48
  * HEAD_OPEN: string[];
48
49
  * }}
49
- */function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if((0,_lodash.isString)(script)){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}/**
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}/**
50
51
  * Creates a new default (Winston) logger.
51
52
  * @param {object} [options={}]
52
53
  * @param {string} [options.defaultLogLevel='info']
53
54
  * @return {object}
54
- */function newDefaultLogger({defaultLogLevel="info"}={}){const{format,transports}=_winston.default;return _winston.default.createLogger({format:format.combine(format.splat(),format.timestamp(),format.colorize(),format.printf(({level,message,timestamp,stack,...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]})}/**
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,timestamp,stack,...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]})}/**
55
56
  * Creates the middleware.
56
57
  * @param webpackConfig
57
58
  * @param options Additional options:
@@ -81,25 +82,23 @@ res=null}return res}/**
81
82
  * - `maxage?: number` – the maximum age of cached result in ms.
82
83
  * If undefined - infinite age is assumed.
83
84
  * @return Created middleware.
84
- */function factory(webpackConfig,options){const ops=(0,_lodash.defaults)((0,_lodash.clone)(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
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
85
86
  // server function, and this initialization is for testing uses, where
86
87
  // renderer is imported directly.
87
- ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);(0,_buildInfo.setBuildInfo)(buildInfo);// publicPath from webpack.output has a trailing slash at the end.
88
- const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=_nodeFs.default.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
89
- const cache=ops.staticCacheController?new _Cache.default(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
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{publicPath,path:outputPath}=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.
90
91
  // eslint-disable-next-line complexity
91
92
  return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
92
- 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)=>{(0,_nodeZlib.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
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
93
94
  // .replaceAll() method instead relying on reg. expression for
94
95
  // global matching.
95
96
  const regex=new RegExp(buffer.nonce,"g");// TODO: It should be implemented more careful.
96
- 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},{cipher,iv}]=await Promise.all([// NOTE: Written this way to avoid triggering the "await-thenable"
97
- // ESLint rule.
98
- brr instanceof Promise?brr:Promise.resolve(brr),prepareCipher(buildInfo.key)]);let helmet;// Gets the mapping between code chunk names and their asset files.
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.
99
98
  // These data come from the Webpack compilation, either from the stats
100
99
  // attached to the request (in dev mode), or from a file output during
101
100
  // the build (in prod mode).
102
- let chunkGroups;const webpackStats=(0,_lodash.get)(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=(0,_lodash.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
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
103
102
  // App has been checked to exist.
104
103
  const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ssrContext.chunks=[];// NOTE: JS does not have problems if resolve() and reject() methods
105
104
  // of a Promise are called multiple times, with different arguments;
@@ -109,14 +108,14 @@ const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ss
109
108
  // if any.
110
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,
111
110
  // and we should wire it up to the SSR timeout below.
112
- const helmetContext={};void(0,_static.prerenderToNodeStream)(/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactRouter.StaticRouter,{location:req.url,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactHelmet.HelmetProvider,{context:helmetContext,children:/*#__PURE__*/(0,_jsxRuntime.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),(0,_jsUtils.timer)(timeout).then(()=>false)]));if(bailed)break}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
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
113
112
  // to ensure the correct hydration when some pending promises have
114
113
  // resolved and placed their data into the initial global state.
115
- 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 _nodeStream.Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done()}}))})}/* Encrypts data to be injected into HTML.
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.
116
115
  * Keep in mind, that this encryption is no way secure: as the JS bundle
117
116
  * contains decryption key and is able to decode it at the client side.
118
117
  * Hovewer, for a number of reasons, encryption of injected data is still
119
- * better than injection of a plain text. */const payload=(0,_serializeJavascript.default)({CHUNK_GROUPS:chunkGroups,CONFIG:configToInject??sanitizedConfig,ISTATE:ssrContext.state},{ignoreFunction:true,unsafe:true});cipher.update(_nodeForge.default.util.createBuffer(payload,"utf8"));cipher.finish();const INJ=_nodeForge.default.util.encode64(`${iv}${cipher.output.data}`);const chunkSet=new Set;// TODO: "main" chunk has to be added explicitly,
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,
120
119
  // because unlike all other chunks they are not managed by <CodeSplit>
121
120
  // component, thus they are not added to the ssrContext.chunks
122
121
  // automatically. Actually, names of these entry chunks should be
@@ -151,7 +150,7 @@ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} s
151
150
  </body>
152
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,
153
152
  // but it greately simplifies testing, and error reporting.
154
- await new Promise((done,failed)=>{(0,_nodeZlib.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
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
155
154
  // before it completes will likely hide the error, making it difficult
156
155
  // to debug. Thus, at least for now, lets send response after it.
157
156
  res.send(html)}catch(error){next(error)}}}
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["_nodeFs","_interopRequireDefault","require","_nodePath","_nodeStream","_nodeZlib","_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","brr","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","helmetContext","prerenderToNodeStream","jsx","GlobalStateProvider","state","children","StaticRouter","HelmetProvider","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","logMsg","log","redirectTo","redirect","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","link","brotliCompress","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\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 get,\n isString,\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 { type HelmetDataContext, 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, SsrContextT } from 'utils/globalState';\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 redirectTo?: 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,\n config: ConfigT,\n) => 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` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; 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 ArrayBuffer {\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 brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n // NOTE: Written this way to avoid triggering the \"await-thenable\"\n // ESLint rule.\n brr instanceof Promise ? brr : Promise.resolve(brr),\n\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 () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\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 void 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: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\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 if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\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?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${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 if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\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":"kUAIA,IAAAA,OAAA,CAAAC,sBAAA,CAAAC,OAAA,aACA,IAAAC,SAAA,CAAAF,sBAAA,CAAAC,OAAA,eACA,IAAAE,WAAA,CAAAF,OAAA,gBACA,IAAAG,SAAA,CAAAH,OAAA,cAKA,IAAAI,QAAA,CAAAL,sBAAA,CAAAC,OAAA,aAEA,IAAAK,iBAAA,CAAAL,OAAA,mCACA,IAAAM,QAAA,CAAAN,OAAA,yBAEA,IAAAO,OAAA,CAAAP,OAAA,WAUA,IAAAQ,OAAA,CAAAT,sBAAA,CAAAC,OAAA,YACA,IAAAS,UAAA,CAAAV,sBAAA,CAAAC,OAAA,gBAEA,IAAAU,OAAA,CAAAV,OAAA,qBACA,IAAAW,YAAA,CAAAX,OAAA,6BACA,IAAAY,YAAA,CAAAZ,OAAA,iBACA,IAAAa,oBAAA,CAAAd,sBAAA,CAAAC,OAAA,0BACA,IAAAc,UAAA,CAAAd,OAAA,wCAIA,IAAAe,MAAA,CAAAhB,sBAAA,CAAAC,OAAA,aAA4B,IAAAgB,WAAA,CAAAhB,OAAA,sBAtC5B;AACA;AACA,GAsCA,KAAM,CAAAiB,eAAe,CAAG,GAAAC,YAAI,EAACC,eAAM,CAAE,QAAQ,CAAC,CAE9C;AACA;AACA;AACA;AAMA;AAMA;AAAA,GASY,CAAAC,gBAAgB,CAAAC,OAAA,CAAAD,gBAAA,uBAAhBA,gBAAgB,EAAhBA,gBAAgB,0BAAhBA,gBAAgB,sBAAhBA,gBAAgB,gCAAhB,CAAAA,gBAAgB,MAMrB,KAAM,CAAAE,gBAAgB,QACnB,CAAAC,4BACuB,CAG/BC,MAAM,CAAa,EAAE,CAMrBC,MAAM,CAAW,GAAG,CAEpBC,WAAWA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AAC,CAC9DkC,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACApF,GAAG,CAACmF,IAAI,CAACK,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdZ,IAAI,CAACY,KAAK,CACZ,CACF,CACF","ignoreList":[]}
1
+ {"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","cloneDeep","defaults","get","mapValues","config","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, 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, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config;\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 redirectTo?: 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, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\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 (typeof script === 'string') {\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,\n config: ConfigT,\n) => 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` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; 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({ ...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 ArrayBuffer {\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 brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\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 () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\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 void 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: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\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 if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\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\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\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?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${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 if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\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":"k+BAAA;AACA;AACA,GAEA,OAASA,MAAM,KAAQ,aAAa,CACpC,OAAwBC,cAAc,CAAEC,WAAW,KAAQ,aAAa,CACxE,MAAO,CAAAC,EAAE,KAAM,SAAS,CACxB,MAAO,CAAAC,IAAI,KAAM,WAAW,CAC5B,OAASC,QAAQ,KAAQ,aAAa,CACtC,OAASC,cAAc,CAAEC,gBAAgB,KAAQ,WAAW,CAK5D,MAAO,CAAAC,OAAO,KAAM,SAAS,CAE7B,OAASC,mBAAmB,CAAEC,UAAU,KAAQ,gCAAgC,CAChF,OAASC,KAAK,KAAQ,sBAAsB,CAE5C,OACEC,SAAS,CACTC,QAAQ,CACRC,GAAG,CACHC,SAAS,KACJ,WAAW,CAElB,MAAO,CAAAC,MAAM,KAAM,QAAQ,CAE3B,OAASC,qBAAqB,KAAQ,kBAAkB,CACxD,OAAiCC,cAAc,KAAQ,0BAA0B,CACjF,OAASC,YAAY,K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,10 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _nodePath=require("node:path");var _nodeUrl=require("node:url");var _lodash=require("lodash");var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _csurf=_interopRequireDefault(require("@dr.pogodin/csurf"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
1
+ import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";/**
2
2
  * Creation of standard ExpressJS server for ReactJS apps.
3
- */// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
3
+ */import{sep}from"node:path";import{pathToFileURL}from"node:url";import{cloneDeep,mapValues,pick}from"lodash-es";import compression from"compression";import cookieParser from"cookie-parser";import csrf from"@dr.pogodin/csurf";import express from"express";import favicon from"serve-favicon";import helmet from"helmet";import loggerMiddleware from"morgan";import requestIp from"request-ip";import{v4 as uuid}from"uuid";import rendererFactory from"./renderer.js";import{CODES,ERRORS,getErrorForCode,newError}from"./utils/errors.js";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
4
4
  /**
5
5
  * Default Content Security Policy settings.
6
6
  * @ignore
7
- */const defaultCspSettings={directives:(0,_lodash.mapValues)(_helmet.default.contentSecurityPolicy.getDefaultDirectives(),// 'https:' options (automatic re-write of insecure URLs to secure ones)
7
+ */const defaultCspSettings={directives:mapValues(helmet.contentSecurityPolicy.getDefaultDirectives(),// 'https:' options (automatic re-write of insecure URLs to secure ones)
8
8
  // is removed to facilitate local development with HTTP server. In cloud
9
9
  // deployments we assume Apache or Nginx server in front of out app takes
10
10
  // care about such re-writes.
@@ -27,17 +27,17 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
27
27
  * }} A deep copy of default CSP settings object used by `react-utils`,
28
28
  * with the exception of `nonce-xxx` clause in `script-src` directive,
29
29
  * which is added dynamically for each request.
30
- */function getDefaultCspSettings(){return(0,_lodash.cloneDeep)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_lodash.pick)(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return}next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
30
+ */export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings)}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=express();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return}next()})}server.use(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=uuid();// TODO: This is deprecated, but it is kept for now for backward
31
31
  // compatibility. Should be removed sometime later.
32
32
  req2.cspNonce=req2.nonce;// The deep clone is necessary here to ensure that default value can't be
33
33
  // mutated during request processing.
34
- let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}_helmet.default.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use((0,_serveFavicon.default)(options.favicon))}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:")});server.use(_express.default.json({limit:"300kb"}));server.use(_express.default.urlencoded({extended:false}));server.use((0,_cookieParser.default)(options.cookieSignatureSecret));server.use(_requestIp.default.mw());server.use((0,_csurf.default)({cookie:true}));_morgan.default.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use((0,_morgan.default)(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
34
+ let cspSettings=cloneDeep(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}helmet.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use(favicon(options.favicon))}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:")});server.use(express.json({limit:"300kb"}));server.use(express.urlencoded({extended:false}));server.use(cookieParser(options.cookieSignatureSecret));server.use(requestIp.mw());server.use(csrf({cookie:true}));loggerMiddleware.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use(loggerMiddleware(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
35
35
  // then mark it as always present.
36
36
  write:options.logger.info.bind(options.logger)}}));// Note: no matter the "public path", we want the service worker, if any,
37
37
  // to be served from the root, to have all web app pages in its scope.
38
38
  // Thus, this setup to serve it. Probably, need some more configuration
39
39
  // for special cases, but this will do for now.
40
- server.get("/__service-worker.js",_express.default.static(webpackConfig.output?.path??"",{setHeaders:res=>res.set("Cache-Control","no-cache")}));/* Setup of Hot Module Reloading for development environment.
40
+ server.get("/__service-worker.js",express.static(webpackConfig.output?.path??"",{setHeaders:res=>res.set("Cache-Control","no-cache")}));/* Setup of Hot Module Reloading for development environment.
41
41
  * These dependencies are not used, nor installed for production use,
42
42
  * hence we should violate some import-related lint rules. *//* eslint-disable import/no-extraneous-dependencies */if(options.devMode){// This is a workaround for SASS bug:
43
43
  // https://github.com/dart-lang/sdk/issues/27979
@@ -45,9 +45,7 @@ server.get("/__service-worker.js",_express.default.static(webpackConfig.output?.
45
45
  // (in dev mode), and app modules are imported in some unfortunate ways.
46
46
  // TODO: Double-check, what is going on here.
47
47
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
48
- if(!global.location){global.location={href:`${(0,_nodeUrl.pathToFileURL)(process.cwd()).href}${_nodePath.sep}`}}/* eslint-disable @typescript-eslint/no-require-imports */const webpack=require("webpack");// TODO: Figure out the exact type for options, don't wanna waste time on it
49
- // right now.
50
- const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next((0,_errors.newError)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
48
+ if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`}}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const{default:webpackHotMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-hot-middleware");const compiler=webpack(webpackConfig);if(!compiler)throw Error("Internal error");server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,express.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next(newError(ERRORS.NOT_FOUND,CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
51
49
  // what the default ExpressJS error handler does anyway, see:
52
50
  // https://expressjs.com/en/guide/error-handling.html
53
51
  //
@@ -57,6 +55,6 @@ const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMid
57
55
  // though.
58
56
  server.use((error,req,res,next)=>{// TODO: This is needed to correctly handled any errors thrown after
59
57
  // sending initial response to the client.
60
- if(res.headersSent){next(error);return}const status=error.status??_errors.CODES.INTERNAL_SERVER_ERROR;const serverSide=status>=_errors.CODES.INTERNAL_SERVER_ERROR;// Log server-side errors always, client-side at debug level only.
61
- options.logger.log(serverSide?"error":"debug",error.toString());let message=error.message||(0,_errors.getErrorForCode)(status);if(serverSide&&process.env.NODE_ENV==="production"){message=_errors.ERRORS.INTERNAL_SERVER_ERROR}res.status(status).send(message)})}return server}
58
+ if(res.headersSent){next(error);return}const status=error.status??CODES.INTERNAL_SERVER_ERROR;const serverSide=status>=CODES.INTERNAL_SERVER_ERROR;// Log server-side errors always, client-side at debug level only.
59
+ options.logger.log(serverSide?"error":"debug",error.toString());let message=error.message||getErrorForCode(status);if(serverSide&&process.env.NODE_ENV==="production"){message=ERRORS.INTERNAL_SERVER_ERROR}res.status(status).send(message)})}return server}
62
60
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["_nodePath","require","_nodeUrl","_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","cookieSignatureSecret","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 'node:path';\nimport { pathToFileURL } from 'node: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 = Exclude<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 cookieSignatureSecret?: string;\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(options.cookieSignatureSecret));\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":"qOAIA,IAAAA,SAAA,CAAAC,OAAA,cACA,IAAAC,QAAA,CAAAD,OAAA,aAEA,IAAAE,OAAA,CAAAF,OAAA,WAMA,IAAAG,YAAA,CAAAC,sBAAA,CAAAJ,OAAA,iBACA,IAAAK,aAAA,CAAAD,sBAAA,CAAAJ,OAAA,mBACA,IAAAM,MAAA,CAAAF,sBAAA,CAAAJ,OAAA,uBAEA,IAAAO,QAAA,CAAAH,sBAAA,CAAAJ,OAAA,aAQA,IAAAQ,aAAA,CAAAJ,sBAAA,CAAAJ,OAAA,mBACA,IAAAS,OAAA,CAAAL,sBAAA,CAAAJ,OAAA,YACA,IAAAU,OAAA,CAAAN,sBAAA,CAAAJ,OAAA,YACA,IAAAW,UAAA,CAAAP,sBAAA,CAAAJ,OAAA,gBACA,IAAAY,KAAA,CAAAZ,OAAA,SAIA,IAAAa,SAAA,CAAAT,sBAAA,CAAAJ,OAAA,gBAKA,IAAAc,OAAA,CAAAd,OAAA,mBAtCA;AACA;AACA,GA6CA;AAMA;AACA;AACA;AACA,GACA,KAAM,CAAAe,kBAAkB,CAAG,CACzBC,UAAU,CAAE,GAAAC,iBAAS,EACnBC,eAAM,CAACC,qBAAqB,CAACC,oBAAoB,CAAC,CAAC,CAEnD;AACA;AACA;AACA;AACCC,KAAK,EAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,EAAKA,IAAI,GAAK,QAAQ,CAC3E,CACF,CAAC,CACDR,kBAAkB,CAACC,UAAU,CAAC,WAAW,CAAC,CAAG,CAC3C,QAAQ,CAER;AACA;AACA,uBAAuB,CACxB,CAED,CACE,KAAM,CAAAA,UAAU,CAAGD,kBAAkB,CAACC,UAAU,CAAC,YAAY,CAAC,CAC9D,GAAIA,UAAU,CAAEA,UA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6BAA6B,CACjC,GAAI5E,OAAO,CAAC6E,oBAAoB,CAAE,CAChCD,6BAA6B,CAAG,KAAM,CAAA5E,OAAO,CAAC6E,oBAAoB,CAACtE,MAAM,CAC3E,CAEA,oBACA,GAAI,CAACqE,6BAA6B,CAAE,CAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACArE,MAAM,CAACK,GAAG,CAAC,CACTkE,KAEC,CACDjE,GAAY,CACZC,GAAa,CACbC,IAAkB,GACf,CACH;AACA;AACA,GAAID,GAAG,CAACiE,WAAW,CAAE,CACnBhE,IAAI,CAAC+D,KAAK,CAAC,CACX,MACF,CAEA,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAIL,aAAK,CAACM,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAKL,aAAK,CAACM,qBAAgC,CAEpE;AACAjF,OAAO,CAACU,MAAM,CAAEyE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAI,GAAAC,uBAAe,EAACN,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAInB,OAAO,CAACwB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDH,OAAO,CAAGZ,cAAM,CAACQ,qBACnB,CAEAnE,GAAG,CAACkE,MAAM,CAACA,MAAM,CAAC,CAAC9C,IAAI,CAACmD,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAA9E,MACT","ignoreList":[]}
1
+ {"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","csrf","express","favicon","helmet","loggerMiddleware","requestIp","v4","uuid","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","Error","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\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';\n\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 = Exclude<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 cookieSignatureSecret?: string;\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(options.cookieSignatureSecret));\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 const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n if (!compiler) throw Error('Internal error');\n\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":"oRAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,OAASC,SAAS,CAAEC,SAAS,CAAEC,IAAI,KAAQ,WAAW,CAEtD,MAAO,CAAAC,WAAW,KAAM,aAAa,CACrC,MAAO,CAAAC,YAAY,KAAM,eAAe,CACxC,MAAO,CAAAC,IAAI,KAAM,mBAAmB,CAEpC,MAAO,CAAAC,OAAO,KAKP,SAAS,CAEhB,MAAO,CAAAC,OAAO,KAAM,eAAe,CACnC,MAAO,CAAAC,MAAM,KAA8B,QAAQ,CACnD,MAAO,CAAAC,gBAAgB,KAAM,QAAQ,CACrC,MAAO,CAAAC,SAAS,KAAM,YAAY,CAClC,OAASC,EAAE,GAAI,CAAAC,IAAI,KAAQ,MAAM,OAI1B,CAAAC,eAAe,4BAMpBC,KAAK,CACLC,MAAM,CACN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AC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAIrF,eAAe,CAACgF,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIjB,OAAO,CAACqB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAGtF,MAAM,CAACkF,qBACnB,CAEAzD,GAAG,CAACwD,MAAM,CAACA,MAAM,CAAC,CAACvC,IAAI,CAAC4C,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAAnE,MACT","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"CODES",{enumerable:true,get:function(){return _httpStatusCodes.StatusCodes}});Object.defineProperty(exports,"ERRORS",{enumerable:true,get:function(){return _httpStatusCodes.ReasonPhrases}});exports.assert=assert;exports.fail=fail;Object.defineProperty(exports,"getErrorForCode",{enumerable:true,get:function(){return _httpStatusCodes.getReasonPhrase}});exports.newError=newError;var _httpStatusCodes=require("http-status-codes");/**
1
+ /**
2
2
  * @category Utilities
3
3
  * @module server/errors
4
4
  * @desc
@@ -7,7 +7,7 @@
7
7
  * const { errors } = server;
8
8
  * ```
9
9
  * Server-side helpers for error handling.
10
- *//**
10
+ */import{StatusCodes as CODES,ReasonPhrases as ERRORS,getReasonPhrase as getErrorForCode}from"http-status-codes";/**
11
11
  * @static
12
12
  * @const CODES
13
13
  * @desc An alias for
@@ -17,7 +17,7 @@
17
17
  * import { server } from '@dr.pogodin/react-utils';
18
18
  * const { CODES } = server.errors;
19
19
  * console.log(CODES.BAD_REQUEST); // Prints: 400
20
- *//**
20
+ */export{CODES};/**
21
21
  * @static
22
22
  * @const ERRORS
23
23
  * @desc An alias for
@@ -27,7 +27,7 @@
27
27
  * import { server } from '@dr.pogodin/react-utils';
28
28
  * const { ERRORS } = server.errors;
29
29
  * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request
30
- *//**
30
+ */export{ERRORS};/**
31
31
  * @static
32
32
  * @func getErrorForCode
33
33
  * @desc An alias for
@@ -38,8 +38,8 @@
38
38
  * @example
39
39
  * import { server } from '@dr.pogodin/react-utils';
40
40
  * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request
41
- */// TODO: It could accept the status code as a constructor argument.
42
- class ErrorWithStatus extends Error{status=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR}/**
41
+ */export{getErrorForCode};// TODO: It could accept the status code as a constructor argument.
42
+ class ErrorWithStatus extends Error{status=CODES.INTERNAL_SERVER_ERROR}/**
43
43
  * ```js
44
44
  * import { server } from '@dr.pogodin/react-utils';
45
45
  * const { newError } = server.errors;
@@ -50,9 +50,9 @@ class ErrorWithStatus extends Error{status=_httpStatusCodes.StatusCodes.INTERNAL
50
50
  * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal
51
51
  * Server Error).
52
52
  * @return {Error}
53
- */function newError(message,statusCode=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR){const error=new ErrorWithStatus(message);error.status=statusCode;return error}/**
53
+ */export function newError(message,statusCode=CODES.INTERNAL_SERVER_ERROR){const error=new ErrorWithStatus(message);error.status=statusCode;return error}/**
54
54
  * Throws an error with given message and HTTP status code.
55
- */function fail(message,statusCode=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR){throw newError(message,statusCode)}/**
55
+ */export function fail(message,statusCode=CODES.INTERNAL_SERVER_ERROR){throw newError(message,statusCode)}/**
56
56
  * Validates the `value` against the given "standard" validation `schema`.
57
57
  * Resolves to the correctly typed `value`, if it has passed the validation;
58
58
  * otherwise throws an error.
@@ -61,5 +61,5 @@ class ErrorWithStatus extends Error{status=_httpStatusCodes.StatusCodes.INTERNAL
61
61
  * @param [message] Optional error message, to prepend the validation error
62
62
  * message.
63
63
  * @param [statusCode=400] HTTP status code. Defaults to 400 (Bad Request).
64
- */async function assert(value,schema,message="",statusCode=_httpStatusCodes.StatusCodes.BAD_REQUEST){let result=schema["~standard"].validate(value);if(result instanceof Promise)result=await result;if(result.issues){let error=JSON.stringify(result.issues,null,2);if(message)error=`${message}\n\n${error}`;throw fail(error,statusCode)}return result.value}
64
+ */export async function assert(value,schema,message="",statusCode=CODES.BAD_REQUEST){let result=schema["~standard"].validate(value);if(result instanceof Promise)result=await result;if(result.issues){let error=JSON.stringify(result.issues,null,2);if(message)error=`${message}\n\n${error}`;throw fail(error,statusCode)}return result.value}
65
65
  //# sourceMappingURL=errors.js.map