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

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 (241) hide show
  1. package/babel.config.js +1 -0
  2. package/babel.libweb.config.js +16 -0
  3. package/bin/build.js +16 -10
  4. package/bin/setup.js +11 -8
  5. package/build/development/client/index.js.map +1 -1
  6. package/build/development/index.js +9 -4
  7. package/build/development/index.js.map +1 -1
  8. package/build/development/server/Cache.js.map +1 -1
  9. package/build/development/server/index.js +13 -8
  10. package/build/development/server/index.js.map +1 -1
  11. package/build/development/server/renderer.js +15 -8
  12. package/build/development/server/renderer.js.map +1 -1
  13. package/build/development/server/server.js +18 -15
  14. package/build/development/server/server.js.map +1 -1
  15. package/build/development/shared/components/Button/index.js +6 -6
  16. package/build/development/shared/components/Button/index.js.map +1 -1
  17. package/build/development/shared/components/Checkbox/index.js +8 -8
  18. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  19. package/build/development/shared/components/GenericLink/index.js +5 -1
  20. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  21. package/build/development/shared/components/Input/index.js +10 -9
  22. package/build/development/shared/components/Input/index.js.map +1 -1
  23. package/build/development/shared/components/Link.js.map +1 -1
  24. package/build/development/shared/components/Modal/index.js +8 -6
  25. package/build/development/shared/components/Modal/index.js.map +1 -1
  26. package/build/development/shared/components/NavLink.js.map +1 -1
  27. package/build/development/shared/components/PageLayout/index.js +6 -6
  28. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  29. package/build/development/shared/components/TextArea/index.js +13 -9
  30. package/build/development/shared/components/TextArea/index.js.map +1 -1
  31. package/build/development/shared/components/Throbber/index.js +6 -6
  32. package/build/development/shared/components/Throbber/index.js.map +1 -1
  33. package/build/development/shared/components/WithTooltip/Tooltip.js +1 -0
  34. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  35. package/build/development/shared/components/WithTooltip/index.js +7 -7
  36. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  37. package/build/development/shared/components/YouTubeVideo/index.js +9 -9
  38. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  39. package/build/development/shared/components/index.js.map +1 -1
  40. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  41. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  42. package/build/development/shared/components/selectors/CustomDropdown/index.js +11 -11
  43. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  44. package/build/development/shared/components/selectors/NativeDropdown/index.js +12 -12
  45. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  46. package/build/development/shared/components/selectors/Switch/index.js +7 -7
  47. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  48. package/build/development/shared/utils/config.js +5 -6
  49. package/build/development/shared/utils/config.js.map +1 -1
  50. package/build/development/shared/utils/globalState.js.map +1 -1
  51. package/build/development/shared/utils/index.js.map +1 -1
  52. package/build/development/shared/utils/jest/E2eSsrEnv.js +14 -10
  53. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  54. package/build/development/shared/utils/splitComponent.js +18 -21
  55. package/build/development/shared/utils/splitComponent.js.map +1 -1
  56. package/build/development/shared/utils/time.js.map +1 -1
  57. package/build/production/client/index.js.map +1 -1
  58. package/build/production/index.js +5 -3
  59. package/build/production/index.js.map +1 -1
  60. package/build/production/server/Cache.js.map +1 -1
  61. package/build/production/server/index.js +5 -5
  62. package/build/production/server/index.js.map +1 -1
  63. package/build/production/server/renderer.js +7 -7
  64. package/build/production/server/renderer.js.map +1 -1
  65. package/build/production/server/server.js +5 -7
  66. package/build/production/server/server.js.map +1 -1
  67. package/build/production/shared/components/Button/index.js +1 -1
  68. package/build/production/shared/components/Button/index.js.map +1 -1
  69. package/build/production/shared/components/Checkbox/index.js +1 -1
  70. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  71. package/build/production/shared/components/GenericLink/index.js +2 -2
  72. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  73. package/build/production/shared/components/Input/index.js +1 -1
  74. package/build/production/shared/components/Input/index.js.map +1 -1
  75. package/build/production/shared/components/Link.js.map +1 -1
  76. package/build/production/shared/components/Modal/index.js +1 -1
  77. package/build/production/shared/components/Modal/index.js.map +1 -1
  78. package/build/production/shared/components/NavLink.js.map +1 -1
  79. package/build/production/shared/components/PageLayout/index.js +1 -1
  80. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  81. package/build/production/shared/components/TextArea/index.js +1 -1
  82. package/build/production/shared/components/TextArea/index.js.map +1 -1
  83. package/build/production/shared/components/Throbber/index.js +1 -1
  84. package/build/production/shared/components/Throbber/index.js.map +1 -1
  85. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  86. package/build/production/shared/components/WithTooltip/index.js +1 -1
  87. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  88. package/build/production/shared/components/YouTubeVideo/index.js +1 -1
  89. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  90. package/build/production/shared/components/index.js.map +1 -1
  91. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  92. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  93. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  94. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  95. package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
  96. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  97. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  98. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  99. package/build/production/shared/utils/config.js +3 -5
  100. package/build/production/shared/utils/config.js.map +1 -1
  101. package/build/production/shared/utils/globalState.js.map +1 -1
  102. package/build/production/shared/utils/index.js.map +1 -1
  103. package/build/production/shared/utils/jest/E2eSsrEnv.js +8 -7
  104. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  105. package/build/production/shared/utils/splitComponent.js +6 -17
  106. package/build/production/shared/utils/splitComponent.js.map +1 -1
  107. package/build/production/shared/utils/time.js.map +1 -1
  108. package/build/types-code/index.d.ts +2 -2
  109. package/build/web/client/getInj.js +47 -0
  110. package/build/web/client/getInj.js.map +1 -0
  111. package/build/web/client/index.js +31 -0
  112. package/build/web/client/index.js.map +1 -0
  113. package/build/web/client/init.js +47 -0
  114. package/build/web/client/init.js.map +1 -0
  115. package/build/web/index.js +23 -0
  116. package/build/web/index.js.map +1 -0
  117. package/build/web/server/Cache.js +54 -0
  118. package/build/web/server/Cache.js.map +1 -0
  119. package/build/web/server/index.js +211 -0
  120. package/build/web/server/index.js.map +1 -0
  121. package/build/web/server/renderer.js +516 -0
  122. package/build/web/server/renderer.js.map +1 -0
  123. package/build/web/server/server.js +233 -0
  124. package/build/web/server/server.js.map +1 -0
  125. package/build/web/server/utils/errors.js +103 -0
  126. package/build/web/server/utils/errors.js.map +1 -0
  127. package/build/web/server/utils/index.js +4 -0
  128. package/build/web/server/utils/index.js.map +1 -0
  129. package/build/web/shared/components/Button/index.js +90 -0
  130. package/build/web/shared/components/Button/index.js.map +1 -0
  131. package/build/web/shared/components/Button/style.scss +54 -0
  132. package/build/web/shared/components/Checkbox/index.js +35 -0
  133. package/build/web/shared/components/Checkbox/index.js.map +1 -0
  134. package/build/web/shared/components/Checkbox/theme.scss +63 -0
  135. package/build/web/shared/components/GenericLink/index.js +107 -0
  136. package/build/web/shared/components/GenericLink/index.js.map +1 -0
  137. package/build/web/shared/components/GenericLink/style.scss +3 -0
  138. package/build/web/shared/components/Input/index.js +71 -0
  139. package/build/web/shared/components/Input/index.js.map +1 -0
  140. package/build/web/shared/components/Input/theme.scss +52 -0
  141. package/build/web/shared/components/Link.js +20 -0
  142. package/build/web/shared/components/Link.js.map +1 -0
  143. package/build/web/shared/components/Modal/base-theme.scss +38 -0
  144. package/build/web/shared/components/Modal/index.js +128 -0
  145. package/build/web/shared/components/Modal/index.js.map +1 -0
  146. package/build/web/shared/components/Modal/styles.scss +3 -0
  147. package/build/web/shared/components/NavLink.js +13 -0
  148. package/build/web/shared/components/NavLink.js.map +1 -0
  149. package/build/web/shared/components/PageLayout/base-theme.scss +30 -0
  150. package/build/web/shared/components/PageLayout/index.js +38 -0
  151. package/build/web/shared/components/PageLayout/index.js.map +1 -0
  152. package/build/web/shared/components/TextArea/index.js +106 -0
  153. package/build/web/shared/components/TextArea/index.js.map +1 -0
  154. package/build/web/shared/components/TextArea/style.scss +68 -0
  155. package/build/web/shared/components/Throbber/index.js +26 -0
  156. package/build/web/shared/components/Throbber/index.js.map +1 -0
  157. package/build/web/shared/components/Throbber/theme.scss +26 -0
  158. package/build/web/shared/components/WithTooltip/Tooltip.js +226 -0
  159. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -0
  160. package/build/web/shared/components/WithTooltip/default-theme.scss +36 -0
  161. package/build/web/shared/components/WithTooltip/index.js +117 -0
  162. package/build/web/shared/components/WithTooltip/index.js.map +1 -0
  163. package/build/web/shared/components/YouTubeVideo/base.scss +15 -0
  164. package/build/web/shared/components/YouTubeVideo/index.js +56 -0
  165. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -0
  166. package/build/web/shared/components/YouTubeVideo/throbber.scss +11 -0
  167. package/build/web/shared/components/index.js +18 -0
  168. package/build/web/shared/components/index.js.map +1 -0
  169. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +79 -0
  170. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -0
  171. package/build/web/shared/components/selectors/CustomDropdown/Options/style.scss +6 -0
  172. package/build/web/shared/components/selectors/CustomDropdown/index.js +120 -0
  173. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -0
  174. package/build/web/shared/components/selectors/CustomDropdown/theme.scss +118 -0
  175. package/build/web/shared/components/selectors/NativeDropdown/index.js +82 -0
  176. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -0
  177. package/build/web/shared/components/selectors/NativeDropdown/theme.scss +81 -0
  178. package/build/web/shared/components/selectors/Switch/index.js +49 -0
  179. package/build/web/shared/components/selectors/Switch/index.js.map +1 -0
  180. package/build/web/shared/components/selectors/Switch/theme.scss +39 -0
  181. package/build/web/shared/components/selectors/common.js +12 -0
  182. package/build/web/shared/components/selectors/common.js.map +1 -0
  183. package/build/web/shared/components/selectors/index.js +4 -0
  184. package/build/web/shared/components/selectors/index.js.map +1 -0
  185. package/build/web/shared/utils/config.js +19 -0
  186. package/build/web/shared/utils/config.js.map +1 -0
  187. package/build/web/shared/utils/globalState.js +15 -0
  188. package/build/web/shared/utils/globalState.js.map +1 -0
  189. package/build/web/shared/utils/index.js +13 -0
  190. package/build/web/shared/utils/index.js.map +1 -0
  191. package/build/web/shared/utils/isomorphy/buildInfo.js +44 -0
  192. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -0
  193. package/build/web/shared/utils/isomorphy/environment-check.js +17 -0
  194. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -0
  195. package/build/web/shared/utils/isomorphy/index.js +36 -0
  196. package/build/web/shared/utils/isomorphy/index.js.map +1 -0
  197. package/build/web/shared/utils/jest/E2eSsrEnv.js +230 -0
  198. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -0
  199. package/build/web/shared/utils/jest/global.js +4 -0
  200. package/build/web/shared/utils/jest/global.js.map +1 -0
  201. package/build/web/shared/utils/jest/index.js +165 -0
  202. package/build/web/shared/utils/jest/index.js.map +1 -0
  203. package/build/web/shared/utils/splitComponent.js +218 -0
  204. package/build/web/shared/utils/splitComponent.js.map +1 -0
  205. package/build/web/shared/utils/time.js +85 -0
  206. package/build/web/shared/utils/time.js.map +1 -0
  207. package/build/web/shared/utils/webpack.js +61 -0
  208. package/build/web/shared/utils/webpack.js.map +1 -0
  209. package/build/web/styles/_global/reset.css +52 -0
  210. package/build/web/styles/_mixins/fonts.scss +40 -0
  211. package/build/web/styles/_mixins/media.scss +150 -0
  212. package/build/web/styles/_mixins/typography.scss +83 -0
  213. package/build/web/styles/global.scss +11 -0
  214. package/build/web/styles/mixins.scss +6 -0
  215. package/config/babel/node-ssr.js +5 -2
  216. package/config/jest/default.js +7 -2
  217. package/config/webpack/app-base.js +10 -7
  218. package/config/webpack/app-development.js +3 -2
  219. package/package.json +24 -34
  220. package/src/index.ts +9 -7
  221. package/src/server/index.ts +6 -8
  222. package/src/server/renderer.tsx +7 -9
  223. package/src/server/server.ts +13 -15
  224. package/src/shared/components/Modal/base-theme.scss +1 -1
  225. package/src/shared/components/PageLayout/base-theme.scss +1 -1
  226. package/src/shared/utils/config.ts +5 -10
  227. package/src/shared/utils/jest/E2eSsrEnv.ts +8 -1
  228. package/src/shared/utils/splitComponent.tsx +17 -20
  229. package/build/development/__chunk_groups__.json +0 -6
  230. package/build/development/style.css +0 -909
  231. package/build/development/web.bundle.js +0 -752
  232. package/build/production/__chunk_groups__.json +0 -6
  233. package/build/production/style.css +0 -2
  234. package/build/production/style.css.map +0 -1
  235. package/build/production/web.bundle.js +0 -3
  236. package/build/production/web.bundle.js.LICENSE.txt +0 -9
  237. package/build/production/web.bundle.js.map +0 -1
  238. package/dev-styles.js +0 -1
  239. package/node-entry.js +0 -15
  240. package/null.js +0 -1
  241. package/prod-styles.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":";;;;;;;;AAEA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,QAAA,GAAAD,OAAA;AAEA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,UAAA,GAAAH,OAAA;AAIqB,IAAAI,WAAA,GAAAJ,OAAA;AApBrB;;AAsBA;AACA;AACA;AACA;AACA,IAAIK,iBAA+B;AAEnC,IAAIC,yBAAc,EAAE;EAClB;EACA;AACF;AACA;AACA;EACED,iBAAiB,GAAGL,OAAO,sBAAgB,CAAC,CAACO,OAAO,CAAC,CAAC,CAACC,YAAY,IAAI,CAAC,CAAC;EACzE;AACF;AACA;AACA;AACA;AAEA,MAAMC,SAAiC,GAAG,CAAC,CAAC;AAE5C,SAASC,aAAaA,CAAA,EAAG;EACvB,OAAO,IAAAC,uBAAY,EAAC,CAAC,CAACC,UAAU;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,cAAcA,CACrBC,IAAY,EACZC,YAAyB,EACzBC,QAAiB,EACU;EAC3B,IAAIC,GAA8B;EAClC,MAAMC,IAAI,GAAG,G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react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","_interopRequireWildcard","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","getClientChunkGroups","IS_CLIENT_SIDE","undefined","getInj","Promise","resolve","then","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","asset","endsWith","promise","push","length","allSettled","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n return getInj().CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":";;;;;;;;AAEA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,QAAA,GAAAD,OAAA;AAEA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,UAAA,GAAAH,OAAA;AAIqB,IAAAI,WAAA,GAAAJ,OAAA;AAAA,SAAAK,wBAAAC,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAH,uBAAA,YAAAA,CA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,CACA,CAAC;IAEhB,CAAC;IAED,OAAO;MAAEvE,OAAO,EAAEsE;IAAQ,CAAC;EAC7B,CAAC,CAAC;EAEF,MAAMU,SAAmD,GAAGA,CAAC;IAC3DT,QAAQ;IACR,GAAGE;EACY,CAAC,kBAChB,IAAAM,eAAA,EAACE,eAAQ;IAACC,QAAQ,EAAElB,WAAY;IAAAO,QAAA,eAC9B,IAAAQ,eAAA,EAACd;IACC;IAAA;MAAA,GACIQ,IAAI;MAAAF,QAAA,EAEPA;IAAQ,CACI;EAAC,CACR,CACX;EAED,OAAOS,SAAS;AAClB","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"time.js","names":["_cookie","require","_react","_dayjs","_interopRequireDefault","_jsUtils","_reactGlobalState","_globalState","useCurrent","autorefresh","globalStatePath","precision","SEC_MS","now","setter","useGlobalState","Date","useEffect","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","getSsrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","serialize","toString","path","time","DAY_MS","HOUR_MS","MIN_MS","YEAR_MS","timer","_default","exports","default","Object","assign","dayjs"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport { useEffect } from 'react';\nimport dayjs from 'dayjs';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { getSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAC,sBAAA,CAAAH,OAAA;AAEA,IAAAI,QAAA,GAAAJ,OAAA;AASA,IAAAK,iB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EACf,MAAM;IACJ,MAAMsB,KAAK,GAAGL,UAAU,IACnBC,UAAU,EAAEK,GAAG,CAACC,OAAO,CAACP,UAAU,CAAW;IAClD,OAAOK,KAAK,GAAGG,QAAQ,CAACH,KAAK,CAAC,GAAG,CAAC;EACpC,CACF,CAAC;EACD,IAAAf,gBAAS,EAAC,MAAM;IACd,MAAMmB,IAAI,GAAG,IAAIpB,IAAI,CAAC,CAAC;IACvB,MAAMgB,KAAK,GAAGI,IAAI,CAACC,iBAAiB,CAAC,CAAC;IACtCN,SAAS,CAACC,KAAK,CAAC;IAChB,IAAIL,UAAU,EAAE;MACdW,QAAQ,CAACC,MAAM,GAAG,IAAAC,iBAAS,EAACb,UAAU,EAAEK,KAAK,CAACS,QAAQ,CAAC,CAAC,EAAE;QAAEC,IAAI,EAAE;MAAI,CAAC,CAAC;IAC1E;EACF,CAAC,EAAE,CAACf,UAAU,EAAEI,SAAS,CAAC,CAAC;EAC3B,OAAOD,MAAM;AACf;AAEA,MAAMa,IAAI,GAAG;EACXC,MAAM,EAANA,eAAM;EACNC,OAAO,EAAPA,gBAAO;EACPC,MAAM,EAANA,eAAM;EACNlC,MAAM,EAANA,eAAM;EACNmC,OAAO,EAAPA,gBAAO;EACPlC,GAAG,EAAEG,IAAI,CAACH,GAAG;EACbmC,KAAK,EAALA,cAAK;EACLxC,UAAU;EACVkB;AACF,CAAC;AAAC,IAAAuB,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaC,MAAM,CAACC,MAAM,CAACC,cAAK,EAAEX,IAAI,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"time.js","names":["_cookie","require","_react","_dayjs","_interopRequireDefault","_jsUtils","_reactGlobalState","_globalState","useCurrent","autorefresh","globalStatePath","precision","SEC_MS","now","setter","useGlobalState","Date","useEffect","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","getSsrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","serialize","toString","path","time","DAY_MS","HOUR_MS","MIN_MS","YEAR_MS","timer","_default","exports","default","Object","assign","dayjs"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport { useEffect } from 'react';\nimport dayjs from 'dayjs';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { getSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAC,sBAAA,CAAAH,OAAA;AAEA,IAAAI,QAAA,GAAAJ,OAAA;AASA,IAAAK,iBAAA,GAAAL,OAAA;AAEA,IAAAM,YAAA,GAAAN,OAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASO,UAAUA,CAAC;EACzBC,WAAW,GAAG,KAAK;EACnBC,eAAe,GAAG,aAAa;EAC/BC,SAAS,GAAG,CAAC,GAAGC;AAClB,CAAC,GAAG,CAAC,CAAC,EAAU;EACd,MAAM,CAACC,GAAG,EAAEC,MAAM,CAAC,GAAG,IAAAC,gCAAc,EAClCL,eAAe,EACfM,IAAI,CAACH,GACP,CAAC;EACD,IAAAI,gBAAS,EAAC,MAAM;IACd,IAAIC,OAAmC;IACvC,MAAMC,MAAM,GAAGA,CAAA,KAAY;MACzBL,MAAM,CAAEM,GAAG,IAAK;QACd,MAAMC,GAAG,GAAGL,IAAI,CAACH,GAAG,CAAC,CAAC;QACtB,OAAOS,IAAI,CAACC,GAAG,CAACF,GAAG,GAAGD,GAAG,CAAC,GAAGT,SAAS,GAAGU,GAAG,GAAGD,GAAG;MACpD,CAAC,CAAC;MACF,IA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AM;EACNC,OAAO,EAAPA,gBAAO;EACPC,MAAM,EAANA,eAAM;EACNlC,MAAM,EAANA,eAAM;EACNmC,OAAO,EAAPA,gBAAO;EACPlC,GAAG,EAAEG,IAAI,CAACH,GAAG;EACbmC,KAAK,EAALA,cAAK;EACLxC,UAAU;EACVkB;AACF,CAAC;AAAA,IAAAuB,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcC,MAAM,CAACC,MAAM,CAACC,cAAK,EAAEX,IAAI,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"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 function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\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={getInj().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":"gLAIA,IAAAA,OAAA,CAAAC,OAAA,qBACA,IAAAC,YAAA,CAAAD,OAAA,6BACA,IAAAE,YAAA,CAAAF,OAAA,iBAEA,IAAAG,iBAAA,CAAAH,OAAA,mCAEA,IAAAI,OAAA,CAAAC,sBAAA,CAAAL,OAAA,cAA8B,IAAAM,WAAA,CAAAN,OAAA,sBAV9B;AACA,qBAgBA;AACA;AACA;AACA;AACA,GACe,QAAS,CAAAO,MAAMA,CAC5BC,WAA0B,CAC1BC,OAAiB,CAAG,CAAC,CAAC,CAChB,CACN,KAAM,CAAAC,SAAS,CAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC,CACvD,GAAI,CAACF,SAAS,CAAE,KAAM,CAAAG,KAAK,CAAC,wCAAwC,CAAC,CACrE,KAAM,CAAAC,KAAK,cACT,GAAAR,WAAA,CAAAS,GAAA,EAACZ,iBAAA,CAAAa,mBAAmB,EAACC,YAAY,CAAE,GAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,EAAIV,OAAO,CAACQ,YAAa,CAAAG,QAAA,cACzE,GAAAd,WAAA,CAAAS,GAAA,EAACb,YAAA,CAAAmB,aAAa,EAAAD,QAAA,cACZ,GAAAd,WAAA,CAAAS,GAAA,EAACd,YAAA,CAAAqB,cAAc,EAAAF,QAAA,cACb,GAAAd,WAAA,CAAAS,GAAA,EAACP,WAAW,GAAE,CAAC,CACD,CAAC,CACJ,CAAC,CACG,CACtB,CAED,GAAIC,OAAO,CAACc,WAAW,CAAE,CACvB,KAAM,CAAAC,IAAI,CAAG,GAAAC,kBAAU,EAACf,SAAS,CAAC,CAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CACnB,CAAC,IAAM,GAAAa,mBAAW,EAACjB,SAAS,CAAEI,KAAK,CACrC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","_jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"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 function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\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={getInj().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":"gLAIA,IAAAA,OAAA,CAAAC,OAAA,qBACA,IAAAC,YAAA,CAAAD,OAAA,6BACA,IAAAE,YAAA,CAAAF,OAAA,iBAEA,IAAAG,iBAAA,CAAAH,OAAA,mCAEA,IAAAI,OAAA,CAAAC,sBAAA,CAAAL,OAAA,cAA8B,IAAAM,WAAA,CAAAN,OAAA,sBAV9B;AACA,qBAgBA;AACA;AACA;AACA;AACA,GACe,QAAS,CAAAO,MAAMA,CAC5BC,WAA0B,CAC1BC,OAAiB,CAAG,CAAC,CAAC,CAChB,CACN,KAAM,CAAAC,SAAS,CAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC,CACvD,GAAI,CAACF,SAAS,CAAE,KAAM,CAAAG,KAAK,CAAC,wCAAwC,CAAC,CACrE,KAAM,CAAAC,KAAK,cACT,GAAAC,eAAA,EAACC,qCAAmB,EAACC,YAAY,CAAE,GAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,EAAIV,OAAO,CAACQ,YAAa,CAAAG,QAAA,cACzE,GAAAL,eAAA,EAACM,0BAAa,EAAAD,QAAA,cACZ,GAAAL,eAAA,EAACO,2BAAc,EAAAF,QAAA,cACb,GAAAL,eAAA,EAACP,WAAW,GAAE,CAAC,CACD,CAAC,CACJ,CAAC,CACG,CACtB,CAED,GAAIC,OAAO,CAACc,WAAW,CAAE,CACvB,KAAM,CAAAC,IAAI,CAAG,GAAAC,kBAAU,EAACf,SAAS,CAAC,CAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CACnB,CAAC,IAAM,GAAAa,mBAAW,EAACjB,SAAS,CAAEI,KAAK,CACrC","ignoreList":[]}
@@ -1,7 +1,9 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={client:true,server:true,assertEmptyObject:true,config:true,Barrier:true,Cached:true,Emitter:true,isomorphy:true,getSsrContext:true,Semaphore:true,splitComponent:true,themed:true,ThemeProvider:true,time:true,webpack:true,withRetries:true,getGlobalState:true,GlobalStateProvider:true,newAsyncDataEnvelope:true,useAsyncCollection:true,useAsyncData:true,useGlobalState:true,withGlobalStateType:true};Object.defineProperty(exports,"Barrier",{enumerable:true,get:function(){return _utils.Barrier}});Object.defineProperty(exports,"Cached",{enumerable:true,get:function(){return _utils.Cached}});Object.defineProperty(exports,"Emitter",{enumerable:true,get:function(){return _utils.Emitter}});Object.defineProperty(exports,"GlobalStateProvider",{enumerable:true,get:function(){return _reactGlobalState.GlobalStateProvider}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return _utils.Semaphore}});Object.defineProperty(exports,"ThemeProvider",{enumerable:true,get:function(){return _utils.ThemeProvider}});Object.defineProperty(exports,"assertEmptyObject",{enumerable:true,get:function(){return _utils.assertEmptyObject}});exports.client=void 0;Object.defineProperty(exports,"config",{enumerable:true,get:function(){return _utils.config}});Object.defineProperty(exports,"getGlobalState",{enumerable:true,get:function(){return _reactGlobalState.getGlobalState}});Object.defineProperty(exports,"getSsrContext",{enumerable:true,get:function(){return _utils.getSsrContext}});Object.defineProperty(exports,"isomorphy",{enumerable:true,get:function(){return _utils.isomorphy}});Object.defineProperty(exports,"newAsyncDataEnvelope",{enumerable:true,get:function(){return _reactGlobalState.newAsyncDataEnvelope}});exports.server=void 0;Object.defineProperty(exports,"splitComponent",{enumerable:true,get:function(){return _utils.splitComponent}});Object.defineProperty(exports,"themed",{enumerable:true,get:function(){return _utils.themed}});Object.defineProperty(exports,"time",{enumerable:true,get:function(){return _utils.time}});Object.defineProperty(exports,"useAsyncCollection",{enumerable:true,get:function(){return _reactGlobalState.useAsyncCollection}});Object.defineProperty(exports,"useAsyncData",{enumerable:true,get:function(){return _reactGlobalState.useAsyncData}});Object.defineProperty(exports,"useGlobalState",{enumerable:true,get:function(){return _reactGlobalState.useGlobalState}});Object.defineProperty(exports,"webpack",{enumerable:true,get:function(){return _utils.webpack}});Object.defineProperty(exports,"withGlobalStateType",{enumerable:true,get:function(){return _reactGlobalState.withGlobalStateType}});Object.defineProperty(exports,"withRetries",{enumerable:true,get:function(){return _utils.withRetries}});var _utils=require("./shared/utils");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _components=require("./shared/components");Object.keys(_components).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_components[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _components[key]}})});// It is a safeguard against multiple instances / versions of the library
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={client:true,server:true,assertEmptyObject:true,config:true,Barrier:true,Cached:true,Emitter:true,isomorphy:true,getSsrContext:true,Semaphore:true,splitComponent:true,themed:true,ThemeProvider:true,time:true,webpack:true,withRetries:true,getGlobalState:true,GlobalStateProvider:true,newAsyncDataEnvelope:true,useAsyncCollection:true,useAsyncData:true,useGlobalState:true,withGlobalStateType:true};Object.defineProperty(exports,"Barrier",{enumerable:true,get:function(){return _utils.Barrier}});Object.defineProperty(exports,"Cached",{enumerable:true,get:function(){return _utils.Cached}});Object.defineProperty(exports,"Emitter",{enumerable:true,get:function(){return _utils.Emitter}});Object.defineProperty(exports,"GlobalStateProvider",{enumerable:true,get:function(){return _reactGlobalState.GlobalStateProvider}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return _utils.Semaphore}});Object.defineProperty(exports,"ThemeProvider",{enumerable:true,get:function(){return _utils.ThemeProvider}});Object.defineProperty(exports,"assertEmptyObject",{enumerable:true,get:function(){return _utils.assertEmptyObject}});exports.client=void 0;Object.defineProperty(exports,"config",{enumerable:true,get:function(){return _utils.config}});Object.defineProperty(exports,"getGlobalState",{enumerable:true,get:function(){return _reactGlobalState.getGlobalState}});Object.defineProperty(exports,"getSsrContext",{enumerable:true,get:function(){return _utils.getSsrContext}});Object.defineProperty(exports,"isomorphy",{enumerable:true,get:function(){return _utils.isomorphy}});Object.defineProperty(exports,"newAsyncDataEnvelope",{enumerable:true,get:function(){return _reactGlobalState.newAsyncDataEnvelope}});exports.server=void 0;Object.defineProperty(exports,"splitComponent",{enumerable:true,get:function(){return _utils.splitComponent}});Object.defineProperty(exports,"themed",{enumerable:true,get:function(){return _utils.themed}});Object.defineProperty(exports,"time",{enumerable:true,get:function(){return _utils.time}});Object.defineProperty(exports,"useAsyncCollection",{enumerable:true,get:function(){return _reactGlobalState.useAsyncCollection}});Object.defineProperty(exports,"useAsyncData",{enumerable:true,get:function(){return _reactGlobalState.useAsyncData}});Object.defineProperty(exports,"useGlobalState",{enumerable:true,get:function(){return _reactGlobalState.useGlobalState}});Object.defineProperty(exports,"webpack",{enumerable:true,get:function(){return _utils.webpack}});Object.defineProperty(exports,"withGlobalStateType",{enumerable:true,get:function(){return _reactGlobalState.withGlobalStateType}});Object.defineProperty(exports,"withRetries",{enumerable:true,get:function(){return _utils.withRetries}});var _client=_interopRequireDefault(require("./client"));var _utils=require("./shared/utils");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _components=require("./shared/components");Object.keys(_components).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_components[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _components[key]}})});// It is a safeguard against multiple instances / versions of the library
2
2
  // being loaded into environment by mistake (e.g. because of different
