@dr.pogodin/react-utils 1.47.0-alpha.5 → 1.47.0-alpha.8

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 (211) hide show
  1. package/build/development/client/getInj.js +11 -0
  2. package/build/development/client/getInj.js.map +1 -1
  3. package/build/development/client/index.js +1 -1
  4. package/build/development/client/index.js.map +1 -1
  5. package/build/development/index.js +1 -11
  6. package/build/development/index.js.map +1 -1
  7. package/build/development/server/index.js +3 -6
  8. package/build/development/server/index.js.map +1 -1
  9. package/build/development/server/renderer.js +20 -0
  10. package/build/development/server/renderer.js.map +1 -1
  11. package/build/development/server/server.js +6 -0
  12. package/build/development/server/server.js.map +1 -1
  13. package/build/development/server/utils/index.js +1 -1
  14. package/build/development/server/utils/index.js.map +1 -1
  15. package/build/development/shared/components/Button/index.js +1 -1
  16. package/build/development/shared/components/Button/index.js.map +1 -1
  17. package/build/development/shared/components/Checkbox/index.js +1 -1
  18. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  19. package/build/development/shared/components/Input/index.js +1 -1
  20. package/build/development/shared/components/Input/index.js.map +1 -1
  21. package/build/development/shared/components/Modal/index.js +1 -1
  22. package/build/development/shared/components/Modal/index.js.map +1 -1
  23. package/build/development/shared/components/PageLayout/index.js +1 -1
  24. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  25. package/build/development/shared/components/TextArea/index.js +1 -1
  26. package/build/development/shared/components/TextArea/index.js.map +1 -1
  27. package/build/development/shared/components/Throbber/index.js +1 -1
  28. package/build/development/shared/components/Throbber/index.js.map +1 -1
  29. package/build/development/shared/components/WithTooltip/index.js +1 -1
  30. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  31. package/build/development/shared/components/YouTubeVideo/index.js +1 -1
  32. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  33. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -0
  34. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  35. package/build/development/shared/components/selectors/CustomDropdown/index.js +5 -1
  36. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  37. package/build/development/shared/components/selectors/NativeDropdown/index.js +7 -1
  38. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  39. package/build/development/shared/components/selectors/Switch/index.js +3 -1
  40. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  41. package/build/development/shared/utils/jest/E2eSsrEnv.js +4 -0
  42. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  43. package/build/development/shared/utils/splitComponent.js +18 -0
  44. package/build/development/shared/utils/splitComponent.js.map +1 -1
  45. package/build/development/shared/utils/webpack.js +4 -0
  46. package/build/development/shared/utils/webpack.js.map +1 -1
  47. package/build/production/client/getInj.js +1 -1
  48. package/build/production/client/getInj.js.map +1 -1
  49. package/build/production/client/index.js +1 -1
  50. package/build/production/client/index.js.map +1 -1
  51. package/build/production/index.js +2 -6
  52. package/build/production/index.js.map +1 -1
  53. package/build/production/server/index.js +3 -3
  54. package/build/production/server/index.js.map +1 -1
  55. package/build/production/server/renderer.js +1 -1
  56. package/build/production/server/renderer.js.map +1 -1
  57. package/build/production/server/server.js +1 -1
  58. package/build/production/server/server.js.map +1 -1
  59. package/build/production/server/utils/index.js +1 -1
  60. package/build/production/server/utils/index.js.map +1 -1
  61. package/build/production/shared/components/Button/index.js +1 -1
  62. package/build/production/shared/components/Button/index.js.map +1 -1
  63. package/build/production/shared/components/Checkbox/index.js +1 -1
  64. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  65. package/build/production/shared/components/Input/index.js +1 -1
  66. package/build/production/shared/components/Input/index.js.map +1 -1
  67. package/build/production/shared/components/Modal/index.js +1 -1
  68. package/build/production/shared/components/Modal/index.js.map +1 -1
  69. package/build/production/shared/components/PageLayout/index.js +1 -1
  70. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  71. package/build/production/shared/components/TextArea/index.js +1 -1
  72. package/build/production/shared/components/TextArea/index.js.map +1 -1
  73. package/build/production/shared/components/Throbber/index.js +1 -1
  74. package/build/production/shared/components/Throbber/index.js.map +1 -1
  75. package/build/production/shared/components/WithTooltip/index.js +1 -1
  76. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  77. package/build/production/shared/components/YouTubeVideo/index.js +1 -1
  78. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  79. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  80. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  81. package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
  82. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  83. package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
  84. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  85. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  86. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  87. package/build/production/shared/utils/jest/E2eSsrEnv.js +1 -1
  88. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  89. package/build/production/shared/utils/splitComponent.js +1 -1
  90. package/build/production/shared/utils/splitComponent.js.map +1 -1
  91. package/build/production/shared/utils/webpack.js +1 -1
  92. package/build/production/shared/utils/webpack.js.map +1 -1
  93. package/build/types-code/client/index.d.ts +1 -1
  94. package/build/types-code/index.d.ts +0 -5
  95. package/build/types-code/server/index.d.ts +4 -9
  96. package/build/types-code/server/utils/index.d.ts +1 -1
  97. package/build/web/client/getInj.js +7 -0
  98. package/build/web/client/getInj.js.map +1 -1
  99. package/build/web/client/index.js +1 -1
  100. package/build/web/client/index.js.map +1 -1
  101. package/build/web/index.js +1 -11
  102. package/build/web/index.js.map +1 -1
  103. package/build/web/server/index.js +3 -6
  104. package/build/web/server/index.js.map +1 -1
  105. package/build/web/server/renderer.js +10 -0
  106. package/build/web/server/renderer.js.map +1 -1
  107. package/build/web/server/server.js +3 -0
  108. package/build/web/server/server.js.map +1 -1
  109. package/build/web/server/utils/index.js +1 -1
  110. package/build/web/server/utils/index.js.map +1 -1
  111. package/build/web/shared/components/Button/index.js +1 -1
  112. package/build/web/shared/components/Button/index.js.map +1 -1
  113. package/build/web/shared/components/Checkbox/index.js +1 -1
  114. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  115. package/build/web/shared/components/Input/index.js +1 -1
  116. package/build/web/shared/components/Input/index.js.map +1 -1
  117. package/build/web/shared/components/Modal/index.js +1 -1
  118. package/build/web/shared/components/Modal/index.js.map +1 -1
  119. package/build/web/shared/components/PageLayout/index.js +1 -1
  120. package/build/web/shared/components/PageLayout/index.js.map +1 -1
  121. package/build/web/shared/components/TextArea/index.js +1 -1
  122. package/build/web/shared/components/TextArea/index.js.map +1 -1
  123. package/build/web/shared/components/Throbber/index.js +1 -1
  124. package/build/web/shared/components/Throbber/index.js.map +1 -1
  125. package/build/web/shared/components/WithTooltip/index.js +1 -1
  126. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  127. package/build/web/shared/components/YouTubeVideo/index.js +1 -1
  128. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  129. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +3 -0
  130. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  131. package/build/web/shared/components/selectors/CustomDropdown/index.js +3 -1
  132. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  133. package/build/web/shared/components/selectors/NativeDropdown/index.js +4 -1
  134. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  135. package/build/web/shared/components/selectors/Switch/index.js +2 -1
  136. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  137. package/build/web/shared/utils/jest/E2eSsrEnv.js +2 -0
  138. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  139. package/build/web/shared/utils/splitComponent.js +9 -0
  140. package/build/web/shared/utils/splitComponent.js.map +1 -1
  141. package/build/web/shared/utils/webpack.js +2 -0
  142. package/build/web/shared/utils/webpack.js.map +1 -1
  143. package/config/babel/node-ssr.js +7 -1
  144. package/config/babel/webpack.js +3 -1
  145. package/config/webpack/app-base.js +4 -7
  146. package/config/webpack/app-development.js +2 -3
  147. package/package.json +20 -9
  148. package/src/client/getInj.ts +0 -71
  149. package/src/client/index.tsx +0 -45
  150. package/src/client/init.ts +0 -52
  151. package/src/index.ts +0 -75
  152. package/src/server/Cache.ts +0 -61
  153. package/src/server/index.ts +0 -243
  154. package/src/server/renderer.tsx +0 -635
  155. package/src/server/server.ts +0 -330
  156. package/src/server/utils/errors.ts +0 -122
  157. package/src/server/utils/index.ts +0 -3
  158. package/src/shared/components/Button/index.tsx +0 -130
  159. package/src/shared/components/Button/style.scss +0 -54
  160. package/src/shared/components/Checkbox/index.tsx +0 -53
  161. package/src/shared/components/Checkbox/theme.scss +0 -63
  162. package/src/shared/components/GenericLink/index.tsx +0 -141
  163. package/src/shared/components/GenericLink/style.scss +0 -3
  164. package/src/shared/components/Input/index.tsx +0 -96
  165. package/src/shared/components/Input/theme.scss +0 -52
  166. package/src/shared/components/Link.tsx +0 -25
  167. package/src/shared/components/Modal/base-theme.scss +0 -38
  168. package/src/shared/components/Modal/index.tsx +0 -177
  169. package/src/shared/components/Modal/styles.scss +0 -3
  170. package/src/shared/components/NavLink.tsx +0 -18
  171. package/src/shared/components/PageLayout/base-theme.scss +0 -30
  172. package/src/shared/components/PageLayout/index.tsx +0 -51
  173. package/src/shared/components/TextArea/index.tsx +0 -139
  174. package/src/shared/components/TextArea/style.scss +0 -68
  175. package/src/shared/components/Throbber/index.tsx +0 -28
  176. package/src/shared/components/Throbber/theme.scss +0 -26
  177. package/src/shared/components/WithTooltip/Tooltip.tsx +0 -274
  178. package/src/shared/components/WithTooltip/default-theme.scss +0 -36
  179. package/src/shared/components/WithTooltip/index.tsx +0 -186
  180. package/src/shared/components/YouTubeVideo/base.scss +0 -15
  181. package/src/shared/components/YouTubeVideo/index.tsx +0 -73
  182. package/src/shared/components/YouTubeVideo/throbber.scss +0 -11
  183. package/src/shared/components/index.ts +0 -20
  184. package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
  185. package/src/shared/components/selectors/CustomDropdown/Options/style.scss +0 -6
  186. package/src/shared/components/selectors/CustomDropdown/index.tsx +0 -146
  187. package/src/shared/components/selectors/CustomDropdown/theme.scss +0 -118
  188. package/src/shared/components/selectors/NativeDropdown/index.tsx +0 -90
  189. package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -81
  190. package/src/shared/components/selectors/Switch/index.tsx +0 -74
  191. package/src/shared/components/selectors/Switch/theme.scss +0 -39
  192. package/src/shared/components/selectors/common.ts +0 -57
  193. package/src/shared/components/selectors/index.ts +0 -8
  194. package/src/shared/utils/config.ts +0 -59
  195. package/src/shared/utils/globalState.ts +0 -44
  196. package/src/shared/utils/index.ts +0 -45
  197. package/src/shared/utils/isomorphy/buildInfo.ts +0 -50
  198. package/src/shared/utils/isomorphy/environment-check.ts +0 -18
  199. package/src/shared/utils/isomorphy/index.ts +0 -36
  200. package/src/shared/utils/jest/E2eSsrEnv.ts +0 -304
  201. package/src/shared/utils/jest/global.ts +0 -17
  202. package/src/shared/utils/jest/index.ts +0 -215
  203. package/src/shared/utils/splitComponent.tsx +0 -284
  204. package/src/shared/utils/time.ts +0 -101
  205. package/src/shared/utils/webpack.ts +0 -80
  206. package/src/styles/_global/reset.css +0 -52
  207. package/src/styles/_mixins/fonts.scss +0 -40
  208. package/src/styles/_mixins/media.scss +0 -150
  209. package/src/styles/_mixins/typography.scss +0 -83
  210. package/src/styles/global.scss +0 -11
  211. package/src/styles/mixins.scss +0 -6
