@dr.pogodin/react-utils 1.25.5 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/babel.config.js +3 -1
  2. package/bin/build.js +25 -5
  3. package/build/development/client/getInj.js +9 -8
  4. package/build/development/client/getInj.js.map +1 -1
  5. package/build/development/client/index.js +6 -3
  6. package/build/development/client/index.js.map +1 -1
  7. package/build/development/client/init.js +4 -0
  8. package/build/development/client/init.js.map +1 -1
  9. package/build/development/index.js +168 -42
  10. package/build/development/index.js.map +1 -1
  11. package/build/development/server/Cache.js +13 -13
  12. package/build/development/server/Cache.js.map +1 -1
  13. package/build/development/server/index.js +16 -24
  14. package/build/development/server/index.js.map +1 -1
  15. package/build/development/server/renderer.js +56 -44
  16. package/build/development/server/renderer.js.map +1 -1
  17. package/build/development/server/server.js +9 -5
  18. package/build/development/server/server.js.map +1 -1
  19. package/build/development/server/utils/errors.js +12 -9
  20. package/build/development/server/utils/errors.js.map +1 -1
  21. package/build/development/server/utils/index.js +2 -2
  22. package/build/development/server/utils/index.js.map +1 -1
  23. package/build/development/shared/components/Button/index.js +8 -7
  24. package/build/development/shared/components/Button/index.js.map +1 -1
  25. package/build/development/shared/components/Checkbox/index.js +25 -28
  26. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  27. package/build/development/shared/components/Dropdown/index.js +25 -19
  28. package/build/development/shared/components/Dropdown/index.js.map +1 -1
  29. package/build/development/shared/components/GenericLink/index.js +44 -37
  30. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  31. package/build/development/shared/components/Input/index.js +8 -9
  32. package/build/development/shared/components/Input/index.js.map +1 -1
  33. package/build/development/shared/components/Link.js +10 -9
  34. package/build/development/shared/components/Link.js.map +1 -1
  35. package/build/development/shared/components/MetaTags.js +22 -18
  36. package/build/development/shared/components/MetaTags.js.map +1 -1
  37. package/build/development/shared/components/Modal/index.js +17 -18
  38. package/build/development/shared/components/Modal/index.js.map +1 -1
  39. package/build/development/shared/components/NavLink.js +10 -9
  40. package/build/development/shared/components/NavLink.js.map +1 -1
  41. package/build/development/shared/components/PageLayout/index.js +17 -20
  42. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  43. package/build/development/shared/components/ScalableRect/index.js +27 -7
  44. package/build/development/shared/components/ScalableRect/index.js.map +1 -1
  45. package/build/development/shared/components/Throbber/index.js +14 -23
  46. package/build/development/shared/components/Throbber/index.js.map +1 -1
  47. package/build/development/shared/components/WithTooltip/Tooltip.js +20 -24
  48. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  49. package/build/development/shared/components/WithTooltip/index.js +11 -11
  50. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  51. package/build/development/shared/components/YouTubeVideo/index.js +16 -15
  52. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  53. package/build/development/shared/components/index.js +2 -2
  54. package/build/development/shared/components/index.js.map +1 -1
  55. package/build/development/shared/utils/config.js +1 -2
  56. package/build/development/shared/utils/config.js.map +1 -1
  57. package/build/development/shared/utils/globalState.js +15 -0
  58. package/build/development/shared/utils/globalState.js.map +1 -0
  59. package/build/development/shared/utils/index.js +13 -11
  60. package/build/development/shared/utils/index.js.map +1 -1
  61. package/build/development/shared/utils/isomorphy/buildInfo.js +7 -3
  62. package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
  63. package/build/development/shared/utils/isomorphy/environment-check.js +2 -4
  64. package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
  65. package/build/development/shared/utils/isomorphy/index.js.map +1 -1
  66. package/build/development/shared/utils/jest/E2eSsrEnv.js +35 -28
  67. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  68. package/build/development/shared/utils/jest/global.js +17 -0
  69. package/build/development/shared/utils/jest/global.js.map +1 -0
  70. package/build/development/shared/utils/jest/index.js +18 -11
  71. package/build/development/shared/utils/jest/index.js.map +1 -1
  72. package/build/development/shared/utils/splitComponent.js +25 -34
  73. package/build/development/shared/utils/splitComponent.js.map +1 -1
  74. package/build/development/shared/utils/time.js +16 -13
  75. package/build/development/shared/utils/time.js.map +1 -1
  76. package/build/development/shared/utils/webpack.js +3 -3
  77. package/build/development/shared/utils/webpack.js.map +1 -1
  78. package/build/development/web.bundle.js +92 -82
  79. package/build/production/client/getInj.js +1 -1
  80. package/build/production/client/getInj.js.map +1 -1
  81. package/build/production/client/index.js +4 -4
  82. package/build/production/client/index.js.map +1 -1
  83. package/build/production/client/init.js +3 -1
  84. package/build/production/client/init.js.map +1 -1
  85. package/build/production/index.js +1 -1
  86. package/build/production/index.js.map +1 -1
  87. package/build/production/server/Cache.js +7 -8
  88. package/build/production/server/Cache.js.map +1 -1
  89. package/build/production/server/index.js +5 -4
  90. package/build/production/server/index.js.map +1 -1
  91. package/build/production/server/renderer.js +32 -30
  92. package/build/production/server/renderer.js.map +1 -1
  93. package/build/production/server/server.js +7 -5
  94. package/build/production/server/server.js.map +1 -1
  95. package/build/production/server/utils/errors.js +9 -10
  96. package/build/production/server/utils/errors.js.map +1 -1
  97. package/build/production/server/utils/index.js +1 -1
  98. package/build/production/server/utils/index.js.map +1 -1
  99. package/build/production/shared/components/Button/index.js +4 -4
  100. package/build/production/shared/components/Button/index.js.map +1 -1
  101. package/build/production/shared/components/Checkbox/index.js +12 -12
  102. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  103. package/build/production/shared/components/Dropdown/index.js +11 -11
  104. package/build/production/shared/components/Dropdown/index.js.map +1 -1
  105. package/build/production/shared/components/GenericLink/index.js +25 -20
  106. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  107. package/build/production/shared/components/Input/index.js +7 -7
  108. package/build/production/shared/components/Input/index.js.map +1 -1
  109. package/build/production/shared/components/Link.js +2 -2
  110. package/build/production/shared/components/Link.js.map +1 -1
  111. package/build/production/shared/components/MetaTags.js +10 -10
  112. package/build/production/shared/components/MetaTags.js.map +1 -1
  113. package/build/production/shared/components/Modal/index.js +2 -2
  114. package/build/production/shared/components/Modal/index.js.map +1 -1
  115. package/build/production/shared/components/NavLink.js +1 -1
  116. package/build/production/shared/components/NavLink.js.map +1 -1
  117. package/build/production/shared/components/PageLayout/index.js +2 -2
  118. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  119. package/build/production/shared/components/ScalableRect/index.js +7 -3
  120. package/build/production/shared/components/ScalableRect/index.js.map +1 -1
  121. package/build/production/shared/components/Throbber/index.js +2 -2
  122. package/build/production/shared/components/Throbber/index.js.map +1 -1
  123. package/build/production/shared/components/WithTooltip/Tooltip.js +13 -13
  124. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  125. package/build/production/shared/components/WithTooltip/index.js +3 -3
  126. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  127. package/build/production/shared/components/YouTubeVideo/index.js +7 -7
  128. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  129. package/build/production/shared/components/index.js +1 -1
  130. package/build/production/shared/components/index.js.map +1 -1
  131. package/build/production/shared/utils/config.js +1 -1
  132. package/build/production/shared/utils/config.js.map +1 -1
  133. package/build/production/shared/utils/globalState.js +3 -0
  134. package/build/production/shared/utils/globalState.js.map +1 -0
  135. package/build/production/shared/utils/index.js +3 -3
  136. package/build/production/shared/utils/index.js.map +1 -1
  137. package/build/production/shared/utils/isomorphy/buildInfo.js +7 -4
  138. package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
  139. package/build/production/shared/utils/isomorphy/environment-check.js +2 -2
  140. package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
  141. package/build/production/shared/utils/isomorphy/index.js.map +1 -1
  142. package/build/production/shared/utils/jest/E2eSsrEnv.js +9 -9
  143. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  144. package/build/production/shared/utils/jest/global.js +2 -0
  145. package/build/production/shared/utils/jest/global.js.map +1 -0
  146. package/build/production/shared/utils/jest/index.js +6 -6
  147. package/build/production/shared/utils/jest/index.js.map +1 -1
  148. package/build/production/shared/utils/splitComponent.js +16 -16
  149. package/build/production/shared/utils/splitComponent.js.map +1 -1
  150. package/build/production/shared/utils/time.js +12 -8
  151. package/build/production/shared/utils/time.js.map +1 -1
  152. package/build/production/shared/utils/webpack.js +3 -3
  153. package/build/production/shared/utils/webpack.js.map +1 -1
  154. package/build/production/web.bundle.js +1 -1
  155. package/build/production/web.bundle.js.map +1 -1
  156. package/build/types-code/client/getInj.d.ts +3 -0
  157. package/build/types-code/client/index.d.ts +11 -0
  158. package/build/types-code/client/init.d.ts +9 -0
  159. package/build/types-code/index.d.ts +10 -0
  160. package/build/types-code/server/Cache.d.ts +37 -0
  161. package/build/types-code/server/index.d.ts +145 -0
  162. package/build/types-code/server/renderer.d.ts +106 -0
  163. package/build/types-code/server/server.d.ts +41 -0
  164. package/build/types-code/server/utils/errors.d.ts +104 -0
  165. package/build/types-code/server/utils/index.d.ts +1 -0
  166. package/build/types-code/shared/components/Button/index.d.ts +27 -0
  167. package/build/types-code/shared/components/Checkbox/index.d.ts +21 -0
  168. package/build/types-code/shared/components/Dropdown/index.d.ts +23 -0
  169. package/build/types-code/shared/components/GenericLink/index.d.ts +61 -0
  170. package/build/types-code/shared/components/Input/index.d.ts +11 -0
  171. package/build/types-code/shared/components/Link.d.ts +12 -0
  172. package/build/types-code/shared/components/MetaTags.d.ts +68 -0
  173. package/build/types-code/shared/components/Modal/index.d.ts +26 -0
  174. package/build/types-code/shared/components/NavLink.d.ts +5 -0
  175. package/build/types-code/shared/components/PageLayout/index.d.ts +16 -0
  176. package/build/types-code/shared/components/ScalableRect/index.d.ts +19 -0
  177. package/build/types-code/shared/components/Throbber/index.d.ts +9 -0
  178. package/build/types-code/shared/components/WithTooltip/Tooltip.d.ts +23 -0
  179. package/build/types-code/shared/components/WithTooltip/index.d.ts +17 -0
  180. package/build/types-code/shared/components/YouTubeVideo/index.d.ts +13 -0
  181. package/build/types-code/shared/components/index.d.ts +16 -0
  182. package/build/types-code/shared/utils/config.d.ts +2 -0
  183. package/build/types-code/shared/utils/globalState.d.ts +20 -0
  184. package/build/types-code/shared/utils/index.d.ts +52 -0
  185. package/build/types-code/shared/utils/isomorphy/buildInfo.d.ts +23 -0
  186. package/build/types-code/shared/utils/isomorphy/environment-check.d.ts +11 -0
  187. package/build/types-code/shared/utils/isomorphy/index.d.ts +20 -0
  188. package/build/types-code/shared/utils/jest/E2eSsrEnv.d.ts +31 -0
  189. package/build/types-code/shared/utils/jest/global.d.ts +12 -0
  190. package/build/types-code/shared/utils/jest/index.d.ts +85 -0
  191. package/build/types-code/shared/utils/splitComponent.d.ts +41 -0
  192. package/build/types-code/shared/utils/time.d.ts +62 -0
  193. package/build/types-code/shared/utils/webpack.d.ts +18 -0
  194. package/build/types-scss/__tests__/js/config/publicPath support/__assets__/style.scss.d.ts +1 -0
  195. package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/MockPackageA/TestComponent/style.scss.d.ts +1 -0
  196. package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/MockPackageB/TestComponent/style.scss.d.ts +1 -0
  197. package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/style.scss.d.ts +1 -0
  198. package/build/types-scss/__tests__/js/shared/components/NavLink/styles.scss.d.ts +1 -0
  199. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentA/style.scss.d.ts +1 -0
  200. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentB/style.scss.d.ts +1 -0
  201. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentC/style.scss.d.ts +1 -0
  202. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/style.scss.d.ts +1 -0
  203. package/build/types-scss/__tests__/ts/config/publicPath support/__assets__/style.scss.d.ts +1 -0
  204. package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/MockPackageA/TestComponent/style.scss.d.ts +1 -0
  205. package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/MockPackageB/TestComponent/style.scss.d.ts +1 -0
  206. package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/style.scss.d.ts +1 -0
  207. package/build/types-scss/__tests__/ts/shared/components/NavLink/styles.scss.d.ts +1 -0
  208. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentA/style.scss.d.ts +1 -0
  209. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentB/style.scss.d.ts +1 -0
  210. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentC/style.scss.d.ts +1 -0
  211. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/style.scss.d.ts +1 -0
  212. package/build/types-scss/src/shared/components/Button/style.scss.d.ts +6 -0
  213. package/build/types-scss/src/shared/components/Checkbox/theme.scss.d.ts +6 -0
  214. package/build/types-scss/src/shared/components/Dropdown/theme.scss.d.ts +9 -0
  215. package/build/types-scss/src/shared/components/GenericLink/style.scss.d.ts +1 -0
  216. package/build/types-scss/src/shared/components/Input/theme.scss.d.ts +6 -0
  217. package/build/types-scss/src/shared/components/Modal/base-theme.scss.d.ts +5 -0
  218. package/build/types-scss/src/shared/components/PageLayout/base-theme.scss.d.ts +6 -0
  219. package/build/types-scss/src/shared/components/ScalableRect/style.scss.d.ts +2 -0
  220. package/build/types-scss/src/shared/components/Throbber/theme.scss.d.ts +6 -0
  221. package/build/types-scss/src/shared/components/WithTooltip/default-theme.scss.d.ts +7 -0
  222. package/build/types-scss/src/shared/components/YouTubeVideo/base.scss.d.ts +5 -0
  223. package/build/types-scss/src/shared/components/YouTubeVideo/throbber.scss.d.ts +4 -0
  224. package/config/eslint/jest.json +3 -2
  225. package/config/eslint/typescript.js +34 -0
  226. package/config/jest/default.js +3 -3
  227. package/package.json +75 -33
  228. package/src/client/getInj.ts +43 -0
  229. package/src/client/index.tsx +40 -0
  230. package/src/client/init.ts +47 -0
  231. package/src/index.ts +58 -0
  232. package/src/server/Cache.ts +68 -0
  233. package/src/server/index.ts +230 -0
  234. package/src/server/renderer.tsx +604 -0
  235. package/src/server/server.ts +309 -0
  236. package/src/server/utils/errors.ts +135 -0
  237. package/src/server/utils/index.ts +3 -0
  238. package/src/shared/components/Button/index.tsx +146 -0
  239. package/src/shared/components/Button/style.scss +53 -0
  240. package/src/shared/components/Checkbox/index.tsx +71 -0
  241. package/src/shared/components/Checkbox/theme.scss +43 -0
  242. package/src/shared/components/Dropdown/index.tsx +144 -0
  243. package/src/shared/components/Dropdown/theme.scss +63 -0
  244. package/src/shared/components/GenericLink/index.tsx +157 -0
  245. package/src/shared/components/GenericLink/style.scss +3 -0
  246. package/src/shared/components/Input/index.tsx +59 -0
  247. package/src/shared/components/Input/theme.scss +27 -0
  248. package/src/shared/components/Link.tsx +21 -0
  249. package/src/shared/components/MetaTags.tsx +170 -0
  250. package/src/shared/components/Modal/base-theme.scss +38 -0
  251. package/src/shared/components/Modal/index.tsx +144 -0
  252. package/src/shared/components/Modal/styles.scss +5 -0
  253. package/src/shared/components/NavLink.tsx +13 -0
  254. package/src/shared/components/PageLayout/base-theme.scss +30 -0
  255. package/src/shared/components/PageLayout/index.tsx +76 -0
  256. package/src/shared/components/ScalableRect/index.tsx +84 -0
  257. package/src/shared/components/ScalableRect/style.scss +10 -0
  258. package/src/shared/components/Throbber/index.tsx +43 -0
  259. package/src/shared/components/Throbber/theme.scss +26 -0
  260. package/src/shared/components/WithTooltip/Tooltip.tsx +353 -0
  261. package/src/shared/components/WithTooltip/default-theme.scss +36 -0
  262. package/src/shared/components/WithTooltip/index.tsx +204 -0
  263. package/src/shared/components/YouTubeVideo/base.scss +13 -0
  264. package/src/shared/components/YouTubeVideo/index.tsx +96 -0
  265. package/src/shared/components/YouTubeVideo/throbber.scss +11 -0
  266. package/src/shared/components/index.ts +17 -0
  267. package/src/shared/utils/config.ts +21 -0
  268. package/src/shared/utils/globalState.ts +29 -0
  269. package/src/shared/utils/index.ts +105 -0
  270. package/src/shared/utils/isomorphy/buildInfo.ts +54 -0
  271. package/src/shared/utils/isomorphy/environment-check.ts +18 -0
  272. package/src/shared/utils/isomorphy/index.ts +38 -0
  273. package/src/shared/utils/jest/E2eSsrEnv.ts +250 -0
  274. package/src/shared/utils/jest/global.ts +19 -0
  275. package/src/shared/utils/jest/index.tsx +157 -0
  276. package/src/shared/utils/splitComponent.tsx +255 -0
  277. package/src/shared/utils/time.ts +118 -0
  278. package/src/shared/utils/webpack.ts +45 -0
  279. package/src/styles/_global/reset.css +52 -0
  280. package/src/styles/global.scss +11 -0
  281. package/tsconfig.configs.json +18 -0
  282. package/tsconfig.json +27 -0
  283. package/tsconfig.types.json +53 -0
  284. package/typed-scss-modules.config.ts +9 -0
  285. package/types.d.ts +37 -0
  286. package/{webpack.config.js → webpack.config.ts} +7 -3
  287. package/config/babel/node-ssr.js +0 -85
  288. package/config/babel/webpack.js +0 -122
  289. package/config/webpack/app-base.js +0 -330
  290. package/config/webpack/app-development.js +0 -80
  291. package/config/webpack/app-production.js +0 -60
  292. package/config/webpack/lib-base.js +0 -155
  293. package/config/webpack/lib-development.js +0 -45
  294. package/config/webpack/lib-production.js +0 -44
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["_fs","_interopRequireDefault","require","_path","_stream","_zlib","_winston","_reactGlobalState","_jsUtils","_lodash","_config","_nodeForge","_server","_reactHelmet","_server2","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","exports","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","script","isString","code","location","undefined","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","level","combine","splat","timestamp","colorize","printf","message","stack","rest","Object","keys","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","status","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","chunkGroups","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","ssrContext","state","cloneDeep","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","renderToPipeableStream","jsx","GlobalStateProvider","children","StaticRouter","onAllReady","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","pipe","Writable","write","chunk","_","Helmet","renderStatic","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress"],"sources":["../../../src/server/renderer.jsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { Writable } from 'stream';\nimport { brotliCompress, brotliDecompress } from 'zlib';\nimport winston from 'winston';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport { setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\nexport const SCRIPT_LOCATIONS = {\n BODY_OPEN: 'BODY_OPEN',\n DEFAULT: 'DEFAULT',\n HEAD_OPEN: 'HEAD_OPEN',\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @ignore\n * @param {String} context Webpack context path used during the build.\n * @return {Object} Resolves to the build-time information.\n */\nfunction getBuildInfo(context) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @ignore\n * @param {string} buildDir\n * @return {object}\n */\nfunction readChunkGroupsJson(buildDir) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @ignore\n * @param {String} key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return {Promise} Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n res[script.location] += script.code;\n } else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}) {\n const { format, transports } = winston;\n return winston.createLogger({\n level: defaultLogLevel,\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n\n/**\n * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\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 {object} [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param {boolean} [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param {boolean} [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param {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 * @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 * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const ops = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n }\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n const cache = ops.staticCacheController\n ? new Cache(ops.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef;\n if (cache) {\n cacheRef = ops.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, req.nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender(req, sanitizedConfig),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet;\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n let App = ops.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n\n chunkGroups,\n };\n let stream;\n if (App) {\n const ssrStart = Date.now();\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\n const timeout = ops.ssrTimeout + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n /* eslint-enable no-await-in-loop */\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n App = '';\n stream.pipe(new Writable({\n write: (chunk, _, done) => {\n App += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon ? (\n '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n ) : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${App || ''}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add({ buffer, status }, cacheRef.key);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"ySAIA,IAAAA,GAAA,CAAAC,sBAAA,CAAAC,OAAA,QACA,IAAAC,KAAA,CAAAF,sBAAA,CAAAC,OAAA,UAEA,IAAAE,OAAA,CAAAF,OAAA,WACA,IAAAG,KAAA,CAAAH,OAAA,SACA,IAAAI,QAAA,CAAAL,sBAAA,CAAAC,OAAA,aAEA,IAAAK,iBAAA,CAAAL,OAAA,mCACA,IAAAM,QAAA,CAAAN,OAAA,yBAEA,IAAAO,OAAA,CAAAP,OAAA,WAUA,IAAAQ,OAAA,CAAAT,sBAAA,CAAAC,OAAA,YACA,IAAAS,UAAA,CAAAV,sBAAA,CAAAC,OAAA,gBAEA,IAAAU,OAAA,CAAAV,OAAA,qBACA,IAAAW,YAAA,CAAAX,OAAA,iBACA,IAAAY,QAAA,CAAAZ,OAAA,4BACA,IAAAa,oBAAA,CAAAd,sBAAA,CAAAC,OAAA,0BACA,IAAAc,UAAA,CAAAd,OAAA,wCAEA,IAAAe,MAAA,CAAAhB,sBAAA,CAAAC,OAAA,aAA4B,IAAAgB,WAAA,CAAAhB,OAAA,sBAjC5B;AACA;AACA,GAiCA,KAAM,CAAAiB,eAAe,CAAG,GAAAC,YAAI,EAACC,eAAM,CAAE,QAAQ,CAAC,CAEvC,KAAM,CAAAC,gBAAgB,CAAG,CAC9BC,SAAS,CAAE,WAAW,CACtBC,OAAO,CAAE,SAAS,CAClBC,SAAS,CAAE,WACb,CAAC,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GATAC,OAAA,CAAAJ,gBAAA,CAAAA,gBAAA,CAUA,QAA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EA;AACA;AACA;AACApF,GAAG,CAACmF,IAAI,CAACK,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdb,IAAI,CAACa,KAAK,CACZ,CACF,CACF"}
1
+ {"version":3,"file":"renderer.js","names":["_fs","_interopRequireDefault","require","_path","_stream","_zlib","_winston","_reactGlobalState","_jsUtils","_lodash","_config","_nodeForge","_server","_reactHelmet","_server2","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","exports","ServerSsrContext","SsrContext","chunks","status","constructor","req","chunkGroups","initialState","cloneDeep","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","isString","code","location","undefined","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","level","combine","splat","timestamp","colorize","printf","message","stack","rest","Object","keys","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","pipeableStream","renderToPipeableStream","jsx","GlobalStateProvider","state","children","StaticRouter","onAllReady","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","pipe","Writable","write","chunk","_","Helmet","renderStatic","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { type Request, type RequestHandler } from 'express';\nimport { type ComponentType } from 'react';\nimport { Writable } from 'stream';\nimport { brotliCompress, brotliDecompress } from 'zlib';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { type PipeableStream, renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport { type ChunkGroupsT, type SsrContextT } from 'utils/globalState';\n\nimport { type Configuration } from 'webpack';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\ninterface LogMethodI {\n (level: string, message: string, ...meta: any[]): void;\n}\ninterface LeveledLogMethodI {\n (message: string, ...meta: any[]): void;\n}\n\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nclass ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) || ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8'));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8'));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req: Request) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n res[script.location] += script.code;\n } else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}) {\n const { format, transports } = winston;\n return winston.createLogger({\n level: defaultLogLevel,\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n\ntype ConfigT = {\n [key: string]: ConfigT | string;\n};\n\ntype BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: any;\n};\n\ntype BeforeRenderT =\n(req: Request, config: ConfigT) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n }\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n interface BufferWithNonce extends Buffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, (req as any).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender!(req, sanitizedConfig as any),\n prepareCipher(buildInfo.key) as Promise<any>,\n ]);\n\n let helmet;\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }: { name: string }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: PipeableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise<PipeableStream>((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App2 />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n /* eslint-enable no-await-in-loop */\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n stream!.pipe(new Writable({\n write: (chunk, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon ? (\n '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n ) : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n const b = buffer as BufferWithNonce;\n if (error) failed(error);\n else {\n b.nonce = (req as any).nonce; // eslint-disable-line no-param-reassign\n cache!.add({ buffer: b, status }, cacheRef!.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"ySAIA,IAAAA,GAAA,CAAAC,sBAAA,CAAAC,OAAA,QACA,IAAAC,KAAA,CAAAF,sBAAA,CAAAC,OAAA,UAEAA,OAAA,YACAA,OAAA,UACA,IAAAE,OAAA,CAAAF,OAAA,W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E7L,MAAO,CAAC,CAAEiG,QAAQ,CAAE7E,GAAG,CAAE+E,MAAM,CAAC/D,MAAM,CAAC,CAC/DkE,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACArF,GAAG,CAACoF,IAAI,CAACK,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdZ,IAAI,CAACY,KAAK,CACZ,CACF,CACF"}
@@ -1,4 +1,4 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _path=require("path");var _url=require("url");var _lodash=require("lodash");var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _csurf=_interopRequireDefault(require("@dr.pogodin/csurf"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _path=require("path");var _url=require("url");var _lodash=require("lodash");var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _csurf=_interopRequireDefault(require("@dr.pogodin/csurf"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");require("webpack");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
2
2
  * Creation of standard ExpressJS server for ReactJS apps.
3
3
  */ /**
4
4
  * Default Content Security Policy settings.
@@ -26,15 +26,17 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
26
26
  * }} A deep copy of default CSP settings object used by `react-utils`,
27
27
  * with the exception of `nonce-xxx` clause in `script-src` directive,
28
28
  * which is added dynamically for each request.
29
- */function getDefaultCspSettings(){return(0,_lodash.cloneDeep)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_lodash.pick)(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;return res.redirect(url)}return next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{req.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
29
+ */function getDefaultCspSettings(){return(0,_lodash.cloneDeep)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_lodash.pick)(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;return res.redirect(url)}return next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
30
30
  // compatibility. Should be removed sometime later.
31
- req.cspNonce=req.nonce;// The deep clone is necessary here to ensure that default value can't be
31
+ req2.cspNonce=req2.nonce;// The deep clone is necessary here to ensure that default value can't be
32
32
  // mutated during request processing.
33
- let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);cspSettings.directives["script-src"].push(`'nonce-${req.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}_helmet.default.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use((0,_serveFavicon.default)(options.favicon))}server.use("/robots.txt",(req,res)=>res.send("User-agent: *\nDisallow:"));server.use(_express.default.json({limit:"300kb"}));server.use(_express.default.urlencoded({extended:false}));server.use((0,_cookieParser.default)());server.use(_requestIp.default.mw());server.use((0,_csurf.default)({cookie:true}));_morgan.default.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use((0,_morgan.default)(FORMAT,{stream:{write:options.logger.info.bind(options.logger)}}));// Note: no matter the "public path", we want the service worker, if any,
33
+ let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}_helmet.default.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use((0,_serveFavicon.default)(options.favicon))}server.use("/robots.txt",(req,res)=>res.send("User-agent: *\nDisallow:"));server.use(_express.default.json({limit:"300kb"}));server.use(_express.default.urlencoded({extended:false}));server.use((0,_cookieParser.default)());server.use(_requestIp.default.mw());server.use((0,_csurf.default)({cookie:true}));_morgan.default.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use((0,_morgan.default)(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
34
+ // then mark it as always present.
35
+ write:options.logger.info.bind(options.logger)}}));// Note: no matter the "public path", we want the service worker, if any,
34
36
  // to be served from the root, to have all web app pages in its scope.
35
37
  // Thus, this setup to serve it. Probably, need some more configuration
36
38
  // for special cases, but this will do for now.
37
- server.get("/__service-worker.js",_express.default.static(webpackConfig.output.path,{setHeaders:res=>res.set("Cache-Control","no-cache")}));/* Setup of Hot Module Reloading for development environment.
39
+ server.get("/__service-worker.js",_express.default.static(webpackConfig.output?.path||"",{setHeaders:res=>res.set("Cache-Control","no-cache")}));/* Setup of Hot Module Reloading for development environment.
38
40
  * These dependencies are not used, nor installed for production use,
39
41
  * hence we should violate some import-related lint rules. */ /* eslint-disable global-require */ /* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable import/no-unresolved */if(options.devMode){// This is a workaround for SASS bug:
40
42
  // https://github.com/dart-lang/sdk/issues/27979
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV","undefined"],"sources":["../../../src/server/server.js"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => array.filter((item) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output;\n\n const server = express();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output.path,\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, express.static(webpackConfig.output.path));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((error, req, res, next) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) return next(error);\n\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n return undefined;\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,IAAAA,KAAA,CAAAC,OAAA,SACA,IAAAC,IAAA,CAAAD,OAAA,QAEA,IAAAE,OAAA,CAAAF,OAAA,WAMA,IAAAG,YAAA,CAAAC,sBAAA,CAAAJ,OAAA,iBACA,IAAAK,aAAA,CAAAD,sBAAA,CAAAJ,OAAA,mBACA,IAAAM,MAAA,CAAAF,sBAAA,CAAAJ,OAAA,uBACA,IAAAO,QAAA,CAAAH,sBAAA,CAAAJ,OAAA,aACA,IAAAQ,aAAA,CAAAJ,sBAAA,CAAAJ,OAAA,mBACA,IAAAS,OAAA,CAAAL,sBAAA,CAAAJ,OAAA,YACA,IAAAU,OAAA,CAAAN,sBAAA,CAAAJ,OAAA,YACA,IAAAW,UAAA,CAAAP,sBAAA,CAAAJ,OAAA,gBACA,IAAAY,KAAA,CAAAZ,OAAA,SAEA,IAAAa,SAAA,CAAAT,sBAAA,CAAAJ,OAAA,gBAEA,IAAAc,OAAA,CAAAd,OAAA,mBAzBA;AACA;AACA,GAFA,CAgCA;AACA;AACA;AACA,GACA,KA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G,CAAEC,GAAG,CAAEC,IAAI,GAAK,CAC7BA,IAAI,CAAC,GAAAuD,gBAAQ,EAACC,cAAM,CAACC,SAAS,CAAEC,aAAK,CAACD,SAAS,CAAC,CAClD,CAAC,CAAC,CAEF,GAAI,CAAAE,6BAA6B,CACjC,GAAI1E,OAAO,CAAC2E,oBAAoB,CAAE,CAChCD,6BAA6B,CAAG,KAAM,CAAA1E,OAAO,CAAC2E,oBAAoB,CAACpE,MAAM,CAC3E,CAEA,oBACA,GAAI,CAACmE,6BAA6B,CAAE,CAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAnE,MAAM,CAACK,GAAG,CAAC,CAACgE,KAAK,CAAE/D,GAAG,CAAEC,GAAG,CAAEC,IAAI,GAAK,CACpC;AACA;AACA,GAAID,GAAG,CAAC+D,WAAW,CAAE,MAAO,CAAA9D,IAAI,CAAC6D,KAAK,CAAC,CAEvC,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAIL,aAAK,CAACM,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAIL,aAAK,CAACM,qBAAqB,CAExD;AACA/E,OAAO,CAACU,MAAM,CAACuE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAAC,CAEzD,GAAI,CAAAM,OAAO,CAAGN,KAAK,CAACM,OAAO,EAAI,GAAAC,uBAAe,EAACL,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAInB,OAAO,CAACuB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDH,OAAO,CAAGX,cAAM,CAACQ,qBACnB,CAEAjE,GAAG,CAACgE,MAAM,CAACA,MAAM,CAAC,CAAC7C,IAAI,CAACiD,OAAO,CAAC,CAChC,MAAO,CAAAI,SACT,CAAC,CACH,CAEA,MAAO,CAAA/E,MACT"}
1
+ {"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV","undefined"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\nimport { type Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\ntype ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?: (server: ServerT) => Promise<boolean>;\n beforeExpressJsSetup?: (server: ServerT) => Promise<void>;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n) {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path || '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: any,\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) return next(error);\n\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n return undefined;\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,IAAAA,KAAA,CAAAC,OAAA,SACA,IAAAC,IAAA,CAAAD,OAAA,QAEA,IAAAE,OAAA,CAAAF,OAAA,WAMA,IAAAG,YAAA,CAAAC,sBAAA,CAAAJ,OAAA,iBACA,IAAAK,aAAA,CAAAD,sBAAA,CAAAJ,OAAA,mBACA,IAAAM,MAAA,CAAAF,sBAAA,CAAAJ,OAAA,uBAEA,IAAAO,QAAA,CAAAH,sBAAA,CAAAJ,OAAA,aAOA,IAAAQ,aAAA,CAAAJ,sBAAA,CAAAJ,OAAA,mBACA,IAAAS,OAAA,CAAAL,sBAAA,CAAAJ,OAAA,YACA,IAAAU,OAAA,CAAAN,sBAAA,CAAAJ,OAAA,YACA,IAAAW,UAAA,CAAAP,sBAAA,CAAAJ,OAAA,gBACA,IAAAY,KAAA,CAAAZ,OAAA,SACAA,OAAA,YAEA,IAAAa,SAAA,CAAAT,sBAAA,CAAAJ,OAAA,gBAKA,IAAAc,OAAA,CAAAd,OAAA,mBApCA;AACA;AACA,GAFA,CAmDA;AACA;AACA;AACA,GACA,KAAM,CAA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AAhF,MACT"}
@@ -50,7 +50,8 @@
50
50
  * const requestBodySchema = joi.object({
51
51
  * sampleKey: joi.string().max(16).required(),
52
52
  * });
53
- */ /**
53
+ */ // TODO: It could accept the status code as a constructor argument.
54
+ class ErrorWithStatus extends Error{status=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR}/**
54
55
  * ```js
55
56
  * import { server } from '@dr.pogodin/react-utils';
56
57
  * const { newError } = server.errors;
@@ -61,16 +62,15 @@
61
62
  * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal
62
63
  * Server Error).
63
64
  * @return {Error}
64
- */function newError(message,statusCode=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR){const error=new Error(message);error.status=statusCode;return error}/**
65
+ */function newError(message,statusCode=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR){const error=new ErrorWithStatus(message);error.status=statusCode;return error}/**
65
66
  * ```js
66
67
  * import { server } from '@dr.pogodin/react-utils';
67
68
  * const { fail } = server.errors;
68
69
  * ```
69
70
  * Throws an error with given message and HTTP status code.
70
- * @param {string} message Error message.
71
- * @param {number} [statusCode=500] HTTP error code. Defaults to 500 (Internal
71
+ * @param message Error message.
72
+ * @param [statusCode=500] HTTP error code. Defaults to 500 (Internal
72
73
  * Server Error).
73
- * @throws {Error}
74
74
  */function fail(message,statusCode=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR){throw newError(message,statusCode)}/**
75
75
  * ```js
76
76
  * import { server } from '@dr.pogodin/react-utils';
@@ -78,11 +78,10 @@
78
78
  * ```
79
79
  * Validates a value using given Joi schema, and throws an error with given
80
80
  * message and HTTP status code in case of the validation failure.
81
- * @param {any} value
82
- * @param {object} schema
83
- * @param {string} [message] Error message.
84
- * @param {number} [statusCode=500] HTTP status code. Defaults to 400 (Bad
81
+ * @param value
82
+ * @param schema
83
+ * @param [message] Error message.
84
+ * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad
85
85
  * Request).
86
- * @throws {Error}
87
86
  */function assert(value,schema,message="",statusCode=_httpStatusCodes.StatusCodes.BAD_REQUEST){const{error}=schema.validate(value,{abortEarly:false});if(error){fail(message.concat(message?"\n":"",error.message),statusCode)}}
88
87
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","newError","message","statusCode","CODES","INTERNAL_SERVER_ERROR","error","Error","status","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.js"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new Error(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n * @throws {Error}\n */\nexport function fail(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param {any} value\n * @param {object} schema\n * @param {string} [message] Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n * @throws {Error}\n */\nexport function assert(\n value,\n schema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":"8oBAWA,IAAAA,gBAAA,CAAAC,OAAA,sBAMA,IAAAC,IAAA,CAAAC,sBAAA,CAAAF,OAAA,SAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GATA,CAmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAVA,CAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAVA,CAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAXA,CAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAZA,CAeA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAG,QAAQA,CAACC,OAAO,CAAEC,UAAU,CAAGC,4BAAK,CAACC,qBAAqB,CAAE,CAC1E,KAAM,CAAAC,KAAK,CAAG,GAAI,CAAAC,KAAK,CAACL,OAAO,CAAC,CAChCI,KAAK,CAACE,MAAM,CAAGL,UAAU,CACzB,MAAO,CAAAG,KACT,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAG,IAAIA,CAACP,OAAO,CAAEC,UAAU,CAAGC,4BAAK,CAACC,qBAAqB,CAAE,CACtE,KAAM,CAAAJ,QAAQ,CAACC,OAAO,CAAEC,UAAU,CACpC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAO,MAAMA,CACpBC,KAAK,CACLC,MAAM,CACNV,OAAO,CAAG,EAAE,CACZC,UAAU,CAAGC,4BAAK,CAACS,WAAW,CAC9B,CACA,KAAM,CAAEP,KAAM,CAAC,CAAGM,MAAM,CAACE,QAAQ,CAACH,KAAK,CAAE,CAAEI,UAAU,CAAE,KAAM,CAAC,CAAC,CAC/D,GAAIT,KAAK,CAAE,CACTG,IAAI,CAACP,OAAO,CAACc,MAAM,CAACd,OAAO,CAAG,IAAI,CAAG,EAAE,CAAEI,KAAK,CAACJ,OAAO,CAAC,CAAEC,UAAU,CACrE,CACF"}
1
+ {"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","ErrorWithStatus","Error","status","CODES","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param message Error message.\n * @param [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n */\nexport function fail(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param value\n * @param schema\n * @param [message] Error message.\n * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n */\nexport function assert(\n value: any,\n schema: joi.AnySchema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":"8oBAWA,IAAAA,gBAAA,CAAAC,OAAA,sBAMA,IAAAC,IAAA,CAAAC,sBAAA,CAAAF,OAAA,SAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GATA,CAmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAVA,CAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAVA,CAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAXA,CAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAZA,CAeA;AACA,KAAM,CAAAG,eAAe,QAAS,CAAAC,KAAM,CAClCC,MAAM,CAAWC,4BAAK,CAACC,qBACzB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAC,QAAQA,CAACC,OAAe,CAAEC,UAAU,CAAGJ,4BAAK,CAACC,qBAAqB,CAAE,CAClF,KAAM,CAAAI,KAAK,CAAG,GAAI,CAAAR,eAAe,CAACM,OAAO,CAAC,CAC1CE,KAAK,CAACN,MAAM,CAAGK,UAAU,CACzB,MAAO,CAAAC,KACT,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAC,IAAIA,CAACH,OAAe,CAAEC,UAAU,CAAGJ,4BAAK,CAACC,qBAAqB,CAAE,CAC9E,KAAM,CAAAC,QAAQ,CAACC,OAAO,CAAEC,UAAU,CACpC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAG,MAAMA,CACpBC,KAAU,CACVC,MAAqB,CACrBN,OAAO,CAAG,EAAE,CACZC,UAAU,CAAGJ,4BAAK,CAACU,WAAW,CAC9B,CACA,KAAM,CAAEL,KAAM,CAAC,CAAGI,MAAM,CAACE,QAAQ,CAACH,KAAK,CAAE,CAAEI,UAAU,CAAE,KAAM,CAAC,CAAC,CAC/D,GAAIP,KAAK,CAAE,CACTC,IAAI,CAACH,OAAO,CAACU,MAAM,CAACV,OAAO,CAAG,IAAI,CAAG,EAAE,CAAEE,KAAK,CAACF,OAAO,CAAC,CAAEC,UAAU,CACrE,CACF"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.errors=void 0;var _errors=_interopRequireWildcard(require("./errors"));exports.errors=_errors;function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.errors=void 0;var _errors=_interopRequireWildcard(require("./errors"));exports.errors=_errors;function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/server/utils/index.js"],"sourcesContent":["// Aggregates utility modules together.\n\nexport * as errors from './errors';\n"],"mappings":""}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/server/utils/index.ts"],"sourcesContent":["// Aggregates utility modules together.\n\nexport * as errors from './errors';\n"],"mappings":""}
@@ -1,11 +1,11 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _Link=_interopRequireDefault(require("../Link"));var _utils=require("../../utils");var _jsxRuntime=require("react/jsx-runtime");// The <Button> component implements a standard button / button-like link.
2
- const defaultTheme={"context":"KM0v4f","ad":"_3jm1-Q","hoc":"_0plpDL","button":"E1FNQT","active":"MAe9O6","disabled":"Br9IWV"};function BaseButton({active,children,disabled,enforceA,onClick,onMouseDown,openNewTab,replace,theme,to}){let className=theme.button;if(active&&theme.active)className+=` ${theme.active}`;if(disabled){if(theme.disabled)className+=` ${theme.disabled}`;return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:className,children:children})}if(to){return/*#__PURE__*/(0,_jsxRuntime.jsx)(_Link.default,{className:className,enforceA:enforceA,onClick:onClick,onMouseDown:onMouseDown,openNewTab:openNewTab,replace:replace,to:to,children:children})}return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:className,onClick:onClick,onKeyDown:onClick,onMouseDown:onMouseDown,role:"button",tabIndex:0,children:children})}/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));require("react");var _Link=_interopRequireDefault(require("../Link"));var _reactThemes=_interopRequireDefault(require("@dr.pogodin/react-themes"));var _jsxRuntime=require("react/jsx-runtime");// The <Button> component implements a standard button / button-like link.
2
+ const defaultTheme={"context":"KM0v4f","ad":"_3jm1-Q","hoc":"_0plpDL","button":"E1FNQT","active":"MAe9O6","disabled":"Br9IWV"};/* eslint-disable react/function-component-definition */const BaseButton=({active,children,disabled,enforceA,onClick,onMouseDown,openNewTab,replace,theme,to})=>{let className=theme.button;if(active&&theme.active)className+=` ${theme.active}`;if(disabled){if(theme.disabled)className+=` ${theme.disabled}`;return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:className,children:children})}if(to){return/*#__PURE__*/(0,_jsxRuntime.jsx)(_Link.default,{className:className,enforceA:enforceA,onClick:onClick,onMouseDown:onMouseDown,openNewTab:openNewTab,replace:replace,to:to,children:children})}return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:className,onClick:onClick,onKeyDown:onClick,onMouseDown:onMouseDown,role:"button",tabIndex:0,children:children})};/**
3
3
  * Button component theme: a map of CSS
4
4
  * class names to append to button elements:
5
5
  * @prop {string} [active] to the root element of active button.
6
6
  * @prop {string} [button] to the root element of any button.
7
7
  * @prop {string} [disabled] to the root element of disabled button.
8
- */const ThemedButton=(0,_utils.themed)("Button",["active","button","disabled"],defaultTheme)(BaseButton);/**
8
+ */const ThemedButton=(0,_reactThemes.default)(BaseButton,"Button",["active","button","disabled"],defaultTheme);/**
9
9
  * Implements themeable buttons, and button-line links (elements which look
10
10
  * like buttons, but behave as links) in the same uniform manner.
11
11
  * @param {object} [props] Component props.
@@ -30,5 +30,5 @@ const defaultTheme={"context":"KM0v4f","ad":"_3jm1-Q","hoc":"_0plpDL","button":"
30
30
  * or URL.
31
31
  * @param {...any} [props....]
32
32
  * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
33
- */BaseButton.defaultProps={active:false,children:undefined,disabled:false,enforceA:false,onClick:undefined,onMouseDown:undefined,openNewTab:false,replace:false,to:undefined};BaseButton.propTypes={active:_propTypes.default.bool,children:_propTypes.default.node,disabled:_propTypes.default.bool,enforceA:_propTypes.default.bool,onClick:_propTypes.default.func,onMouseDown:_propTypes.default.func,openNewTab:_propTypes.default.bool,replace:_propTypes.default.bool,theme:ThemedButton.themeType.isRequired,to:_propTypes.default.oneOfType([_propTypes.default.object,_propTypes.default.string])};var _default=ThemedButton;exports.default=_default;
33
+ */BaseButton.defaultProps={active:false,children:undefined,disabled:false,enforceA:false,onClick:undefined,onMouseDown:undefined,openNewTab:false,replace:false,to:undefined};BaseButton.propTypes={active:_propTypes.default.bool,children:_propTypes.default.node,disabled:_propTypes.default.bool,enforceA:_propTypes.default.bool,onClick:_propTypes.default.func,onMouseDown:_propTypes.default.func,openNewTab:_propTypes.default.bool,replace:_propTypes.default.bool,theme:ThemedButton.themeType.isRequired,to:_propTypes.default.oneOfType([_propTypes.default.object,_propTypes.default.string])};var _default=exports.default=ThemedButton;
34
34
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_Link","_utils","_jsxRuntime","defaultTheme","BaseButton","active","children","disabled","enforceA","onClick","onMouseDown","openNewTab","replace","theme","to","className","button","jsx","default","onKeyDown","role","tabIndex","ThemedButton","themed","defaultProps","undefined","propTypes","PT","bool","node","func","themeType","isRequired","oneOfType","object","string","_default","exports"],"sources":["../../../../../src/shared/components/Button/index.jsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport PT from 'prop-types';\n\nimport Link from 'components/Link';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './style.scss';\n\nfunction BaseButton({\n active,\n children,\n disabled,\n enforceA,\n onClick,\n onMouseDown,\n openNewTab,\n replace,\n theme,\n to,\n}) {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div className={className}>\n {children}\n </div>\n );\n }\n if (to) {\n return (\n <Link\n className={className}\n enforceA={enforceA}\n onClick={onClick}\n onMouseDown={onMouseDown}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n return (\n <div\n className={className}\n onClick={onClick}\n onKeyDown={onClick}\n onMouseDown={onMouseDown}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n}\n\n/**\n * Button component theme: a map of CSS\n * class names to append to button elements:\n * @prop {string} [active] to the root element of active button.\n * @prop {string} [button] to the root element of any button.\n * @prop {string} [disabled] to the root element of disabled button.\n */\nconst ThemedButton = themed('Button', [\n 'active',\n 'button',\n 'disabled',\n], defaultTheme)(BaseButton);\n\n/**\n * Implements themeable buttons, and button-line links (elements which look\n * like buttons, but behave as links) in the same uniform manner.\n * @param {object} [props] Component props.\n * @param {boolean} [props.active] Set `true` to render the button as\n * active, even if it is not active otherwise.\n * @param {boolean} [props.disabled] Set `true` to disable the button.\n * @param {boolean} [props.enforceA] When the button is rendered as `<Link>`\n * component, this prop enforces it to be rendered as a simple `<a>` element\n * (external link), rather than the React router's internal link.\n * See `<Link>` documentation to learn when links are rendered as `<a>`\n * by default.\n * @param {function} [props.onClick] Click event handler.\n * @param {function} [props.onMouseDown] Mouse down event handler.\n * @param {boolean} [props.openNewTab] Set `true` to open link in the new tab.\n * @param {boolean} [props.replace] When the button is rendered as\n * `<Link>`, and the target URL is internal, this property tells that\n * the new route should replace the last record in the browser's history,\n * rather than to be pushed as a new entry into the history stack.\n * @param {ButtonTheme} [props.theme] _Ad hoc_ button theme.\n * @param {object|string} [props.to] If specified, the button will be rendered\n * as `<Link>` (if not disabled), and it will point to the specified location\n * or URL.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nBaseButton.defaultProps = {\n active: false,\n children: undefined,\n disabled: false,\n enforceA: false,\n onClick: undefined,\n onMouseDown: undefined,\n openNewTab: false,\n replace: false,\n to: undefined,\n};\n\nBaseButton.propTypes = {\n active: PT.bool,\n children: PT.node,\n disabled: PT.bool,\n enforceA: PT.bool,\n onClick: PT.func,\n onMouseDown: PT.func,\n openNewTab: PT.bool,\n replace: PT.bool,\n theme: ThemedButton.themeType.isRequired,\n to: P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Ead,YAAY,CAAAe,OAAA,CAAAnB,OAAA,CAAAkB,QAAA"}
1
+ {"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_Link","_reactThemes","_jsxRuntime","defaultTheme","BaseButton","active","children","disabled","enforceA","onClick","onMouseDown","openNewTab","replace","theme","to","className","button","jsx","default","onKeyDown","role","tabIndex","ThemedButton","themed","defaultProps","undefined","propTypes","PT","bool","node","func","themeType","isRequired","oneOfType","object","string","_default","exports"],"sources":["../../../../../src/shared/components/Button/index.tsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport PT from 'prop-types';\nimport { type ReactNode } from 'react';\n\nimport Link from 'components/Link';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './style.scss';\n\ntype PropsT = {\n active?: boolean;\n children?: ReactNode;\n disabled?: boolean;\n enforceA?: boolean;\n onClick?: React.MouseEventHandler & React.KeyboardEventHandler;\n onMouseDown?: React.MouseEventHandler;\n openNewTab?: boolean;\n replace?: boolean;\n theme: Theme & {\n active?: string;\n button?: string;\n disabled?: string;\n };\n // TODO: It needs a more precise typing of the object option.\n to?: object | string;\n};\n\n/* eslint-disable react/function-component-definition */\nconst BaseButton: React.FunctionComponent<PropsT> = ({\n active,\n children,\n disabled,\n enforceA,\n onClick,\n onMouseDown,\n openNewTab,\n replace,\n theme,\n to,\n}) => {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div className={className}>\n {children}\n </div>\n );\n }\n if (to) {\n return (\n <Link\n className={className}\n enforceA={enforceA}\n onClick={onClick}\n onMouseDown={onMouseDown}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n return (\n <div\n className={className}\n onClick={onClick}\n onKeyDown={onClick}\n onMouseDown={onMouseDown}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n};\n\n/**\n * Button component theme: a map of CSS\n * class names to append to button elements:\n * @prop {string} [active] to the root element of active button.\n * @prop {string} [button] to the root element of any button.\n * @prop {string} [disabled] to the root element of disabled button.\n */\nconst ThemedButton = themed(BaseButton, 'Button', [\n 'active',\n 'button',\n 'disabled',\n], defaultTheme);\n\n/**\n * Implements themeable buttons, and button-line links (elements which look\n * like buttons, but behave as links) in the same uniform manner.\n * @param {object} [props] Component props.\n * @param {boolean} [props.active] Set `true` to render the button as\n * active, even if it is not active otherwise.\n * @param {boolean} [props.disabled] Set `true` to disable the button.\n * @param {boolean} [props.enforceA] When the button is rendered as `<Link>`\n * component, this prop enforces it to be rendered as a simple `<a>` element\n * (external link), rather than the React router's internal link.\n * See `<Link>` documentation to learn when links are rendered as `<a>`\n * by default.\n * @param {function} [props.onClick] Click event handler.\n * @param {function} [props.onMouseDown] Mouse down event handler.\n * @param {boolean} [props.openNewTab] Set `true` to open link in the new tab.\n * @param {boolean} [props.replace] When the button is rendered as\n * `<Link>`, and the target URL is internal, this property tells that\n * the new route should replace the last record in the browser's history,\n * rather than to be pushed as a new entry into the history stack.\n * @param {ButtonTheme} [props.theme] _Ad hoc_ button theme.\n * @param {object|string} [props.to] If specified, the button will be rendered\n * as `<Link>` (if not disabled), and it will point to the specified location\n * or URL.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nBaseButton.defaultProps = {\n active: false,\n children: undefined,\n disabled: false,\n enforceA: false,\n onClick: undefined,\n onMouseDown: undefined,\n openNewTab: false,\n replace: false,\n to: undefined,\n};\n\nBaseButton.propTypes = {\n active: PT.bool,\n children: PT.node,\n disabled: PT.bool,\n enforceA: PT.bool,\n onClick: PT.func,\n onMouseDown: PT.func,\n openNewTab: PT.bool,\n replace: PT.bool,\n theme: ThemedButton.themeType.isRequired,\n to: PT.oneOfType([PT.object, PT.string]),\n};\n\nexport default ThemedButton;\n"],"mappings":"gLAEA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,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@@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _utils=require("../../utils");var _jsxRuntime=require("react/jsx-runtime");const defaultTheme={"context":"dNQcC6","ad":"earXxa","hoc":"qAPfQ6","checkbox":"A-f8qJ","container":"Kr0g3M","label":"_3dML-O"};function Checkbox({checked,label,onChange,theme}){return/*#__PURE__*/(0,_jsxRuntime.jsxs)("div",{className:theme.container,children:[label===undefined?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("p",{className:theme.label,children:label}),/*#__PURE__*/(0,_jsxRuntime.jsx)("input",{checked:checked,className:theme.checkbox,onChange:onChange,type:"checkbox"})]})}/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _reactThemes=_interopRequireDefault(require("@dr.pogodin/react-themes"));var _jsxRuntime=require("react/jsx-runtime");const defaultTheme={"context":"dNQcC6","ad":"earXxa","hoc":"qAPfQ6","checkbox":"A-f8qJ","container":"Kr0g3M","label":"_3dML-O"};const Checkbox=({checked,label,onChange,theme})=>/*#__PURE__*/(0,_jsxRuntime.jsxs)("div",{className:theme.container,children:[label===undefined?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("p",{className:theme.label,children:label}),/*#__PURE__*/(0,_jsxRuntime.jsx)("input",{checked:checked,className:theme.checkbox,onChange:onChange,type:"checkbox"})]});/**
2
2
  * Checkbox component theme: a map of
3
3
  * CSS classes to append to its elements:
4
- * @prop {string} [checkbox] to the underlying checkbox `<input>` element.
5
- * @prop {string} [container] to the root checkbox element.
6
- * @prop {string} [label] to the checkbox label element.
7
- */const ThemedCheckbox=(0,_utils.themed)("Checkbox",["checkbox","container","label"],defaultTheme)(Checkbox);/**
4
+ * @prop [checkbox] to the underlying checkbox `<input>` element.
5
+ * @prop [container] to the root checkbox element.
6
+ * @prop [label] to the checkbox label element.
7
+ */const ThemedCheckbox=(0,_reactThemes.default)(Checkbox,"Checkbox",["checkbox","container","label"],defaultTheme);/**
8
8
  * The `<Checkbox>` component implements themeable checkboxes.
9
- * @param {object} [props] Component properties.
10
- * @param {boolean} [props.checked] Checkbox value.
11
- * @param {string} [props.label] Checkbox label.
12
- * @param {function} [props.onChange] State change handler.
13
- * @param {CheckboxTheme} [props.theme] _Ad hoc_ theme.
14
- * @param {...any} [props....]
9
+ * @param [props] Component properties.
10
+ * @param [props.checked] Checkbox value.
11
+ * @param [props.label] Checkbox label.
12
+ * @param [props.onChange] State change handler.
13
+ * @param [props.theme] _Ad hoc_ theme.
14
+ * @param [props....]
15
15
  * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties).
16
- */Checkbox.propTypes={checked:_propTypes.default.bool,label:_propTypes.default.string,onChange:_propTypes.default.func,theme:ThemedCheckbox.themeType.isRequired};Checkbox.defaultProps={checked:undefined,label:undefined,onChange:undefined};var _default=ThemedCheckbox;exports.default=_default;
16
+ */Checkbox.propTypes={checked:_propTypes.default.bool,label:_propTypes.default.string,onChange:_propTypes.default.func,theme:ThemedCheckbox.themeType.isRequired};Checkbox.defaultProps={checked:undefined,label:undefined,onChange:undefined};var _default=exports.default=ThemedCheckbox;
17
17
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_utils","_jsxRuntime","defaultTheme","Checkbox","checked","label","onChange","theme","jsxs","className","container","children","undefined","jsx","checkbox","type","ThemedCheckbox","themed","propTypes","PT","bool","string","func","themeType","isRequired","defaultProps","_default","exports","default"],"sources":["../../../../../src/shared/components/Checkbox/index.jsx"],"sourcesContent":["import PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\nfunction Checkbox({\n checked,\n label,\n onChange,\n theme,\n}) {\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <input\n checked={checked}\n className={theme.checkbox}\n onChange={onChange}\n type=\"checkbox\"\n />\n </div>\n );\n}\n\n/**\n * Checkbox component theme: a map of\n * CSS classes to append to its elements:\n * @prop {string} [checkbox] to the underlying checkbox `<input>` element.\n * @prop {string} [container] to the root checkbox element.\n * @prop {string} [label] to the checkbox label element.\n */\nconst ThemedCheckbox = themed('Checkbox', [\n 'checkbox',\n 'container',\n 'label',\n], defaultTheme)(Checkbox);\n\n/**\n * The `<Checkbox>` component implements themeable checkboxes.\n * @param {object} [props] Component properties.\n * @param {boolean} [props.checked] Checkbox value.\n * @param {string} [props.label] Checkbox label.\n * @param {function} [props.onChange] State change handler.\n * @param {CheckboxTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties).\n */\nCheckbox.propTypes = {\n checked: PT.bool,\n label: PT.string,\n onChange: PT.func,\n theme: ThemedCheckbox.themeType.isRequired,\n};\n\nCheckbox.defaultProps = {\n checked: undefined,\n label: undefined,\n onChange: undefined,\n};\n\nexport default ThemedCheckbox;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBAEA,IAAAC,MAAA,CAAAD,OAAA,gBAA+B,IAAAE,WAAA,CAAAF,OAAA,4BAAAG,YAAA,8GAI/B,QAAS,CAAAC,QAAQA,CAAC,CAChBC,OAAO,CACPC,KAAK,CACLC,QAAQ,CACRC,KACF,CAAC,CAAE,CACD,mBACE,GAAAN,WAAA,CAAAO,IAAA,SAAKC,SAAS,CAAEF,KAAK,CAACG,SAAU,CAAAC,QAAA,EAC5BN,KAAK,GAAKO,SAAS,CAAG,IAAI,cAAG,GAAAX,WAAA,CAAAY,GAAA,OAAGJ,SAAS,CAAEF,KAAK,CAACF,KAAM,CAAAM,QAAA,CAAEN,KAAK,CAAI,CAAC,cACrE,GAAAJ,WAAA,CAAAY,GAAA,WACET,OAAO,CAAEA,OAAQ,CACjBK,SAAS,CAAEF,KAAK,CAACO,QAAS,CAC1BR,QAAQ,CAAEA,QAAS,CACnBS,IAAI,CAAC,UAAU,CAChB,CAAC,EACC,CAET,CAEA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,cAAc,CAAG,GAAAC,aAAM,EAAC,UAAU,CAAE,CACxC,UAAU,CACV,WAAW,CACX,OAAO,CACR,CAAEf,YAAY,CAAC,CAACC,QAAQ,CAAC,CAE1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAA,QAAQ,CAACe,SAAS,CAAG,CACnBd,OAAO,CAAEe,kBAAE,CAACC,IAAI,CAChBf,KAAK,CAAEc,kBAAE,CAACE,MAAM,CAChBf,QAAQ,CAAEa,kBAAE,CAACG,IAAI,CACjBf,KAAK,CAAES,cAAc,CAACO,SAAS,CAACC,UAClC,CAAC,CAEDrB,QAAQ,CAACsB,YAAY,CAAG,CACtBrB,OAAO,CAAEQ,SAAS,CAClBP,KAAK,CAAEO,SAAS,CAChBN,QAAQ,CAAEM,SACZ,CAAC,CAAC,IAAAc,QAAA,CAEaV,cAAc,CAAAW,OAAA,CAAAC,OAAA,CAAAF,QAAA"}
1
+ {"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_reactThemes","_jsxRuntime","defaultTheme","Checkbox","checked","label","onChange","theme","jsxs","className","container","children","undefined","jsx","checkbox","type","ThemedCheckbox","themed","propTypes","PT","bool","string","func","themeType","isRequired","defaultProps","_default","exports","default"],"sources":["../../../../../src/shared/components/Checkbox/index.tsx"],"sourcesContent":["import PT from 'prop-types';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype PropT = {\n checked?: boolean;\n label?: string;\n onChange?: React.ChangeEventHandler<HTMLInputElement>;\n theme: Theme & {\n checkbox?: string;\n container?: string\n label?: string;\n };\n};\n\nconst Checkbox: React.FunctionComponent<PropT> = ({\n checked,\n label,\n onChange,\n theme,\n}) => (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <input\n checked={checked}\n className={theme.checkbox}\n onChange={onChange}\n type=\"checkbox\"\n />\n </div>\n);\n\n/**\n * Checkbox component theme: a map of\n * CSS classes to append to its elements:\n * @prop [checkbox] to the underlying checkbox `<input>` element.\n * @prop [container] to the root checkbox element.\n * @prop [label] to the checkbox label element.\n */\nconst ThemedCheckbox = themed(Checkbox, 'Checkbox', [\n 'checkbox',\n 'container',\n 'label',\n], defaultTheme);\n\n/**\n * The `<Checkbox>` component implements themeable checkboxes.\n * @param [props] Component properties.\n * @param [props.checked] Checkbox value.\n * @param [props.label] Checkbox label.\n * @param [props.onChange] State change handler.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties).\n */\nCheckbox.propTypes = {\n checked: PT.bool,\n label: PT.string,\n onChange: PT.func,\n theme: ThemedCheckbox.themeType.isRequired,\n};\n\nCheckbox.defaultProps = {\n checked: undefined,\n label: undefined,\n onChange: undefined,\n};\n\nexport default ThemedCheckbox;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBAEA,IAAAC,YAAA,CAAAF,sBAAA,CAAAC,OAAA,8BAA8D,IAAAE,WAAA,CAAAF,OAAA,4BAAAG,YAAA,8GAe9D,KAAM,CAAAC,QAAwC,CAAGA,CAAC,CAChDC,OAAO,CACPC,KAAK,CACLC,QAAQ,CACRC,KACF,CAAC,gBACC,GAAAN,WAAA,CAAAO,IAAA,SAAKC,SAAS,CAAEF,KAAK,CAACG,SAAU,CAAAC,QAAA,EAC5BN,KAAK,GAAKO,SAAS,CAAG,IAAI,cAAG,GAAAX,WAAA,CAAAY,GAAA,OAAGJ,SAAS,CAAEF,KAAK,CAACF,KAAM,CAAAM,QAAA,CAAEN,KAAK,CAAI,CAAC,cACrE,GAAAJ,WAAA,CAAAY,GAAA,WACET,OAAO,CAAEA,OAAQ,CACjBK,SAAS,CAAEF,KAAK,CAACO,QAAS,CAC1BR,QAAQ,CAAEA,QAAS,CACnBS,IAAI,CAAC,UAAU,CAChB,CAAC,EACC,CACN,CAED;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,cAAc,CAAG,GAAAC,oBAAM,EAACd,QAAQ,CAAE,UAAU,CAAE,CAClD,UAAU,CACV,WAAW,CACX,OAAO,CACR,CAAED,YAAY,CAAC,CAEhB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAC,QAAQ,CAACe,SAAS,CAAG,CACnBd,OAAO,CAAEe,kBAAE,CAACC,IAAI,CAChBf,KAAK,CAAEc,kBAAE,CAACE,MAAM,CAChBf,QAAQ,CAAEa,kBAAE,CAACG,IAAI,CACjBf,KAAK,CAAES,cAAc,CAACO,SAAS,CAACC,UAClC,CAAC,CAEDrB,QAAQ,CAACsB,YAAY,CAAG,CACtBrB,OAAO,CAAEQ,SAAS,CAClBP,KAAK,CAAEO,SAAS,CAChBN,QAAQ,CAAEM,SACZ,CAAC,CAAC,IAAAc,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEaZ,cAAc"}
@@ -1,24 +1,24 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _utils=require("../../utils");var _jsxRuntime=require("react/jsx-runtime");const defaultTheme={"context":"haRIry","ad":"D4XHG2","hoc":"N3nd34","arrow":"-zPK7Y","container":"_9CQpeA","label":"Gv0kyu","option":"xmsujA","hiddenOption":"RdW3yR","select":"JXK1uw"};/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _reactThemes=_interopRequireDefault(require("@dr.pogodin/react-themes"));var _jsxRuntime=require("react/jsx-runtime");const defaultTheme={"context":"haRIry","ad":"D4XHG2","hoc":"N3nd34","arrow":"-zPK7Y","container":"_9CQpeA","label":"Gv0kyu","option":"xmsujA","hiddenOption":"RdW3yR","select":"JXK1uw"};/**
2
2
  * Implements a themeable dropdown list. Internally it is rendered with help of
3
3
  * the standard HTML `<select>` element, thus the styling support is somewhat
4
4
  * limited.
5
- * @param {object} [props] Component properties.
6
- * @param {function} [props.filter] Options filter function. If provided, only
5
+ * @param [props] Component properties.
6
+ * @param [props.filter] Options filter function. If provided, only
7
7
  * those elements of `options` list will be used by the dropdown, for which this
8
8
  * filter returns `true`.
9
- * @param {string} [props.label] Dropdown label.
10
- * @param {string} [props.onChange] Selection event handler.
11
- * @param {DropdownOption[]|string[]} [props.options=[]] Array of dropdown
9
+ * @param [props.label] Dropdown label.
10
+ * @param [props.onChange] Selection event handler.
11
+ * @param [props.options=[]] Array of dropdown
12
12
  * options. For string elements the option value and name will be the same.
13
13
  * It is allowed to mix DropdownOption and string elements in the same option
14
14
  * list.
15
- * @param {DropdownTheme} [props.theme] _Ad hoc_ theme.
16
- * @param {string} [props.value] Currently selected value.
17
- * @param {...any} [props....]
15
+ * @param [props.theme] _Ad hoc_ theme.
16
+ * @param [props.value] Currently selected value.
17
+ * @param [props....]
18
18
  * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
19
- */function Dropdown({filter,label,onChange,options,theme,value}){let isValidValue=false;const optionElements=[];for(let i=0;i<options.length;++i){const option=options[i];if(!filter||filter(option)){const optionValue=typeof option==="string"?option:option.value;const optionName=option.name===undefined?optionValue:option.name;isValidValue||=optionValue===value;optionElements.push(/*#__PURE__*/(0,_jsxRuntime.jsx)("option",{className:theme.option,value:optionValue,children:optionName},optionValue))}}// NOTE: This element represents the current `value` when it does not match
19
+ */const Dropdown=({filter,label,onChange,options=[],theme,value})=>{let isValidValue=false;const optionElements=[];for(let i=0;i<options.length;++i){const option=options[i];if(!filter||filter(option)){let optionValue;let optionName;if(typeof option==="string"){optionName=option;optionValue=option}else{optionName=option.name||option.value;optionValue=option.value}isValidValue||=optionValue===value;optionElements.push(/*#__PURE__*/(0,_jsxRuntime.jsx)("option",{className:theme.option,value:optionValue,children:optionName},optionValue))}}// NOTE: This element represents the current `value` when it does not match
20
20
  // any valid option. In Chrome, and some other browsers, we are able to hide
21
21
  // it from the opened dropdown; in others, e.g. Safari, the best we can do is
22
22
  // to show it as disabled.
23
- const hiddenOption=isValidValue?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("option",{disabled:true,className:theme.hiddenOption,value:value,children:value},"__reactUtilsHiddenOption");return/*#__PURE__*/(0,_jsxRuntime.jsxs)("div",{className:theme.container,children:[label===undefined?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("p",{className:theme.label,children:label}),/*#__PURE__*/(0,_jsxRuntime.jsxs)("select",{className:theme.select,onChange:onChange,value:value,children:[hiddenOption,optionElements]}),/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:theme.arrow,children:"\u25BC"})]})}const ThemedDropdown=(0,_utils.themed)("Dropdown",["arrow","container","hiddenOption","label","option","select"],defaultTheme)(Dropdown);Dropdown.propTypes={filter:_propTypes.default.func,label:_propTypes.default.string,onChange:_propTypes.default.func,options:_propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.shape({name:_propTypes.default.node,value:_propTypes.default.string.isRequired}),_propTypes.default.string]).isRequired),theme:ThemedDropdown.themeType.isRequired,value:_propTypes.default.string};Dropdown.defaultProps={filter:undefined,label:undefined,onChange:undefined,options:[],value:""};var _default=ThemedDropdown;exports.default=_default;
23
+ const hiddenOption=isValidValue?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("option",{disabled:true,className:theme.hiddenOption,value:value,children:value},"__reactUtilsHiddenOption");return/*#__PURE__*/(0,_jsxRuntime.jsxs)("div",{className:theme.container,children:[label===undefined?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("p",{className:theme.label,children:label}),/*#__PURE__*/(0,_jsxRuntime.jsxs)("select",{className:theme.select,onChange:onChange,value:value,children:[hiddenOption,optionElements]}),/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:theme.arrow,children:"\u25BC"})]})};const ThemedDropdown=(0,_reactThemes.default)(Dropdown,"Dropdown",["arrow","container","hiddenOption","label","option","select"],defaultTheme);Dropdown.propTypes={filter:_propTypes.default.func,label:_propTypes.default.string,onChange:_propTypes.default.func,options:_propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.shape({name:_propTypes.default.string,value:_propTypes.default.string.isRequired}),_propTypes.default.string]).isRequired),theme:ThemedDropdown.themeType.isRequired,value:_propTypes.default.string};Dropdown.defaultProps={filter:undefined,label:undefined,onChange:undefined,options:[],value:""};var _default=exports.default=ThemedDropdown;
24
24
  //# sourceMappingURL=index.js.map