3
3
  // packages pinning down different exact versions of the lib, thus preventing
4
4
  // a proper dedupe and using a single common library version).
5
- if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true;const server=exports.server=_utils.webpack.requireWeak("./server",__dirname);const client=exports.client=server?undefined// eslint-disable-next-line @typescript-eslint/no-require-imports
6
- :require("./client").default;
5
+ if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true;// TODO: This is a rapid workaround to get rid of __dirname. I guess, later
6
+ // we'll re-implement requireWeak() to accept import.meta.url directly, and
7
+ // this workaround won't be needed.
8
+ let dirname=require("url").pathToFileURL(__filename).toString();dirname=dirname.slice(5,dirname.lastIndexOf("/"));const server=exports.server=_utils.webpack.requireWeak("./server",dirname);const client=exports.client=server?undefined:_client.default;
7
9
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_utils","require","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","server","webpack","requireWeak","__dirname","client","undefined","default"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nimport type * as ClientM from './client';\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\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', __dirname);\n\nconst client = server\n ? undefined\n\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n : (require('./client') as typeof ClientM).default;\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 config,\n Barrier,\n Cached,\n Emitter,\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":"sxFAEA,IAAAA,MAAA,CAAAC,OAAA,mBAqBA,IAAAC,iBAAA,CAAAD,OAAA,mCAmBA,IAAAE,WAAA,CAAAF,OAAA,wBAAAG,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,UAAAC,GAAA,KAAAA,GAAA,cAAAA,GAAA,0BAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,CAAAJ,GAAA,YAAAA,GAAA,IAAAK,OAAA,EAAAA,OAAA,CAAAL,GAAA,IAAAJ,WAAA,CAAAI,GAAA,SAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,CAAAL,GAAA,EAAAO,UAAA,MAAAC,GAAA,SAAAA,CAAA,SAAAZ,WAAA,CAAAI,GAAA,OAnCA;AACA;AACA;AACA;AACA,GAAIS,MAAM,CAACC,0BAA0B,CAAE,CACrC,KAAM,CAAAC,KAAK,CAAC,uCAAuC,CACrD,CAAC,IAAM,CAAAF,MAAM,CAACC,0BAA0B,CAAG,IAAI,CAE/C,KAAM,CAAAE,MAAM,CAAAP,OAAA,CAAAO,MAAA,CAAGC,cAAO,CAACC,WAAW,YAAoCC,SAAS,CAAC,CAEhF,KAAM,CAAAC,MAAM,CAAAX,OAAA,CAAAW,MAAA,CAAGJ,MAAM,CACjBK,SAEF;AAAA,CACGvB,OAAO,WAAW,CAAC,CAAoBwB,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_client","_interopRequireDefault","require","_utils","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","pathToFileURL","__filename","toString","slice","lastIndexOf","server","webpack","requireWeak","client","undefined","clientModule"],"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.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\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 config,\n Barrier,\n Cached,\n Emitter,\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":"y2FAEA,IAAAA,OAAA,CAAAC,sBAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,mBAsBA,IAAAE,iBAAA,CAAAF,OAAA,mCAmBA,IAAAG,WAAA,CAAAH,OAAA,wBAAAI,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,UAAAC,GAAA,KAAAA,GAAA,cAAAA,GAAA,0BAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,CAAAJ,GAAA,YAAAA,GAAA,IAAAK,OAAA,EAAAA,OAAA,CAAAL,GAAA,IAAAJ,WAAA,CAAAI,GAAA,SAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,CAAAL,GAAA,EAAAO,UAAA,MAAAC,GAAA,SAAAA,CAAA,SAAAZ,WAAA,CAAAI,GAAA,OArCA;AACA;AACA;AACA;AACA,GAAIS,MAAM,CAACC,0BAA0B,CAAE,CACrC,KAAM,CAAAC,KAAK,CAAC,uCAAuC,CACrD,CAAC,IAAM,CAAAF,MAAM,CAACC,0BAA0B,CAAG,IAAI,CAE/C;AACA;AACA;AACA,GAAI,CAAAE,OAAO,CAAAnB,OAAA,QAAAoB,aAAA,CAAAC,UAAA,EAAAC,QAAA,EAAkB,CAC7BH,OAAO,CAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,CAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC,CAEpD,KAAM,CAAAC,MAAM,CAAAb,OAAA,CAAAa,MAAA,CAAGC,cAAO,CAACC,WAAW,YAAoCR,OAAO,CAAC,CAE9E,KAAM,CAAAS,MAAM,CAAAhB,OAAA,CAAAgB,MAAA,CAAGH,MAAM,CAAGI,SAAS,CAAGC,eAAY","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"Cache.js","names":["Cache","items","size","constructor","maxSize","get","key","maxage","Number","MAX_VALUE","item","Date","now","timestamp","data","add","cached","entries","Object","sort","a","b","entry","itemKey","exports","default"],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items: Record<string, CachedItemT<DatumT>> = {};\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items[key];\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items[key];\n if (cached) this.size -= cached.size;\n\n this.items[key] = { data, size, timestamp: Date.now() };\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = Object.entries(this.items);\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n delete this.items[itemKey];\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"6FAMA;AACA;AACA,GACe,KAAM,CAAAA,KAAc,CACzBC,KAAK,CAAwC,CAAC,CAAC,CAE/CC,IAAI,CAAG,CAAC,CAEhBC,WAAWA,CAASC,OAAe,CAAE,MAAjBA,OAAe,CAAfA,OAAmB,CAEvC;AACF;AACA;AACA;AACA;AACA;AACA;AACA,KACEC,GAAGA,CAAC,CACFC,GAAG,CACHC,MAAM,CAAGC,MAAM,CAACC,SAIlB,CAAC,CAAiB,CAChB,KAAM,CAAAC,IAAI,CAAG,IAAI,CAACT,KAAK,CAACK,GAAG,CAAC,CAC5B,MAAO,CAAAI,IAAI,EAAIC,IAAI,CAACC,GAAG,CAAC,CAAC,CAAGF,IAAI,CAACG,SAAS,CAAGN,MAAM,CAAGG,IAAI,CAACI,IAAI,CAAG,IACpE,CAEA;AACF;AACA;AACA;AACA;AACA,KACEC,GAAGA,CAACD,IAAY,CAAER,GAAW,CAAEJ,IAAY,CAAQ,CACjD,KAAM,CAAAc,MAAM,CAAG,IAAI,CAACf,KAAK,CAACK,GAAG,CAAC,CAC9B,GAAIU,MAAM,CAAE,IAAI,CAACd,IAAI,EAAIc,MAAM,CAACd,IAAI,CAEpC,IAAI,CAACD,KAAK,CAACK,GAAG,CAAC,CAAG,CAAEQ,IAAI,CAAEZ,IAAI,CAAEW,SAAS,CAAEF,IAAI,CAACC,GAAG,CAAC,CAAE,CAAC,CACvD,IAAI,CAACV,IAAI,EAAIA,IAAI,CAEjB,GAAI,IAAI,CAACA,IAAI,CAAG,IAAI,CAACE,OAAO,CAAE,CAC5B,KAAM,CAAAa,OAAO,CAAGC,MAAM,CAACD,OAAO,CAAC,IAAI,CAAChB,KAAK,CAAC,CAC1CgB,OAAO,CAACE,IAAI,CAAC,CAACC,CAAC,CAAEC,CAAC,GAAKD,CAAC,CAAC,CAAC,CAAC,CAACP,SAAS,CAAGQ,CAAC,CAAC,CAAC,CAAC,CAACR,SAAS,CAAC,CAEvD,IAAK,KAAM,CAAAS,KAAK,GAAI,CAAAL,OAAO,CAAE,CAC3B,KAAM,CAACM,OAAO,CAAEb,IAAI,CAAC,CAAGY,KAAK,CAC7B,MAAO,KAAI,CAACrB,KAAK,CAACsB,OAAO,CAAC,CAC1B,IAAI,CAACrB,IAAI,EAAIQ,IAAI,CAACR,IAAI,CACtB,GAAI,IAAI,CAACA,IAAI,CAAG,IAAI,CAACE,OAAO,CAAG,CAAC,CAAE,KACpC,CACF,CACF,CACF,CAACoB,OAAA,CAAAC,OAAA,CAAAzB,KAAA","ignoreList":[]}
1
+ {"version":3,"file":"Cache.js","names":["Cache","items","size","constructor","maxSize","get","key","maxage","Number","MAX_VALUE","item","Date","now","timestamp","data","add","cached","entries","Object","sort","a","b","entry","itemKey","exports","default"],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items: Record<string, CachedItemT<DatumT>> = {};\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items[key];\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items[key];\n if (cached) this.size -= cached.size;\n\n this.items[key] = { data, size, timestamp: Date.now() };\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = Object.entries(this.items);\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n delete this.items[itemKey];\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"6FAMA;AACA;AACA,GACe,KAAM,CAAAA,KAAc,CACzBC,KAAK,CAAwC,CAAC,CAAC,CAE/CC,IAAI,CAAG,CAAC,CAEhBC,WAAWA,CAASC,OAAe,CAAE,MAAjBA,OAAe,CAAfA,OAAmB,CAEvC;AACF;AACA;AACA;AACA;AACA;AACA;AACA,KACEC,GAAGA,CAAC,CACFC,GAAG,CACHC,MAAM,CAAGC,MAAM,CAACC,SAIlB,CAAC,CAAiB,CAChB,KAAM,CAAAC,IAAI,CAAG,IAAI,CAACT,KAAK,CAACK,GAAG,CAAC,CAC5B,MAAO,CAAAI,IAAI,EAAIC,IAAI,CAACC,GAAG,CAAC,CAAC,CAAGF,IAAI,CAACG,SAAS,CAAGN,MAAM,CAAGG,IAAI,CAACI,IAAI,CAAG,IACpE,CAEA;AACF;AACA;AACA;AACA;AACA,KACEC,GAAGA,CAACD,IAAY,CAAER,GAAW,CAAEJ,IAAY,CAAQ,CACjD,KAAM,CAAAc,MAAM,CAAG,IAAI,CAACf,KAAK,CAACK,GAAG,CAAC,CAC9B,GAAIU,MAAM,CAAE,IAAI,CAACd,IAAI,EAAIc,MAAM,CAACd,IAAI,CAEpC,IAAI,CAACD,KAAK,CAACK,GAAG,CAAC,CAAG,CAAEQ,IAAI,CAAEZ,IAAI,CAAEW,SAAS,CAAEF,IAAI,CAACC,GAAG,CAAC,CAAE,CAAC,CACvD,IAAI,CAACV,IAAI,EAAIA,IAAI,CAEjB,GAAI,IAAI,CAACA,IAAI,CAAG,IAAI,CAACE,OAAO,CAAE,CAC5B,KAAM,CAAAa,OAAO,CAAGC,MAAM,CAACD,OAAO,CAAC,IAAI,CAAChB,KAAK,CAAC,CAC1CgB,OAAO,CAACE,IAAI,CAAC,CAACC,CAAC,CAAEC,CAAC,GAAKD,CAAC,CAAC,CAAC,CAAC,CAACP,SAAS,CAAGQ,CAAC,CAAC,CAAC,CAAC,CAACR,SAAS,CAAC,CAEvD,IAAK,KAAM,CAAAS,KAAK,GAAI,CAAAL,OAAO,CAAE,CAC3B,KAAM,CAACM,OAAO,CAAEb,IAAI,CAAC,CAAGY,KAAK,CAC7B,MAAO,KAAI,CAACrB,KAAK,CAACsB,OAAO,CAAC,CAC1B,IAAI,CAACrB,IAAI,EAAIQ,IAAI,CAACR,IAAI,CACtB,GAAI,IAAI,CAACA,IAAI,CAAG,IAAI,CAACE,OAAO,CAAG,CAAC,CAAE,KACpC,CACF,CACF,CACF,CAAAoB,OAAA,CAAAC,OAAA,CAAAzB,KAAA","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=launchServer;Object.defineProperty(exports,"errors",{enumerable:true,get:function(){return _utils.errors}});Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});require("source-map-support/register");var _nodeHttp=_interopRequireDefault(require("node:http"));var _nodeHttps=_interopRequireDefault(require("node:https"));var _lodash=require("lodash");require("raf/polyfill");var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./utils");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}// eslint-disable-next-line import/no-unassigned-import
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=launchServer;Object.defineProperty(exports,"errors",{enumerable:true,get:function(){return _utils.errors}});Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});require("source-map-support/register");var _nodeHttp=_interopRequireDefault(require("node:http"));var _nodeHttps=_interopRequireDefault(require("node:https"));var _cloneDeep=_interopRequireDefault(require("lodash/cloneDeep"));var _defaults=_interopRequireDefault(require("lodash/defaults"));var _isFinite=_interopRequireDefault(require("lodash/isFinite"));var _isNumber=_interopRequireDefault(require("lodash/isNumber"));var _isString=_interopRequireDefault(require("lodash/isString"));var _toNumber=_interopRequireDefault(require("lodash/toNumber"));require("raf/polyfill");var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./utils");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}// eslint-disable-next-line import/no-unassigned-import
2
2
  // Polyfill required by ReactJS.