@@ -3,9 +3,10 @@ import http from 'node:http';
3
3
  import 'raf/polyfill.js';
4
4
  import type { Configuration } from 'webpack';
5
5
  import { type OptionsT as ServerOptionsT, type ServerT, getDefaultCspSettings } from './server';
6
- import { errors } from './utils';
6
+ import { SCRIPT_LOCATIONS } from './renderer';
7
+ export * from './utils';
7
8
  export type { BeforeRenderResT, BeforeRenderT, ConfigT, ServerSsrContext, } from './renderer';
8
- export { errors, getDefaultCspSettings, type ServerT };
9
+ export { getDefaultCspSettings, SCRIPT_LOCATIONS, type ServerT, };
9
10
  type OptionsT = ServerOptionsT & {
10
11
  https?: {
11
12
  cert: string;
@@ -131,13 +132,7 @@ type OptionsT = ServerOptionsT & {
131
132
  * defaults to 1 second.
132
133
  * @return Resolves to an object with created Express and HTTP servers.
133
134
  */
134
- declare function launchServer(webpackConfig: Configuration, options?: OptionsT): Promise<{
135
+ export declare function launchServer(webpackConfig: Configuration, options?: OptionsT): Promise<{
135
136
  expressServer: ServerT;
136
137
  httpServer: http.Server;
137
138
  }>;
138
- declare namespace launchServer {
139
- var SCRIPT_LOCATIONS: typeof import("./renderer").SCRIPT_LOCATIONS;
140
- var getDefaultCspSettings: typeof import("./server").getDefaultCspSettings;
141
- var errors: typeof import("./utils/errors");
142
- }
143
- export default launchServer;
@@ -1 +1 @@
1
- export * as errors from './errors';
1
+ export * from './errors';
@@ -1,3 +1,10 @@
1
+ import "core-js/modules/es.array-buffer.detached.js";
2
+ import "core-js/modules/es.array-buffer.transfer.js";
3
+ import "core-js/modules/es.array-buffer.transfer-to-fixed-length.js";
4
+ import "core-js/modules/es.typed-array.to-reversed.js";
5
+ import "core-js/modules/es.typed-array.to-sorted.js";
6
+ import "core-js/modules/es.typed-array.with.js";
7
+ import "core-js/modules/web.dom-exception.stack.js";
1
8
  // Encapsulates retrieval of server-side data injection into HTML template.
2
9
 
3
10
  /* global document */
@@ -1 +1 @@
1
- {"version":3,"file":"getInj.js","names":["getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","window","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n // TODO: Our current handling of this encryption / decryption follows\n // a legacy approach, and can be enhanced by using Crypto features.\n // Though, this is not strictly intended to be secure (it is more\n // to obfurscate injected data, rather than really keeping them\n // secure), thus it is fine like this for now.\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n return {};\n })();\n\n return inj;\n}\n"],"mappings":"AAAA;;AAEA;;AAIA,SAASA,YAAY;AAErB,IAAIC,GAAqC;AAEzC,eAAe,SAASC,MAAMA,CAA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MAAM,CAACP,MAAM,CAAC,GAAG,CAAS;;MAEvD;MACA;MACAzB,GAAG,GAAG8B,GAAG;MAET,OAAOA,GAAG;IACZ,CAAC,MAAM,IAAI,OAAOV,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACa,qBAAqB,EAAE;MACxE,MAAMH,GAAG,GAAGV,MAAM,CAACa,qBAAqB;MACxC,OAAOb,MAAM,CAACa,qBAAqB;MACnC,OAAOH,GAAG;IACZ;;IAEA;IACA;IACA;IACA,OAAO,CAAC,CAAC;EACX,CAAC,EAAE,CAAC;EAEJ,OAAO9B,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"getInj.js","names":["getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","window","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n // TODO: Our current handling of this encryption / decryption follows\n // a legacy approach, and can be enhanced by using Crypto features.\n // Though, this is not strictly intended to be secure (it is more\n // to obfurscate injected data, rather than really keeping them\n // secure), thus it is fine like this for now.\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n return {};\n })();\n\n return inj;\n}\n"],"mappings":";;;;;;;AAAA;;AAEA;;AAIA,SAASA,YAAY;AAErB,IAAIC,GAAqC;AAEzC,eAAe,SAASC,MAAMA,CAAA,EAAyB;EACrDD,GAAG,KAAK,CAAC,YAAY;IACnB,MAAME,WAAmC,GAAG,OAAOC,QAAQ,KAAK,WAAW,GACvE,IAAI,GAAGA,QAAQ,CAACC,aAAa,CAAC,2BAA2B,CAAC;IAE9D,IAAIF,WAAW,EAAE;MACfA,WAAW,CAACG,MAAM,CAAC,CAAC;;MAEpB;MACA;MACA,MAAMC,IAAI,GAAGC,IAAI,CAACL,WAAW,CAACM,OAAO,CAAC;;MAEtC;MACA;MACA;MACA;MACA;MACA,MAAM;QAAEC;MAAI,CAAC,GAAGV,YAAY,CAAC,CAAC;MAE9B,MAAMW,IAAI,GAAIC,CAAS,IAAKA,CAAC,CAACC,UAAU,CAAC,CAAC,CAAC;MAC3C,MAAMC,UAAU,GAAGC,UAAU,CAACC,IAAI,CAACT,IAAI,CAACU,KAAK,CAAC,EAAE,CAAC,EAAEN,IAAI,CAAC;MACxD,MAAMO,QAAQ,GAAGH,UAAU,CAACC,IAAI,CAACT,IAAI,CAACU,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAEN,IAAI,CAAC;MACzD,MAAMQ,SAAS,GAAGJ,UAAU,CAACC,IAAI,CAACR,IAAI,CAACE,GAAG,CAAC,EAAEC,IAAI,CAAC;MAElD,MAAMS,IAAI,GAAG,MAAMC,MAAM,CAACC,MAAM,CAACC,MAAM,CAACC,SAAS,CAC/C,KAAK,EACLL,SAAS,EACT;QAAEM,IAAI,EAAE;MAAU,CAAC,EACnB,KAAK,EACL,CAAC,SAAS,CACZ,CAAC;MAED,MAAMC,MAAM,GAAG,MAAML,MAAM,CAACC,MAAM,CAACC,MAAM,CAACI,OAAO,CAAC;QAChDC,EAAE,EAAEV,QAAQ;QACZO,IAAI,EAAE;MACR,CAAC,EAAEL,IAAI,EAAEN,UAAU,CAAC;MAEpB,MAAMe,OAAO,GAAG,IAAIC,WAAW,CAAC,CAAC;;MAEjC;MACA,MAAMC,GAAG,GAAGC,IAAI,CAAC,IAAIH,OAAO,CAACI,MAAM,CAACP,MAAM,CAAC,GAAG,CAAS;;MAEvD;MACA;MACAzB,GAAG,GAAG8B,GAAG;MAET,OAAOA,GAAG;IACZ,CAAC,MAAM,IAAI,OAAOV,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACa,qBAAqB,EAAE;MACxE,MAAMH,GAAG,GAAGV,MAAM,CAACa,qBAAqB;MACxC,OAAOb,MAAM,CAACa,qBAAqB;MACnC,OAAOH,GAAG;IACZ;;IAEA;IACA;IACA;IACA,OAAO,CAAC,CAAC;EACX,CAAC,EAAE,CAAC;EAEJ,OAAO9B,GAAG;AACZ","ignoreList":[]}
@@ -12,7 +12,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
12
12
  * @param Application Root application component
13
13
  * @param [options={}] Optional. Additional settings.
14
14
  */
15
- export default async function Launch(Application, options = {}) {
15
+ export async function launchClient(Application, options = {}) {
16
16
  const inj = await getInj();
17
17
  const container = document.getElementById('react-view');
18
18
  if (!container) throw Error('Failed to find container for React app');
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createRoot","hydrateRoot","HelmetProvider","BrowserRouter","GlobalStateProvider","getInj","jsx","_jsx","Launch","Application","options","inj","container","document","getElementById","Error","scene","initialState","ISTATE","children","dontHydrate","root","render"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default async function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): Promise<void> {\n const inj = await getInj();\n\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={inj.ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"AAAA;AACA;;AAGA,SAASA,UAAU,EAAEC,WAAW,QAAQ,kBAAkB;AAC1D,SAASC,cAAc,QAAQ,0BAA0B;AACzD,SAASC,aAAa,QAAQ,cAAc;AAE5C,SAASC,mBAAmB,QAAQ,gCAAgC;AAEpE,OAAOC,MAAM;AAAiB,SAAAC,GAAA,IAAAC,IAAA;AAO9B;AACA;AACA;AACA;AACA;AACA,eAAe,eAAeC,MAAMA,CAClCC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EACP;EACf,MAAMC,GAAG,GAAG,MAAMN,MAAM,CAAC,CAAC;EAE1B,MAAMO,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACTT,IAAA,CAACH,mBAAmB;IAACa,YAAY,EAAEN,GAAG,CAACO,MAAM,IAAIR,OAAO,CAACO,YAAa;IAAAE,QAAA,eACpEZ,IAAA,CAACJ,aAAa;MAAAgB,QAAA,eACZZ,IAAA,CAACL,cAAc;QAAAiB,QAAA,eACbZ,IAAA,CAACE,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACU,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAGrB,UAAU,CAACY,SAAS,CAAC;IAClCS,IAAI,CAACC,MAAM,CAACN,KAAK,CAAC;EACpB,CAAC,MAAMf,WAAW,CAACW,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["createRoot","hydrateRoot","HelmetProvider","BrowserRouter","GlobalStateProvider","getInj","jsx","_jsx","launchClient","Application","options","inj","container","document","getElementById","Error","scene","initialState","ISTATE","children","dontHydrate","root","render"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport async function launchClient(\n Application: ComponentType,\n options: OptionsT = {},\n): Promise<void> {\n const inj = await getInj();\n\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={inj.ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"AAAA;AACA;;AAGA,SAASA,UAAU,EAAEC,WAAW,QAAQ,kBAAkB;AAC1D,SAASC,cAAc,QAAQ,0BAA0B;AACzD,SAASC,aAAa,QAAQ,cAAc;AAE5C,SAASC,mBAAmB,QAAQ,gCAAgC;AAEpE,OAAOC,MAAM;AAAiB,SAAAC,GAAA,IAAAC,IAAA;AAO9B;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,YAAYA,CAChCC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EACP;EACf,MAAMC,GAAG,GAAG,MAAMN,MAAM,CAAC,CAAC;EAE1B,MAAMO,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACTT,IAAA,CAACH,mBAAmB;IAACa,YAAY,EAAEN,GAAG,CAACO,MAAM,IAAIR,OAAO,CAACO,YAAa;IAAAE,QAAA,eACpEZ,IAAA,CAACJ,aAAa;MAAAgB,QAAA,eACZZ,IAAA,CAACL,cAAc;QAAAiB,QAAA,eACbZ,IAAA,CAACE,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACU,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAGrB,UAAU,CAACY,SAAS,CAAC;IAClCS,IAAI,CAACC,MAAM,CAACN,KAAK,CAAC;EACpB,CAAC,MAAMf,WAAW,CAACW,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
@@ -1,6 +1,5 @@
1
1
  import "./styles/global.scss";
2
- import clientModule from "./client";
3
- import { webpack } from "./shared/utils";
2
+
4
3
  // It is a safeguard against multiple instances / versions of the library
5
4
  // being loaded into environment by mistake (e.g. because of different
6
5
  // packages pinning down different exact versions of the lib, thus preventing
@@ -8,16 +7,7 @@ import { webpack } from "./shared/utils";
8
7
  if (global.REACT_UTILS_LIBRARY_LOADED) {
9
8
  throw Error('React utils library is already loaded');
10
9
  } else global.REACT_UTILS_LIBRARY_LOADED = true;
11
-
12
- // TODO: This is a rapid workaround to get rid of __dirname. I guess, later
13
- // we'll re-implement requireWeak() to accept import.meta.url directly, and
14
- // this workaround won't be needed.
15
- // eslint-disable-next-line @typescript-eslint/prefer-destructuring
16
- const dirname = import.meta.dirname;
17
- const server = webpack.requireWeak('./server', dirname);
18
- const client = server ? undefined : clientModule;
19
10
  export { getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType } from '@dr.pogodin/react-global-state';
20
11
  export * from "./shared/components";
21
12
  export { assertEmptyObject, Barrier, Cached, Emitter, getConfig, isomorphy, getSsrContext, Semaphore, splitComponent, themed, ThemeProvider, time, webpack, withRetries } from "./shared/utils";
22
- export { client, server };
23
13
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["clientModule","webpack","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","import","meta","server","requireWeak","client","undefined","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","Barrier","Cached","Emitter","getConfig","isomorphy","getSsrContext","Semaphore","splitComponent","themed","ThemeProvider","time","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport clientModule from './client';\nimport { webpack } from './shared/utils';\n\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\n// eslint-disable-next-line @typescript-eslint/prefer-destructuring\nconst dirname = import.meta.dirname;\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server ? undefined : clientModule;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n Barrier,\n Cached,\n Emitter,\n getConfig,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":"AAAA;AAEA,OAAOA,YAAY;AACnB,SAASC,OAAO;AAIhB;AACA;AACA;AACA;AACA,IAAIC,MAAM,CAACC,0BAA0B,EAAE;EACrC,MAAMC,KAAK,CAAC,uCAAuC,CAAC;AACtD,CAAC,MAAMF,MAAM,CAACC,0BAA0B,GAAG,IAAI;;AAE/C;AACA;AACA;AACA;AACA,MAAME,OAAO,GAAGC,MAAM,CAACC,IAAI,CAACF,OAAO;AAEnC,MAAMG,MAAM,GAAGP,OAAO,CAACQ,WAAW,CAAwB,UAAU,EAAEJ,OAAO,CAAC;AAE9E,MAAMK,MAAM,GAAGF,MAAM,GAAGG,SAAS,GAAGX,YAAY;AAEhD,SAUEY,cAAc,EACdC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,QACd,gCAAgC;AAEvC;AAUA,SACEC,iBAAiB,EACjBC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,aAAa,EAGbC,SAAS,EACTC,cAAc,EAEdC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJ7B,OAAO,EACP8B,WAAW;AAGb,SAASrB,MAAM,EAAEF,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["global","REACT_UTILS_LIBRARY_LOADED","Error","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","Barrier","Cached","Emitter","getConfig","isomorphy","getSsrContext","Semaphore","splitComponent","themed","ThemeProvider","time","webpack","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n Barrier,\n Cached,\n Emitter,\n getConfig,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n"],"mappings":"AAAA;;AAEA;AACA;AACA;AACA;AACA,IAAIA,MAAM,CAACC,0BAA0B,EAAE;EACrC,MAAMC,KAAK,CAAC,uCAAuC,CAAC;AACtD,CAAC,MAAMF,MAAM,CAACC,0BAA0B,GAAG,IAAI;AAE/C,SAUEE,cAAc,EACdC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,QACd,gCAAgC;AAEvC;AAUA,SACEC,iBAAiB,EACjBC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,aAAa,EAGbC,SAAS,EACTC,cAAc,EAEdC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJC,OAAO,EACPC,WAAW","ignoreList":[]}
@@ -10,8 +10,8 @@ import { cloneDeep, defaults } from 'lodash-es';
10
10
  import 'raf/polyfill.js';
11
11
  import serverFactory, { getDefaultCspSettings } from "./server";
12
12
  import { SCRIPT_LOCATIONS, newDefaultLogger } from "./renderer";
13
- import { errors } from "./utils";
14
- export { errors, getDefaultCspSettings };
13
+ export * from "./utils";
14
+ export { getDefaultCspSettings, SCRIPT_LOCATIONS };
15
15
 
16
16
  /**
17
17
  * Normalizes a port into a number, string, or false.
@@ -142,7 +142,7 @@ function normalizePort(value) {
142
142
  * defaults to 1 second.
143
143
  * @return Resolves to an object with created Express and HTTP servers.
144
144
  */
145
- export default async function launchServer(webpackConfig, options = {}) {
145
+ export async function launchServer(webpackConfig, options = {}) {
146
146
  /* Options normalization. */
147
147
  const ops = cloneDeep(options);
148
148
 
@@ -199,7 +199,4 @@ export default async function launchServer(webpackConfig, options = {}) {
199
199
  httpServer
200
200
  };
201
201
  }
202
- launchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;
203
- launchServer.getDefaultCspSettings = getDefaultCspSettings;
204
- launchServer.errors = errors;
205
202
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["http","https","cloneDeep","defaults","serverFactory","getDefaultCspSettings","SCRIPT_LOCATIONS","newDefaultLogger","errors","normalizePort","value","port","parseInt","Number","isFinite","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport { errors, getDefaultCspSettings, type ServerT };\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [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 {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [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 * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport default async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\nlaunchServer.getDefaultCspSettings = getDefaultCspSettings;\nlaunchServer.errors = errors;\n"],"mappings":"AAAA;AACA,OAAO,gCAAgC;AAEvC,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAE9B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,WAAW;;AAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAIxB,OAAOC,aAAa,IAGlBC,qBAAqB;AAGvB,SAASC,gBAAgB,EAAEC,gBAAgB;AAE3C,SAASC,MAAM;AASf,SAASA,MAAM,EAAEH,qBAAqB;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA,SAASI,aAAaA,CAACC,KAAsB,EAAE;EAC7C,MAAMC,IAAI,GAAG,OAAOD,KAAK,KAAK,QAAQ,GAAGE,QAAQ,CAACF,KAAK,CAAC,GAAGA,KAAK;EAChE,IAAIG,MAAM,CAACC,QAAQ,CAACH,IAAI,CAAC,EAAE,OAAOA,IAAI,CAAC,CAAC;EACxC,OAAOD,KAAK,CAAC,CAAC;AAChB;AAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,eAAeK,YAAYA,CACxCC,aAA4B,EAC5BC,OAAiB,GAAG,CAAC,CAAC,EAIrB;EACD;EACA,MAAMC,GAAG,GAAGhB,SAAS,CAACe,OAAO,CAAC;;EAE9B;EACAC,GAAG,CAACP,IAAI,GAAGF,aAAa,CAACS,GAAG,CAACP,IAAI,IAAIQ,OAAO,CAACC,GAAG,CAACC,IAAI,IAAI,IAAI,CAAC;EAC9DlB,QAAQ,CAACe,GAAG,EAAE;IAAEI,aAAa,EAAE;EAAK,CAAC,CAAC;;EAEtC;EACA;EACAJ,GAAG,CAACK,MAAM,KAAKhB,gBAAgB,CAAC;IAC9BiB,eAAe,EAAEN,GAAG,CAACO;EACvB,CAAC,CAAC;;EAEF;EACA,MAAMC,aAAa,GAAG,MAAMtB,aAAa,CAACY,aAAa,EAAEE,GAAG,CAAC;EAE7D,IAAIS,UAAuB;EAC3B,IAAIT,GAAG,CAACjB,KAAK,EAAE;IACb0B,UAAU,GAAG1B,KAAK,CAAC2B,YAAY,CAAC;MAC9BC,IAAI,EAAEX,GAAG,CAACjB,KAAK,CAAC4B,IAAI;MACpBC,GAAG,EAAEZ,GAAG,CAACjB,KAAK,CAAC6B;IACjB,CAAC,EAAEJ,a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B,GAAGA,gBAAgB;AAChDS,YAAY,CAACV,qBAAqB,GAAGA,qBAAqB;AAC1DU,YAAY,CAACP,MAAM,GAAGA,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["http","https","cloneDeep","defaults","serverFactory","getDefaultCspSettings","SCRIPT_LOCATIONS","newDefaultLogger","normalizePort","value","port","parseInt","Number","isFinite","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n getDefaultCspSettings,\n SCRIPT_LOCATIONS,\n type ServerT,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [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 {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [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 * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,OAAO,gCAAgC;AAEvC,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAE9B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,WAAW;;AAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAIxB,OAAOC,aAAa,IAGlBC,qBAAqB;AAGvB,SAASC,gBAAgB,EAAEC,gBAAgB;AAE3C;AASA,SACEF,qBAAqB,EACrBC,gBAAgB;;AAIlB;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,aAAaA,CAACC,KAAsB,EAAE;EAC7C,MAAMC,IAAI,GAAG,OAAOD,KAAK,KAAK,QAAQ,GAAGE,QAAQ,CAACF,KAAK,CAAC,GAAGA,KAAK;EAChE,IAAIG,MAAM,CAACC,QAAQ,CAACH,IAAI,CAAC,EAAE,OAAOA,IAAI,CAAC,CAAC;EACxC,OAAOD,KAAK,CAAC,CAAC;AAChB;AAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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,OAAO,KAAK,QAAQ,EAAE,MAAMD,KAAK;IACrE,MAAME,IAAI,GAAG,OAAOhB,GAAG,CAACP,IAAI,KAAK,QAAQ,GAAG,QAAQO,GAAG,CAACP,IAAI,EAAE,GAAG,QAAQO,GAAG,CAACP,IAAI,EAAE;;IAEnF;IACA,QAASqB,KAAK,CAAuBG,IAAI;MACvC,KAAK,QAAQ;QACXjB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,+BAA+B,CAAC;QACzD,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAK,YAAY;QACflB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC;QAC9C,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAKC,SAAS;MACd;QACE,MAAML,KAAK;IACf;EACF,CAAC,CAAC;;EAEF;EACAL,UAAU,CAACI,EAAE,CAAC,WAAW,EAAE,MAAM;IAC/B,MAAMO,IAAI,GAAGX,UAAU,CAACY,OAAO,CAAC,CAAE;IAClC,MAAML,IAAI,GAAG,OAAOI,IAAI,KAAK,QAAQ,GAAG,QAAQA,IAAI,EAAE,GAAG,QAAQA,IAAI,CAAC3B,IAAI,EAAE;IAC5EO,GAAG,CAACK,MAAM,CAAEiB,IAAI,CAAC,uBAAuBN,IAAI,OAC1Cf,OAAO,CAACC,GAAG,CAACqB,QAAQ,OAAO,CAAC;EAChC,CAAC,CAAC;EAEFd,UAAU,CAACe,MAAM,CAACxB,GAAG,CAACP,IAAI,CAAC;EAE3B,OAAO;IACLe,aAAa;IACbC;EACF,CAAC;AACH","ignoreList":[]}
@@ -1,3 +1,13 @@
1
+ import "core-js/modules/es.iterator.constructor.js";
2
+ import "core-js/modules/es.iterator.for-each.js";
3
+ import "core-js/modules/es.iterator.map.js";
4
+ import "core-js/modules/es.set.difference.v2.js";
5
+ import "core-js/modules/es.set.intersection.v2.js";
6
+ import "core-js/modules/es.set.is-disjoint-from.v2.js";
7
+ import "core-js/modules/es.set.is-subset-of.v2.js";
8
+ import "core-js/modules/es.set.is-superset-of.v2.js";
9
+ import "core-js/modules/es.set.symmetric-difference.v2.js";
10
+ import "core-js/modules/es.set.union.v2.js";
1
11
  /**
2
12
  * ExpressJS middleware for server-side rendering of a ReactJS app.
3
13
  */
@@ -1 +1 @@
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":"AAAA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,aAAa;AACpC,SAAwBC,cAAc,EAAEC,WAAW,QAAQ,aAAa;AACxE,OAAOC,EAAE,MAAM,SAAS;AACxB,OAAOC,IAAI,MAAM,WAAW;AAC5B,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,cAAc,EAAEC,gBAAgB,QAAQ,WAAW;AAK5D,OAAOC,OAAO,MAAM,SAAS;AAE7B,SAASC,mBAAmB,EAAEC,UAAU,QAAQ,gCAAgC;AAChF,SAASC,KAAK,QAAQ,sBAAsB;AAE5C,SACEC,SAAS,EACTC,QAAQ,EACRC,GAAG,EACHC,SAAS,QACJ,WAAW;AAElB,OAAOC,MAAM,MAAM,QAAQ;AAE3B,SAASC,qBAAqB,QAAQ,kBAAkB;AACxD,SAAiCC,cAAc,QAAQ,0BAA0B;AACjF,S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gBAAgB,CAACkC,SAAS,CAAC;AAC9D,mCAAmC+E,aAAa;AAChD,cAAcqD,iBAAiB;AAC/B,cAAcE,oBAAoB,CAACxK,gBAAgB,CAACmC,OAAO,CAAC;AAC5D;AACA,gBAAgB;MAEV,MAAMhC,MAAM,GAAG+G,UAAU,CAAC/G,MAAM,IAAI,GAAG;MACvC,IAAIA,MAAM,KAAK,GAAG,EAAEc,GAAG,CAACd,MAAM,CAACA,MAAM,CAAC;MAEtC,IAAIgF,QAAQ,IAAIhF,MAAM,GAAG,GAAG,EAAE;QAC5B;QACA;QACA,MAAM,IAAI6D,OAAO,CAAO,CAACwB,IAAI,EAAEC,MAAM,KAAK;UACxC9G,cAAc,CAACgH,IAAI,EAAE,CAACD,KAAK,EAAEL,MAAM,KAAK;YACtC,IAAIK,KAAK,EAAED,MAAM,CAACC,KAAK,CAAC,CAAC,KACpB;cACH,MAAMoF,CAAC,GAAGzF,MAAoC;cAC9CyF,CAAC,CAAC9E,KAAK,GAAI3F,GAAG,CAEX2F,KAAK;cACRpB,KAAK,CAAEwF,GAAG,CAAC;gBAAE/E,MAAM,EAAEyF,CAAC;gBAAE3K;cAAO,CAAC,EAAEgF,QAAQ,CAAChE,GAAG,EAAEkE,MAAM,CAAC5B,MAAM,CAAC;cAC9D+B,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdX,IAAI,CAACW,KAAK,CAAC;IACb;EACF,CAAC;AACH","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":";;;;;;;;;;AAAA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,aAAa;AACpC,SAAwBC,cAAc,EAAEC,WAAW,QAAQ,aAAa;AACxE,OAAOC,EAAE,MAAM,SAAS;AACxB,OAAOC,IAAI,MAAM,WAAW;AAC5B,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,cAAc,EAAEC,gBAAgB,QAAQ,WAAW;AAK5D,OAAOC,OAAO,MAAM,SAAS;AAE7B,SAASC,mBAAmB,EAAEC,UAAU,QAAQ,gCAAgC;AAChF,SAASC,KAAK,QAAQ,sBAAsB;AAE5C,SACEC,SAAS,EACTC,QAAQ,EACRC,GAAG,EACHC,SAAS,QACJ,WAAW;AAElB,OAAOC,MAAM,MAAM,QAAQ;AAE3B,SAASC,qBAAqB,QAAQ,kBAAkB;AACxD,SAAiCC,cAAc,QAAQ,0BAA0B;AACjF,SAASC,YAAY,QAAQ,cAAc;AAC3C,OAAOC,WAAW,MAAM,sBAAsB;AAC9C,SAA0BC,YAAY;AAItC,OAAOC,KAAK;;AAEZ;AACA;AAAA,SAAAC,GAAA,IAAAC,IAAA;AACA,MAAM;EAAEC,MAAM;EAAE,GAAGC;AAAgB,CAAC,GAAGV,MAAM;;AAE7C;AACA;AACA;AACA;;AAMA;;AAMA;;AASA,WAAYW,gBAAgB,0BAAhBA,gBAAgB;EAAhBA,gBAAgB;EAAhBA,gBAAgB;EAAhBA,gBAAgB;EAAA,OAAhBA,gBAAgB;AAAA;AAM5B,OAAO,MAAMC,gBAAgB,SACnBlB,UAAU,CACa;EAG/BmB,MAAM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cAAc,CAACgH,IAAI,EAAE,CAACD,KAAK,EAAEL,MAAM,KAAK;YACtC,IAAIK,KAAK,EAAED,MAAM,CAACC,KAAK,CAAC,CAAC,KACpB;cACH,MAAMoF,CAAC,GAAGzF,MAAoC;cAC9CyF,CAAC,CAAC9E,KAAK,GAAI3F,GAAG,CAEX2F,KAAK;cACRpB,KAAK,CAAEwF,GAAG,CAAC;gBAAE/E,MAAM,EAAEyF,CAAC;gBAAE3K;cAAO,CAAC,EAAEgF,QAAQ,CAAChE,GAAG,EAAEkE,MAAM,CAAC5B,MAAM,CAAC;cAC9D+B,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdX,IAAI,CAACW,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
@@ -1,3 +1,6 @@
1
+ import "core-js/modules/es.array.push.js";
2
+ import "core-js/modules/es.iterator.constructor.js";
3
+ import "core-js/modules/es.iterator.filter.js";
1
4
  /**
2
5
  * Creation of standard ExpressJS server for ReactJS apps.
3
6
  */
@@ -1 +1 @@
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":"AAAA;AACA;AACA;;AAEA,SAASA,GAAG,QAAQ,WAAW;AAC/B,SAASC,aAAa,QAAQ,UAAU;AAExC,SAASC,SAAS,EAAEC,SAAS,EAAEC,IAAI,QAAQ,WAAW;AAEtD,OAAOC,WAAW,MAAM,aAAa;AACrC,OAAOC,YAAY,MAAM,eAAe;AACxC,OAAOC,IAAI,MAAM,mBAAmB;AAEpC,OAAOC,OAAO,MAKP,SAAS;AAEhB,OAAOC,OAAO,MAAM,eAAe;AACnC,OAAOC,MAAM,MAA8B,QAAQ;AACnD,OAAOC,gBAAgB,MAAM,QAAQ;AACrC,OAAOC,SAAS,MAAM,YAAY;AAClC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAIjC,OAAOC,eAAe;AAKtB,SACEC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,QAAQ;;AAKV;;AAMA;AACA;AACA;AACA;AACA,MAAMC,kBAAkB,GAAG;EACzBC,UAAU,EAAElB,SAAS,CACnBO,MAAM,CAACY,qBAAqB,CAACC,oBAAoB,CAAC,CAAC;EAEnD;EACA;EACA;EACA;EACCC,KAAK,IAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,IAAKA,IAAI,KAAK,QAAQ,CAC3E;AACF,CAAC;AACD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E,MAAM;AACf","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":";;;AAAA;AACA;AACA;;AAEA,SAASA,GAAG,QAAQ,WAAW;AAC/B,SAASC,aAAa,QAAQ,UAAU;AAExC,SAASC,SAAS,EAAEC,SAAS,EAAEC,IAAI,QAAQ,WAAW;AAEtD,OAAOC,WAAW,MAAM,aAAa;AACrC,OAAOC,YAAY,MAAM,eAAe;AACxC,OAAOC,IAAI,MAAM,mBAAmB;AAEpC,OAAOC,OAAO,MAKP,SAAS;AAEhB,OAAOC,OAAO,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AGF,MAAM,IAAKlF,KAAK,CAACmF,qBAAgC;;MAEpE;MACApE,OAAO,CAACO,MAAM,CAAE+D,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAIrF,eAAe,CAACgF,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAIjB,OAAO,CAACqB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDF,OAAO,GAAGtF,MAAM,CAACkF,qBAAqB;MACxC;MAEAzD,GAAG,CAACwD,MAAM,CAACA,MAAM,CAAC,CAACvC,IAAI,CAAC4C,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAOnE,MAAM;AACf","ignoreList":[]}
@@ -1,4 +1,4 @@
1
1
  // Aggregates utility modules together.
2
2
 
3
- export * as errors from "./errors";
3
+ export * from "./errors";
4
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["errors"],"sources":["../../../../src/server/utils/index.ts"],"sourcesContent":["// Aggregates utility modules together.\n\nexport * as errors from './errors';\n"],"mappings":"AAAA;;AAEA,OAAO,KAAKA,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/server/utils/index.ts"],"sourcesContent":["// Aggregates utility modules together.\n\nexport * from './errors';\n"],"mappings":"AAAA;;AAEA","ignoreList":[]}
@@ -86,5 +86,5 @@ export const BaseButton = ({
86
86
  * @prop {string} [button] to the root element of any button.
87
87
  * @prop {string} [disabled] to the root element of disabled button.
88
88
  */
89
- export default themed(BaseButton, 'Button', defaultTheme);
89
+ export default /* #__PURE__ */themed(BaseButton, 'Button', defaultTheme);
90
90
  //# sourceMappingURL=index.js.map