3
3
  // TODO: Double-check, if it is still required by React v19?
4
4
  // eslint-disable-next-line import/no-unassigned-import
@@ -7,7 +7,7 @@
7
7
  * TODO: Drop this function?
8
8
  * @param value Port name or number.
9
9
  * @return Port number (Number), name (String), or false.
10
- */function normalizePort(value){const port=(0,_lodash.toNumber)(value);if((0,_lodash.isFinite)(port))return port;/* port number */if(!(0,_lodash.isNumber)(port))return value;/* named pipe */return false}/**
10
+ */function normalizePort(value){const port=(0,_toNumber.default)(value);if((0,_isFinite.default)(port))return port;/* port number */if(!(0,_isNumber.default)(port))return value;/* named pipe */return false}/**
11
11
  * Creates and launches web-server for ReactJS application. Allows zero
12
12
  * or detailed configuration, supports server-side rendering,
13
13
  * and development tools, including Hot Module Reloading (HMR).
@@ -124,8 +124,8 @@
124
124
  * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,
125
125
  * defaults to 1 second.
126
126
  * @return Resolves to an object with created Express and HTTP servers.
127
- */async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=(0,_lodash.cloneDeep)(options);// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
128
- ops.port=normalizePort(ops.port||process.env.PORT||3000);(0,_lodash.defaults)(ops,{httpsRedirect:true});// TODO: Need a separate type for normalized options, which guarantees
127
+ */async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=(0,_cloneDeep.default)(options);// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
128
+ ops.port=normalizePort(ops.port||process.env.PORT||3000);(0,_defaults.default)(ops,{httpsRedirect:true});// TODO: Need a separate type for normalized options, which guarantees
129
129
  // the logger is set!
130
- ops.logger??=(0,_renderer.newDefaultLogger)({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await(0,_server.default)(webpackConfig,ops);let httpServer;if(ops.https){httpServer=_nodeHttps.default.createServer({cert:ops.https.cert,key:ops.https.key},expressServer)}else httpServer=_nodeHttp.default.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=(0,_lodash.isString)(ops.port)?`Pipe ${ops.port}`:`Port ${ops.port}`;/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();const bind=(0,_lodash.isString)(addr)?`pipe ${addr}`:`port ${addr.port}`;ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`)});httpServer.listen(ops.port);return{expressServer,httpServer}}launchServer.SCRIPT_LOCATIONS=_renderer.SCRIPT_LOCATIONS;launchServer.getDefaultCspSettings=_server.getDefaultCspSettings;launchServer.errors=_utils.errors;
130
+ ops.logger??=(0,_renderer.newDefaultLogger)({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await(0,_server.default)(webpackConfig,ops);let httpServer;if(ops.https){httpServer=_nodeHttps.default.createServer({cert:ops.https.cert,key:ops.https.key},expressServer)}else httpServer=_nodeHttp.default.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=(0,_isString.default)(ops.port)?`Pipe ${ops.port}`:`Port ${ops.port}`;/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();const bind=(0,_isString.default)(addr)?`pipe ${addr}`:`port ${addr.port}`;ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`)});httpServer.listen(ops.port);return{expressServer,httpServer}}launchServer.SCRIPT_LOCATIONS=_renderer.SCRIPT_LOCATIONS;launchServer.getDefaultCspSettings=_server.getDefaultCspSettings;launchServer.errors=_utils.errors;
131
131
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["require","_nodeHttp","_interopRequireDefault","_nodeHttps","_lodash","_server","_interopRequireWildcard","_renderer","_utils","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","undefined","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport {\n cloneDeep,\n defaults,\n isFinite,\n isNumber,\n isString,\n toNumber,\n} from 'lodash';\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';\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), or false.\n */\nfunction normalizePort(value: number | string) {\n const port = toNumber(value);\n if (isFinite(port)) return port; /* port number */\n if (!isNumber(port)) return value; /* named pipe */\n return false;\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 = isString(ops.port) ? `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 = isString(addr) ? `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":"mZACAA,OAAA,gCAEA,IAAAC,SAAA,CAAAC,sBAAA,CAAAF,OAAA,eACA,IAAAG,UAAA,CAAAD,sBAAA,CAAAF,OAAA,gBAEA,IAAAI,OAAA,CAAAJ,OAAA,WAYAA,OAAA,iBAIA,IAAAK,OAAA,CAAAC,uBAAA,CAAAN,OAAA,cAMA,IAAAO,SAAA,CAAAP,OAAA,eAEA,IAAAQ,MAAA,CAAAR,OAAA,YAAiC,SAAAM,wBAAAG,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAL,uBAAA,SAAAA,CAAAG,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA,CAAAG,CAAA,CAAAD,CAAA,KAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,SAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,EAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,CAAAQ,CAAA,YAAAP,CAAA,IAAAD,CAAA,aAAAC,CAAA,KAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,CAAAC,CAAA,KAAAM,CAAA,EAAAD,CAAA,CAAAU,MAAA,CAAAC,cAAA,GAAAD,MAAA,CAAAE,wBAAA,CAAAlB,CAAA,CAAAC,CAAA,KAAAM,CAAA,CAAAK,GAAA,EAAAL,CAAA,CAAAM,GAAA,EAAAP,CAAA,CAAAE,CAAA,CAAAP,CAAA,CAAAM,CAAA,EAAAC,CAAA,CAAAP,CAAA,EAAAD,CAAA,CAAAC,CAAA,UAAAO,CAAA,GAAAR,CAAA,CAAAC,CAAA,EA9BjC;AAeA;AACA;AACA;AAwBA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAkB,aAAaA,CAACC,KAAsB,CAAE,CAC7C,KAAM,CAAAC,IAAI,CAAG,GAAAC,gBAAQ,EAACF,KAAK,CAAC,CAC5B,GAAI,GAAAG,gBAAQ,EAACF,IAAI,CAAC,CAAE,MAAO,CAAAA,IAAI,CAAE,iBACjC,GAAI,CAAC,GAAAG,gBAAQ,EAACH,IAAI,CAAC,CAAE,MAAO,CAAAD,KAAK,CAAE,gBACnC,MAAO,MACT,CAYA;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,GACe,cAAe,CAAAK,YAAYA,CACxCC,aAA4B,CAC5BC,OAAi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,CAAC,CACzD,MAAO,CAAApB,OAAO,CAACuB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,YAAY,CACfzB,GAAG,CAACO,MAAM,CAAEa,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC,CAC9C,MAAO,CAAApB,OAAO,CAACuB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,CAAAC,SAAS,CACd,QACE,KAAM,CAAAN,KACV,CACF,CAAC,CAAC,CAEF,iDACAP,UAAU,CAACM,EAAE,CAAC,WAAW,CAAE,IAAM,CAC/B,KAAM,CAAAQ,IAAI,CAAGd,UAAU,CAACe,OAAO,CAAC,CAAE,CAClC,KAAM,CAAAN,IAAI,CAAG,GAAAC,gBAAQ,EAACI,IAAI,CAAC,CAAG,QAAQA,IAAI,EAAE,CAAG,QAAQA,IAAI,CAAClC,IAAI,EAAE,CAClEO,GAAG,CAACO,MAAM,CAAEsB,IAAI,CAAC,uBAAuBP,IAAI,OAC1CpB,OAAO,CAACC,GAAG,CAAC2B,QAAQ,OAAO,CAC/B,CAAC,CAAC,CAEFjB,UAAU,CAACkB,MAAM,CAAC/B,GAAG,CAACP,IAAI,CAAC,CAE3B,MAAO,CACLkB,aAAa,CACbE,UACF,CACF,CAEAhB,YAAY,CAACmC,gBAAgB,CAAGA,0BAAgB,CAChDnC,YAAY,CAACoC,qBAAqB,CAAGA,6BAAqB,CAC1DpC,YAAY,CAACqC,MAAM,CAAGA,aAAM","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["require","_nodeHttp","_interopRequireDefault","_nodeHttps","_cloneDeep","_defaults","_isFinite","_isNumber","_isString","_toNumber","_server","_interopRequireWildcard","_renderer","_utils","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","undefined","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport cloneDeep from 'lodash/cloneDeep';\nimport defaults from 'lodash/defaults';\nimport isFinite from 'lodash/isFinite';\nimport isNumber from 'lodash/isNumber';\nimport isString from 'lodash/isString';\nimport toNumber from 'lodash/toNumber';\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';\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), or false.\n */\nfunction normalizePort(value: number | string) {\n const port = toNumber(value);\n if (isFinite(port)) return port; /* port number */\n if (!isNumber(port)) return value; /* named pipe */\n return false;\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 = isString(ops.port) ? `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 = isString(addr) ? `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":"mZACAA,OAAA,gCAEA,IAAAC,SAAA,CAAAC,sBAAA,CAAAF,OAAA,eACA,IAAAG,UAAA,CAAAD,sBAAA,CAAAF,OAAA,gBAEA,IAAAI,UAAA,CAAAF,sBAAA,CAAAF,OAAA,sBACA,IAAAK,SAAA,CAAAH,sBAAA,CAAAF,OAAA,qBACA,IAAAM,SAAA,CAAAJ,sBAAA,CAAAF,OAAA,qBACA,IAAAO,SAAA,CAAAL,sBAAA,CAAAF,OAAA,qBACA,IAAAQ,SAAA,CAAAN,sBAAA,CAAAF,OAAA,qBACA,IAAAS,SAAA,CAAAP,sBAAA,CAAAF,OAAA,qBAKAA,OAAA,iBAIA,IAAAU,OAAA,CAAAC,uBAAA,CAAAX,OAAA,cAMA,IAAAY,SAAA,CAAAZ,OAAA,eAEA,IAAAa,MAAA,CAAAb,OAAA,YAAe,SAAAW,wBAAAG,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAL,uBAAA,SAAAA,CAAAG,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA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use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ServerSsrContext=exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _nodeFs=_interopRequireDefault(require("node:fs"));var _nodePath=_interopRequireDefault(require("node:path"));var _nodeStream=require("node:stream");var _nodeZlib=require("node:zlib");var _winston=_interopRequireDefault(require("winston"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _jsUtils=require("@dr.pogodin/js-utils");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _static=require("react-dom/static");var _reactHelmet=require("@dr.pogodin/react-helmet");var _reactRouter=require("react-router");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _buildInfo=require("../shared/utils/isomorphy/buildInfo");var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ServerSsrContext=exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _nodeFs=_interopRequireDefault(require("node:fs"));var _nodePath=_interopRequireDefault(require("node:path"));var _nodeStream=require("node:stream");var _nodeZlib=require("node:zlib");var _winston=_interopRequireDefault(require("winston"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _jsUtils=require("@dr.pogodin/js-utils");var _clone=_interopRequireDefault(require("lodash/clone"));var _cloneDeep=_interopRequireDefault(require("lodash/cloneDeep"));var _defaults=_interopRequireDefault(require("lodash/defaults"));var _get=_interopRequireDefault(require("lodash/get"));var _isString=_interopRequireDefault(require("lodash/isString"));var _mapValues=_interopRequireDefault(require("lodash/mapValues"));var _omit=_interopRequireDefault(require("lodash/omit"));var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _static=require("react-dom/static");var _reactHelmet=require("@dr.pogodin/react-helmet");var _reactRouter=require("react-router");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _buildInfo=require("../shared/utils/isomorphy/buildInfo");var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
2
2
  * ExpressJS middleware for server-side rendering of a ReactJS app.
3
- */const sanitizedConfig=(0,_lodash.omit)(_config.default,"SECRET");// Note: These type definitions for logger are copied from Winston logger,
3
+ */const sanitizedConfig=(0,_omit.default)(_config.default,"SECRET");// Note: These type definitions for logger are copied from Winston logger,
4
4
  // then simplified to make it easier to fit an alternative logger into this
5
5
  // interface.
6
6
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
7
7
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
8
8
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
9
- let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCATIONS){SCRIPT_LOCATIONS["BODY_OPEN"]="BODY_OPEN";SCRIPT_LOCATIONS["DEFAULT"]="DEFAULT";SCRIPT_LOCATIONS["HEAD_OPEN"]="HEAD_OPEN";return SCRIPT_LOCATIONS}({});class ServerSsrContext extends _reactGlobalState.SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super((0,_lodash.cloneDeep)(initialState)??{});this.chunkGroups=chunkGroups;this.req=req}}exports.ServerSsrContext=ServerSsrContext;/**
9
+ let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCATIONS){SCRIPT_LOCATIONS["BODY_OPEN"]="BODY_OPEN";SCRIPT_LOCATIONS["DEFAULT"]="DEFAULT";SCRIPT_LOCATIONS["HEAD_OPEN"]="HEAD_OPEN";return SCRIPT_LOCATIONS}({});class ServerSsrContext extends _reactGlobalState.SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super((0,_cloneDeep.default)(initialState)??{});this.chunkGroups=chunkGroups;this.req=req}}/**
10
10
  * Reads build-time information about the app. This information is generated
11
11
  * by our standard Webpack config for apps, and it is written into
12
12
  * ".build-info" file in the context folder specified in Webpack config.
@@ -14,7 +14,7 @@ let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCAT
14
14
  * suitable for cryptographical use.
15
15
  * @param context Webpack context path used during the build.
16
16
  * @return Resolves to the build-time information.
17
- */function getBuildInfo(context){const url=_nodePath.default.resolve(context,".build-info");return JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}/**
17
+ */exports.ServerSsrContext=ServerSsrContext;function getBuildInfo(context){const url=_nodePath.default.resolve(context,".build-info");return JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}/**
18
18
  * Attempts to read from disk the named chunk groups mapping generated
19
19
  * by Webpack during the compilation.
20
20
  * It will not work for development builds, where these stats should be captured
@@ -46,7 +46,7 @@ res=null}return res}/**
46
46
  * DEFAULT: string[];
47
47
  * HEAD_OPEN: string[];
48
48
  * }}
49
- */function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if((0,_lodash.isString)(script)){if(script)res[SCRIPT_LOCATIONS.DEFAULT]+=script}else if(script.code){if(script.location in res)res[script.location]+=script.code;else throw Error(`Invalid location "${script.location}"`)}}return res}/**
49
+ */function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if((0,_isString.default)(script)){if(script)res[SCRIPT_LOCATIONS.DEFAULT]+=script}else if(script.code){if(script.location in res)res[script.location]+=script.code;else throw Error(`Invalid location "${script.location}"`)}}return res}/**
50
50
  * Creates a new default (Winston) logger.
51
51
  * @param {object} [options={}]
52
52
  * @param {string} [options.defaultLogLevel='info']
@@ -81,7 +81,7 @@ res=null}return res}/**
81
81
  * - `maxage?: number` &ndash; the maximum age of cached result in ms.
82
82
  * If undefined - infinite age is assumed.
83
83
  * @return Created middleware.
84
- */function factory(webpackConfig,options){const ops=(0,_lodash.defaults)((0,_lodash.clone)(options),{beforeRender:async()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7});// Note: in normal use the default logger is created and set in the root
84
+ */function factory(webpackConfig,options){const ops=(0,_defaults.default)((0,_clone.default)(options),{beforeRender:async()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7});// Note: in normal use the default logger is created and set in the root
85
85
  // server function, and this initialization is for testing uses, where
86
86
  // renderer is imported directly.
87
87
  ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);(0,_buildInfo.setBuildInfo)(buildInfo);// publicPath from webpack.output has a trailing slash at the end.
@@ -99,7 +99,7 @@ brr instanceof Promise?brr:Promise.resolve(brr),prepareCipher(buildInfo.key)]);l
99
99
  // These data come from the Webpack compilation, either from the stats
100
100
  // attached to the request (in dev mode), or from a file output during
101
101
  // the build (in prod mode).
102
- let chunkGroups;const webpackStats=(0,_lodash.get)(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=(0,_lodash.mapValues)(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets?.map(({name})=>name)??[])}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Optional server-side rendering. */const App=ops.Application;let appHtmlMarkup="";const ssrContext=new ServerSsrContext(req,chunkGroups,initialState);let stream;if(App){const ssrStart=Date.now();// TODO: Somehow, without it TS does not realise that
102
+ let chunkGroups;const webpackStats=(0,_get.default)(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=(0,_mapValues.default)(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets?.map(({name})=>name)??[])}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Optional server-side rendering. */const App=ops.Application;let appHtmlMarkup="";const ssrContext=new ServerSsrContext(req,chunkGroups,initialState);let stream;if(App){const ssrStart=Date.now();// TODO: Somehow, without it TS does not realise that
103
103
  // App has been checked to exist.
104
104
  const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ssrContext.chunks=[];// NOTE: JS does not have problems if resolve() and reject() methods
105
105
  // of a Promise are called multiple times, with different arguments;