@dr.pogodin/react-utils 1.43.25 → 1.43.26

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 (59) hide show
  1. package/bin/build.js +3 -3
  2. package/bin/setup.js +3 -3
  3. package/build/development/server/index.js +4 -4
  4. package/build/development/server/index.js.map +1 -1
  5. package/build/development/server/renderer.js +12 -12
  6. package/build/development/server/renderer.js.map +1 -1
  7. package/build/development/server/server.js +3 -3
  8. package/build/development/server/server.js.map +1 -1
  9. package/build/development/shared/components/Input/index.js.map +1 -1
  10. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  11. package/build/development/shared/components/TextArea/index.js.map +1 -1
  12. package/build/development/shared/components/Throbber/index.js.map +1 -1
  13. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  14. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  15. package/build/development/shared/components/selectors/common.js.map +1 -1
  16. package/build/development/shared/utils/jest/E2eSsrEnv.js +4 -4
  17. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  18. package/build/development/shared/utils/jest/index.js.map +1 -1
  19. package/build/development/shared/utils/webpack.js.map +1 -1
  20. package/build/production/server/index.js +2 -2
  21. package/build/production/server/index.js.map +1 -1
  22. package/build/production/server/renderer.js +7 -7
  23. package/build/production/server/renderer.js.map +1 -1
  24. package/build/production/server/server.js +2 -2
  25. package/build/production/server/server.js.map +1 -1
  26. package/build/production/shared/components/Input/index.js.map +1 -1
  27. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  28. package/build/production/shared/components/TextArea/index.js.map +1 -1
  29. package/build/production/shared/components/Throbber/index.js.map +1 -1
  30. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  31. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  32. package/build/production/shared/components/selectors/common.js.map +1 -1
  33. package/build/production/shared/utils/jest/E2eSsrEnv.js +4 -4
  34. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  35. package/build/production/shared/utils/jest/index.js.map +1 -1
  36. package/build/production/shared/utils/webpack.js.map +1 -1
  37. package/build/production/web.bundle.js +1 -1
  38. package/build/production/web.bundle.js.map +1 -1
  39. package/build/types-code/server/index.d.ts +1 -1
  40. package/config/jest/default.js +1 -1
  41. package/config/webpack/app-base.d.ts +1 -1
  42. package/config/webpack/app-base.js +14 -14
  43. package/config/webpack/lib-base.js +5 -5
  44. package/config/webpack/lib-development.js +2 -2
  45. package/config/webpack/lib-production.js +2 -2
  46. package/package.json +3 -3
  47. package/src/server/index.ts +5 -5
  48. package/src/server/renderer.tsx +8 -6
  49. package/src/server/server.ts +3 -4
  50. package/src/shared/components/Input/index.tsx +1 -4
  51. package/src/shared/components/PageLayout/index.tsx +1 -5
  52. package/src/shared/components/TextArea/index.tsx +1 -5
  53. package/src/shared/components/Throbber/index.tsx +1 -4
  54. package/src/shared/components/WithTooltip/Tooltip.ts +1 -5
  55. package/src/shared/components/selectors/Switch/index.tsx +1 -6
  56. package/src/shared/components/selectors/common.ts +1 -2
  57. package/src/shared/utils/jest/E2eSsrEnv.ts +1 -1
  58. package/src/shared/utils/jest/index.ts +3 -2
  59. package/src/shared/utils/webpack.ts +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_reactThemes","_interopRequireDefault","require","_jsxRuntime","defaultTheme","Throbber","theme","jsxs","className","container","children","jsx","circle","_default","exports","default","themed"],"sources":["../../../../../src/shared/components/Throbber/index.tsx"],"sourcesContent":["import themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT =\n | 'bouncing'\n | 'circle'\n | 'container';\n\ntype PropsT = {\n theme: Theme<ThemeKeyT>;\n};\n\n/**\n * Throbber is an \"action in progress\" indicator, which renders\n * three bouncing circles as a simple pending activity indicator,\n * and can be further themed to a certain degree.\n * @param {object} [props] Component properties.\n * @param {ThrobberTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Throbber: React.FunctionComponent<PropsT> = ({ theme }) => (\n <span className={theme.container}>\n <span className={theme.circle} />\n <span className={theme.circle} />\n <span className={theme.circle} />\n </span>\n);\n\nexport default themed(Throbber, 'Throbber', defaultTheme);\n"],"mappings":";;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAA8D,IAAAC,WAAA,GAAAD,OAAA;AAAA,MAAAE,YAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAa9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,QAAyC,GAAGA,CAAC;EAAEC;AAAM,CAAC,kBAC1D,IAAAH,WAAA,CAAAI,IAAA;EAAMC,SAAS,EAAEF,KAAK,CAACG,SAAU;EAAAC,QAAA,gBAC/B,IAAAP,WAAA,CAAAQ,GAAA;IAAMH,SAAS,EAAEF,KAAK,CAACM;EAAO,CAAE,CAAC,eACjC,IAAAT,WAAA,CAAAQ,GAAA;IAAMH,SAAS,EAAEF,KAAK,CAACM;EAAO,CAAE,CAAC,eACjC,IAAAT,WAAA,CAAAQ,GAAA;IAAMH,SAAS,EAAEF,KAAK,CAACM;EAAO,CAAE,CAAC;AAAA,CAC7B,CACP;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEa,IAAAC,oBAAM,EAACX,QAAQ,EAAE,UAAU,EAAED,YAAY,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_reactThemes","_interopRequireDefault","require","_jsxRuntime","defaultTheme","Throbber","theme","jsxs","className","container","children","jsx","circle","_default","exports","default","themed"],"sources":["../../../../../src/shared/components/Throbber/index.tsx"],"sourcesContent":["import themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'bouncing' | 'circle' | 'container';\n\ntype PropsT = {\n theme: Theme<ThemeKeyT>;\n};\n\n/**\n * Throbber is an \"action in progress\" indicator, which renders\n * three bouncing circles as a simple pending activity indicator,\n * and can be further themed to a certain degree.\n * @param {object} [props] Component properties.\n * @param {ThrobberTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Throbber: React.FunctionComponent<PropsT> = ({ theme }) => (\n <span className={theme.container}>\n <span className={theme.circle} />\n <span className={theme.circle} />\n <span className={theme.circle} />\n </span>\n);\n\nexport default themed(Throbber, 'Throbber', defaultTheme);\n"],"mappings":";;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAA8D,IAAAC,WAAA,GAAAD,OAAA;AAAA,MAAAE,YAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAU9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,QAAyC,GAAGA,CAAC;EAAEC;AAAM,CAAC,kBAC1D,IAAAH,WAAA,CAAAI,IAAA;EAAMC,SAAS,EAAEF,KAAK,CAACG,SAAU;EAAAC,QAAA,gBAC/B,IAAAP,WAAA,CAAAQ,GAAA;IAAMH,SAAS,EAAEF,KAAK,CAACM;EAAO,CAAE,CAAC,eACjC,IAAAT,WAAA,CAAAQ,GAAA;IAAMH,SAAS,EAAEF,KAAK,CAACM;EAAO,CAAE,CAAC,eACjC,IAAAT,WAAA,CAAAQ,GAAA;IAAMH,SAAS,EAAEF,KAAK,CAACM;EAAO,CAAE,CAAC;AAAA,CAC7B,CACP;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEa,IAAAC,oBAAM,EAACX,QAAQ,EAAE,UAAU,EAAED,YAAY,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"Tooltip.js","names":["_react","require","_reactDom","PLACEMENTS","exports","ARROW_STYLE_DOWN","join","ARROW_STYLE_UP","createTooltipComponents","theme","arrow","document","createElement","setAttribute","content","container","appendChild","body","calcTooltipRects","tooltip","getBoundingClientRect","calcViewportRect","scrollX","scrollY","window","documentElement","clientHeight","clientWidth","bottom","left","right","top","calcPositionAboveXY","x","y","tooltipRects","arrowX","width","arrowY","height","containerX","containerY","baseArrowStyle","setComponentPositions","pageX","pageY","placement","element","viewportRect","pos","Math","max","maxX","min","containerStyle","arrowStyle","Tooltip","children","ref","current","heap","useRef","lastElement","undefined","lastPageX","lastPageY","lastPlacement","components","setComponents","useState","pointTo","useImperativeHandle","useEffect","removeChild","createPortal","_default","default"],"sources":["../../../../../src/shared/components/WithTooltip/Tooltip.ts"],"sourcesContent":["/**\n * The actual tooltip component. It is rendered outside the regular document\n * hierarchy, and with sub-components managed without React to achieve the best\n * performance during animation.\n */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\n/**\n * Valid placements of the rendered tooltip. They will be overriden when\n * necessary to fit the tooltip within the viewport.\n */\nexport enum PLACEMENTS {\n ABOVE_CURSOR = 'ABOVE_CURSOR',\n ABOVE_ELEMENT = 'ABOVE_ELEMENT',\n BELOW_CURSOR = 'BELOW_CURSOR',\n BELOW_ELEMENT = 'BELOW_ELEMENT',\n}\n\nconst ARROW_STYLE_DOWN = [\n 'border-bottom-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\nconst ARROW_STYLE_UP = [\n 'border-top-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\ntype ComponentsT = {\n container: HTMLDivElement;\n arrow: HTMLDivElement;\n content: HTMLDivElement;\n};\n\ntype HeapT = {\n lastElement?: HTMLElement;\n lastPageX: number;\n lastPageY: number;\n lastPlacement?: PLACEMENTS | undefined;\n};\n\nexport type ThemeKeysT =\n | 'appearance'\n | 'arrow'\n | 'content'\n | 'container';\n\ntype TooltipThemeT = Theme<ThemeKeysT>;\n\n/**\n * Creates tooltip components.\n * @ignore\n * @param {object} theme Themes to use for tooltip container, arrow,\n * and content.\n * @return {object} Object with DOM references to the container components:\n * container, arrow, content.\n */\nfunction createTooltipComponents(theme: TooltipThemeT): ComponentsT {\n const arrow = document.createElement('div');\n if (theme.arrow) arrow.setAttribute('class', theme.arrow);\n\n const content = document.createElement('div');\n if (theme.content) content.setAttribute('class', theme.content);\n\n const container = document.createElement('div');\n if (theme.container) container.setAttribute('class', theme.container);\n\n container.appendChild(arrow);\n container.appendChild(content);\n document.body.appendChild(container);\n\n return { arrow, container, content };\n}\n\ntype TooltipRectsT = {\n arrow: DOMRect;\n container: DOMRect;\n};\n\n/**\n * Generates bounding client rectangles for tooltip components.\n * @ignore\n * @param tooltip DOM references to the tooltip components.\n * @param tooltip.arrow\n * @param tooltip.container\n * @return Object holding tooltip rectangles in\n * two fields.\n */\nfunction calcTooltipRects(tooltip: ComponentsT): TooltipRectsT {\n return {\n arrow: tooltip.arrow.getBoundingClientRect(),\n container: tooltip.container.getBoundingClientRect(),\n };\n}\n\n/**\n * Calculates the document viewport size.\n * @ignore\n * @return {{x, y, width, height}}\n */\nfunction calcViewportRect() {\n const { scrollX, scrollY } = window;\n const { documentElement: { clientHeight, clientWidth } } = document;\n return {\n bottom: scrollY + clientHeight,\n left: scrollX,\n right: scrollX + clientWidth,\n top: scrollY,\n };\n}\n\n/**\n * Calculates tooltip and arrow positions for the placement just above\n * the cursor.\n * @ignore\n * @param {number} x Cursor page-x position.\n * @param {number} y Cursor page-y position.\n * @param {object} tooltipRects Bounding client rectangles of tooltip parts.\n * @param {object} tooltipRects.arrow\n * @param {object} tooltipRects.container\n * @return {object} Contains the following fields:\n * - {number} arrowX\n * - {number} arrowY\n * - {number} containerX\n * - {number} containerY\n * - {string} baseArrowStyle\n */\nfunction calcPositionAboveXY(\n x: number,\n y: number,\n tooltipRects: TooltipRectsT,\n) {\n const { arrow, container } = tooltipRects;\n return {\n arrowX: 0.5 * (container.width - arrow.width),\n arrowY: container.height,\n containerX: x - container.width / 2,\n containerY: y - container.height - arrow.height / 1.5,\n\n // TODO: Instead of already setting the base style here, we should\n // introduce a set of constants for arrow directions, which will help\n // to do checks dependant on the arrow direction.\n baseArrowStyle: ARROW_STYLE_DOWN,\n };\n}\n\n// const HIT = {\n// NONE: false,\n// LEFT: 'LEFT',\n// RIGHT: 'RIGHT',\n// TOP: 'TOP',\n// BOTTOM: 'BOTTOM',\n// };\n\n/**\n * Checks whether\n * @param {object} pos\n * @param {object} tooltipRects\n * @param {object} viewportRect\n * @return {HIT}\n */\n// function checkViewportFit(pos, tooltipRects, viewportRect) {\n// const { containerX, containerY } = pos;\n// if (containerX < viewportRect.left + 6) return HIT.LEFT;\n// if (containerX > viewportRect.right - 6) return HIT.RIGHT;\n// return HIT.NONE;\n// }\n\n/**\n * Shifts tooltip horizontally to fit into the viewport, while keeping\n * the arrow pointed to the XY point.\n * @param {number} x\n * @param {number} y\n * @param {object} pos\n * @param {number} pageXOffset\n * @param {number} pageXWidth\n */\n// function xPageFitCorrection(x, y, pos, pageXOffset, pageXWidth) {\n// if (pos.containerX < pageXOffset + 6) {\n// pos.containerX = pageXOffset + 6;\n// pos.arrowX = Math.max(6, pageX - containerX - arrowRect.width / 2);\n// } else {\n// const maxX = pageXOffset + docRect.width - containerRect.width - 6;\n// if (containerX > maxX) {\n// containerX = maxX;\n// arrowX = Math.min(\n// containerRect.width - 6,\n// pageX - containerX - arrowRect.width / 2,\n// );\n// }\n// }\n// }\n\n/**\n * Sets positions of tooltip components to point the tooltip to the specified\n * page point.\n * @ignore\n * @param pageX\n * @param pageY\n * @param placement\n * @param element DOM reference to the element wrapped by the tooltip.\n * @param tooltip\n * @param tooltip.arrow DOM reference to the tooltip arrow.\n * @param tooltip.container DOM reference to the tooltip container.\n */\nfunction setComponentPositions(\n pageX: number,\n pageY: number,\n placement: PLACEMENTS | undefined,\n element: HTMLElement | undefined,\n tooltip: ComponentsT,\n) {\n const tooltipRects = calcTooltipRects(tooltip);\n const viewportRect = calcViewportRect();\n\n /* Default container coords: tooltip at the top. */\n const pos = calcPositionAboveXY(pageX, pageY, tooltipRects);\n\n if (pos.containerX < viewportRect.left + 6) {\n pos.containerX = viewportRect.left + 6;\n pos.arrowX = Math.max(\n 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n } else {\n const maxX = viewportRect.right - 6 - tooltipRects.container.width;\n if (pos.containerX > maxX) {\n pos.containerX = maxX;\n pos.arrowX = Math.min(\n tooltipRects.container.width - 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n }\n }\n\n /* If tooltip has not enough space on top - make it bottom tooltip. */\n if (pos.containerY < viewportRect.top + 6) {\n pos.containerY += tooltipRects.container.height\n + 2 * tooltipRects.arrow.height;\n pos.arrowY -= tooltipRects.container.height\n + tooltipRects.arrow.height;\n pos.baseArrowStyle = ARROW_STYLE_UP;\n }\n\n const containerStyle = `left:${pos.containerX}px;top:${pos.containerY}px`;\n tooltip.container.setAttribute('style', containerStyle);\n\n const arrowStyle = `${pos.baseArrowStyle};left:${pos.arrowX}px;top:${pos.arrowY}px`;\n tooltip.arrow.setAttribute('style', arrowStyle);\n}\n\n/* The Tooltip component itself. */\nconst Tooltip: FunctionComponent<{\n children?: ReactNode;\n ref?: RefObject<unknown>;\n theme: TooltipThemeT;\n}> = ({ children, ref, theme }) => {\n // NOTE: The way it has to be implemented, for clean mounting and unmounting\n // at the client side, the <Tooltip> is fully mounted into DOM in the next\n // rendering cycles, and only then it can be correctly measured and positioned.\n // Thus, when we create the <Tooltip> we have to record its target positioning\n // details, and then apply them when it is created.\n\n const { current: heap } = useRef<HeapT>({\n lastElement: undefined,\n lastPageX: 0,\n lastPageY: 0,\n lastPlacement: undefined,\n });\n\n const [components, setComponents] = useState<ComponentsT | null>(null);\n\n const pointTo = (\n pageX: number,\n pageY: number,\n placement: PLACEMENTS,\n element: HTMLElement,\n ) => {\n heap.lastElement = element;\n heap.lastPageX = pageX;\n heap.lastPageY = pageY;\n heap.lastPlacement = placement;\n\n if (components) {\n setComponentPositions(pageX, pageY, placement, element, components);\n }\n };\n useImperativeHandle(ref, () => ({ pointTo }));\n\n /* Inits and destroys tooltip components. */\n useEffect(() => {\n const x = createTooltipComponents(theme);\n setComponents(x);\n return () => {\n document.body.removeChild(x.container);\n setComponents(null);\n };\n }, [theme]);\n\n useEffect(() => {\n if (components) {\n setComponentPositions(\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n components,\n );\n }\n }, [\n components,\n // BEWARE: Careful about these dependencies - they are updated when mouse\n // is moved over the tool-tipped element, thus potentially may cause\n // unnecessary firing of this effect on each mouse event. It does not\n // happen now just because the mouse movements themselves are not causing\n // the component re-rendering, thus dependencies of this effect are not\n // really re-evaluated.\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n ]);\n\n return components ? createPortal(children, components.content) : null;\n};\n\nexport default Tooltip;\n"],"mappings":";;;;;;AAMA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,SAAA,GAAAD,OAAA;AAhBA;AACA;AACA;AACA;AACA;AAgBA;AACA;AACA;AACA;AAHA,IAIYE,UAAU,GAAAC,OAAA,CAAAD,UAAA,0BAAVA,UAAU;EAAVA,UAAU;EAAVA,UAAU;EAAVA,UAAU;EAAVA,UAAU;EAAA,OAAVA,UAAU;AAAA;AAOtB,MAAME,gBAAgB,GAAG,CACvB,iCAAiC,EACjC,+BAA+B,EAC/B,gCAAgC,CACjC,CAACC,IAAI,CAAC,GAAG,CAAC;AAEX,MAAMC,cAAc,GAAG,CACrB,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,CACjC,CAACD,IAAI,CAAC,GAAG,CAAC;AAuBX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,uBAAuBA,CAACC,KAAoB,EAAe;EAClE,MAAMC,KAAK,GAAGC,QA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CAAC;EACH,CAAC,EAAE,CAAC3D,KAAK,CAAC,CAAC;EAEX,IAAA+D,gBAAS,EAAC,MAAM;IACd,IAAIL,UAAU,EAAE;MACdxB,qBAAqB,CACnBiB,IAAI,CAACI,SAAS,EACdJ,IAAI,CAACK,SAAS,EACdL,IAAI,CAACM,aAAa,EAClBN,IAAI,CAACE,WAAW,EAChBK,UACF,CAAC;IACH;EACF,CAAC,EAAE,CACDA,UAAU;EACV;EACA;EACA;EACA;EACA;EACA;EACAP,IAAI,CAACI,SAAS,EACdJ,IAAI,CAACK,SAAS,EACdL,IAAI,CAACM,aAAa,EAClBN,IAAI,CAACE,WAAW,CACjB,CAAC;EAEF,OAAOK,UAAU,gBAAG,IAAAO,sBAAY,EAACjB,QAAQ,EAAEU,UAAU,CAACrD,OAAO,CAAC,GAAG,IAAI;AACvE,CAAC;AAAC,IAAA6D,QAAA,GAAAvE,OAAA,CAAAwE,OAAA,GAEapB,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"Tooltip.js","names":["_react","require","_reactDom","PLACEMENTS","exports","ARROW_STYLE_DOWN","join","ARROW_STYLE_UP","createTooltipComponents","theme","arrow","document","createElement","setAttribute","content","container","appendChild","body","calcTooltipRects","tooltip","getBoundingClientRect","calcViewportRect","scrollX","scrollY","window","documentElement","clientHeight","clientWidth","bottom","left","right","top","calcPositionAboveXY","x","y","tooltipRects","arrowX","width","arrowY","height","containerX","containerY","baseArrowStyle","setComponentPositions","pageX","pageY","placement","element","viewportRect","pos","Math","max","maxX","min","containerStyle","arrowStyle","Tooltip","children","ref","current","heap","useRef","lastElement","undefined","lastPageX","lastPageY","lastPlacement","components","setComponents","useState","pointTo","useImperativeHandle","useEffect","removeChild","createPortal","_default","default"],"sources":["../../../../../src/shared/components/WithTooltip/Tooltip.ts"],"sourcesContent":["/**\n * The actual tooltip component. It is rendered outside the regular document\n * hierarchy, and with sub-components managed without React to achieve the best\n * performance during animation.\n */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\n/**\n * Valid placements of the rendered tooltip. They will be overriden when\n * necessary to fit the tooltip within the viewport.\n */\nexport enum PLACEMENTS {\n ABOVE_CURSOR = 'ABOVE_CURSOR',\n ABOVE_ELEMENT = 'ABOVE_ELEMENT',\n BELOW_CURSOR = 'BELOW_CURSOR',\n BELOW_ELEMENT = 'BELOW_ELEMENT',\n}\n\nconst ARROW_STYLE_DOWN = [\n 'border-bottom-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\nconst ARROW_STYLE_UP = [\n 'border-top-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\ntype ComponentsT = {\n container: HTMLDivElement;\n arrow: HTMLDivElement;\n content: HTMLDivElement;\n};\n\ntype HeapT = {\n lastElement?: HTMLElement;\n lastPageX: number;\n lastPageY: number;\n lastPlacement?: PLACEMENTS | undefined;\n};\n\nexport type ThemeKeysT = 'appearance' | 'arrow' | 'content' | 'container';\n\ntype TooltipThemeT = Theme<ThemeKeysT>;\n\n/**\n * Creates tooltip components.\n * @ignore\n * @param {object} theme Themes to use for tooltip container, arrow,\n * and content.\n * @return {object} Object with DOM references to the container components:\n * container, arrow, content.\n */\nfunction createTooltipComponents(theme: TooltipThemeT): ComponentsT {\n const arrow = document.createElement('div');\n if (theme.arrow) arrow.setAttribute('class', theme.arrow);\n\n const content = document.createElement('div');\n if (theme.content) content.setAttribute('class', theme.content);\n\n const container = document.createElement('div');\n if (theme.container) container.setAttribute('class', theme.container);\n\n container.appendChild(arrow);\n container.appendChild(content);\n document.body.appendChild(container);\n\n return { arrow, container, content };\n}\n\ntype TooltipRectsT = {\n arrow: DOMRect;\n container: DOMRect;\n};\n\n/**\n * Generates bounding client rectangles for tooltip components.\n * @ignore\n * @param tooltip DOM references to the tooltip components.\n * @param tooltip.arrow\n * @param tooltip.container\n * @return Object holding tooltip rectangles in\n * two fields.\n */\nfunction calcTooltipRects(tooltip: ComponentsT): TooltipRectsT {\n return {\n arrow: tooltip.arrow.getBoundingClientRect(),\n container: tooltip.container.getBoundingClientRect(),\n };\n}\n\n/**\n * Calculates the document viewport size.\n * @ignore\n * @return {{x, y, width, height}}\n */\nfunction calcViewportRect() {\n const { scrollX, scrollY } = window;\n const { documentElement: { clientHeight, clientWidth } } = document;\n return {\n bottom: scrollY + clientHeight,\n left: scrollX,\n right: scrollX + clientWidth,\n top: scrollY,\n };\n}\n\n/**\n * Calculates tooltip and arrow positions for the placement just above\n * the cursor.\n * @ignore\n * @param {number} x Cursor page-x position.\n * @param {number} y Cursor page-y position.\n * @param {object} tooltipRects Bounding client rectangles of tooltip parts.\n * @param {object} tooltipRects.arrow\n * @param {object} tooltipRects.container\n * @return {object} Contains the following fields:\n * - {number} arrowX\n * - {number} arrowY\n * - {number} containerX\n * - {number} containerY\n * - {string} baseArrowStyle\n */\nfunction calcPositionAboveXY(\n x: number,\n y: number,\n tooltipRects: TooltipRectsT,\n) {\n const { arrow, container } = tooltipRects;\n return {\n arrowX: 0.5 * (container.width - arrow.width),\n arrowY: container.height,\n containerX: x - container.width / 2,\n containerY: y - container.height - arrow.height / 1.5,\n\n // TODO: Instead of already setting the base style here, we should\n // introduce a set of constants for arrow directions, which will help\n // to do checks dependant on the arrow direction.\n baseArrowStyle: ARROW_STYLE_DOWN,\n };\n}\n\n// const HIT = {\n// NONE: false,\n// LEFT: 'LEFT',\n// RIGHT: 'RIGHT',\n// TOP: 'TOP',\n// BOTTOM: 'BOTTOM',\n// };\n\n/**\n * Checks whether\n * @param {object} pos\n * @param {object} tooltipRects\n * @param {object} viewportRect\n * @return {HIT}\n */\n// function checkViewportFit(pos, tooltipRects, viewportRect) {\n// const { containerX, containerY } = pos;\n// if (containerX < viewportRect.left + 6) return HIT.LEFT;\n// if (containerX > viewportRect.right - 6) return HIT.RIGHT;\n// return HIT.NONE;\n// }\n\n/**\n * Shifts tooltip horizontally to fit into the viewport, while keeping\n * the arrow pointed to the XY point.\n * @param {number} x\n * @param {number} y\n * @param {object} pos\n * @param {number} pageXOffset\n * @param {number} pageXWidth\n */\n// function xPageFitCorrection(x, y, pos, pageXOffset, pageXWidth) {\n// if (pos.containerX < pageXOffset + 6) {\n// pos.containerX = pageXOffset + 6;\n// pos.arrowX = Math.max(6, pageX - containerX - arrowRect.width / 2);\n// } else {\n// const maxX = pageXOffset + docRect.width - containerRect.width - 6;\n// if (containerX > maxX) {\n// containerX = maxX;\n// arrowX = Math.min(\n// containerRect.width - 6,\n// pageX - containerX - arrowRect.width / 2,\n// );\n// }\n// }\n// }\n\n/**\n * Sets positions of tooltip components to point the tooltip to the specified\n * page point.\n * @ignore\n * @param pageX\n * @param pageY\n * @param placement\n * @param element DOM reference to the element wrapped by the tooltip.\n * @param tooltip\n * @param tooltip.arrow DOM reference to the tooltip arrow.\n * @param tooltip.container DOM reference to the tooltip container.\n */\nfunction setComponentPositions(\n pageX: number,\n pageY: number,\n placement: PLACEMENTS | undefined,\n element: HTMLElement | undefined,\n tooltip: ComponentsT,\n) {\n const tooltipRects = calcTooltipRects(tooltip);\n const viewportRect = calcViewportRect();\n\n /* Default container coords: tooltip at the top. */\n const pos = calcPositionAboveXY(pageX, pageY, tooltipRects);\n\n if (pos.containerX < viewportRect.left + 6) {\n pos.containerX = viewportRect.left + 6;\n pos.arrowX = Math.max(\n 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n } else {\n const maxX = viewportRect.right - 6 - tooltipRects.container.width;\n if (pos.containerX > maxX) {\n pos.containerX = maxX;\n pos.arrowX = Math.min(\n tooltipRects.container.width - 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n }\n }\n\n /* If tooltip has not enough space on top - make it bottom tooltip. */\n if (pos.containerY < viewportRect.top + 6) {\n pos.containerY += tooltipRects.container.height\n + 2 * tooltipRects.arrow.height;\n pos.arrowY -= tooltipRects.container.height\n + tooltipRects.arrow.height;\n pos.baseArrowStyle = ARROW_STYLE_UP;\n }\n\n const containerStyle = `left:${pos.containerX}px;top:${pos.containerY}px`;\n tooltip.container.setAttribute('style', containerStyle);\n\n const arrowStyle = `${pos.baseArrowStyle};left:${pos.arrowX}px;top:${pos.arrowY}px`;\n tooltip.arrow.setAttribute('style', arrowStyle);\n}\n\n/* The Tooltip component itself. */\nconst Tooltip: FunctionComponent<{\n children?: ReactNode;\n ref?: RefObject<unknown>;\n theme: TooltipThemeT;\n}> = ({ children, ref, theme }) => {\n // NOTE: The way it has to be implemented, for clean mounting and unmounting\n // at the client side, the <Tooltip> is fully mounted into DOM in the next\n // rendering cycles, and only then it can be correctly measured and positioned.\n // Thus, when we create the <Tooltip> we have to record its target positioning\n // details, and then apply them when it is created.\n\n const { current: heap } = useRef<HeapT>({\n lastElement: undefined,\n lastPageX: 0,\n lastPageY: 0,\n lastPlacement: undefined,\n });\n\n const [components, setComponents] = useState<ComponentsT | null>(null);\n\n const pointTo = (\n pageX: number,\n pageY: number,\n placement: PLACEMENTS,\n element: HTMLElement,\n ) => {\n heap.lastElement = element;\n heap.lastPageX = pageX;\n heap.lastPageY = pageY;\n heap.lastPlacement = placement;\n\n if (components) {\n setComponentPositions(pageX, pageY, placement, element, components);\n }\n };\n useImperativeHandle(ref, () => ({ pointTo }));\n\n /* Inits and destroys tooltip components. */\n useEffect(() => {\n const x = createTooltipComponents(theme);\n setComponents(x);\n return () => {\n document.body.removeChild(x.container);\n setComponents(null);\n };\n }, [theme]);\n\n useEffect(() => {\n if (components) {\n setComponentPositions(\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n components,\n );\n }\n }, [\n components,\n // BEWARE: Careful about these dependencies - they are updated when mouse\n // is moved over the tool-tipped element, thus potentially may cause\n // unnecessary firing of this effect on each mouse event. It does not\n // happen now just because the mouse movements themselves are not causing\n // the component re-rendering, thus dependencies of this effect are not\n // really re-evaluated.\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n ]);\n\n return components ? createPortal(children, components.content) : null;\n};\n\nexport default Tooltip;\n"],"mappings":";;;;;;AAMA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,SAAA,GAAAD,OAAA;AAhBA;AACA;AACA;AACA;AACA;AAgBA;AACA;AACA;AACA;AAHA,IAIYE,UAAU,GAAAC,OAAA,CAAAD,UAAA,0BAAVA,UAAU;EAAVA,UAAU;EAAVA,UAAU;EAAVA,UAAU;EAAVA,UAAU;EAAA,OAAVA,UAAU;AAAA;AAOtB,MAAME,gBAAgB,GAAG,CACvB,iCAAiC,EACjC,+BAA+B,EAC/B,gCAAgC,CACjC,CAACC,IAAI,CAAC,GAAG,CAAC;AAEX,MAAMC,cAAc,GAAG,CACrB,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,CACjC,CAACD,IAAI,CAAC,GAAG,CAAC;AAmBX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,uBAAuBA,CAACC,KAAoB,EAAe;EAClE,MAAMC,KAAK,GAAGC,QAAQ,CAACC,aAAa,CAAC,KAAK,CAAC;EAC3C,IAAIH,KAAK,CAACC,KAAK,EAAEA,KAAK,CAACG,YAAY,CAAC,OAAO,EAAEJ,KAAK,CAACC,KAAK,CAAC;EAEzD,MAAMI,OAAO,GAAGH,QAAQ,CAACC,aAAa,CAAC,KAAK,CAAC;EAC7C,IAAIH,KAAK,CAACK,OAAO,EAAEA,OAAO,CAACD,YAAY,CAAC,OAAO,EAAEJ,KAAK,CAACK,OAAO,CAAC;EAE/D,MAAMC,SAAS,GAAGJ,QAAQ,CAACC,aAAa,CAAC,KAAK,CAAC;EAC/C,IAAIH,KAAK,CAACM,SAAS,EAAEA,SAAS,CAACF,YAAY,CAAC,OAAO,EAAEJ,KAAK,CAACM,SAAS,CAAC;EAErEA,SAAS,CAACC,WAAW,CAACN,KAAK,CAAC;EAC5BK,SAAS,CAACC,WAA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,QAAA,GAAAvE,OAAA,CAAAwE,OAAA,GAEapB,OAAO","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_reactThemes","_interopRequireDefault","require","_common","_jsxRuntime","defaultTheme","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","iValue","iName","optionValueName","className","onPress","selected","push","jsx","onClick","onKeyDown","e","key","role","tabIndex","children","jsxs","container","_default","exports","default","themed"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT =\n | 'container'\n | 'label'\n | 'option'\n | 'options'\n | 'selected';\n\ntype PropsT = {\n label?: React.ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<React.ReactNode>>;\n theme: Theme<ThemeKeyT>;\n value?: ValueT;\n};\n\nconst BaseSwitch: React.FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options || !theme.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = theme.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${theme.selected}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={theme.container}>\n {label ? <div className={theme.label}>{label}</div> : null}\n\n <div className={theme.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n\nexport default themed(BaseSwitch, 'Switch', defaultTheme);\n"],"mappings":";;;;;;;AAAA,IAAAA,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AAoB,CAC1D,CAAC;EACH;EAEA,oBACE,IAAAX,WAAA,CAAA0B,IAAA;IAAKZ,SAAS,EAAER,KAAK,CAACqB,SAAU;IAAAF,QAAA,GAC7BtB,KAAK,gBAAG,IAAAH,WAAA,CAAAkB,GAAA;MAAKJ,SAAS,EAAER,KAAK,CAACH,KAAM;MAAAsB,QAAA,EAAEtB;IAAK,CAAM,CAAC,GAAG,IAAI,eAE1D,IAAAH,WAAA,CAAAkB,GAAA;MAAKJ,SAAS,EAAER,KAAK,CAACD,OAAQ;MAAAoB,QAAA,EAC3Bf;IAAW,CACT,CAAC;EAAA,CACH,CAAC;AAEV,CAAC;AAAC,IAAAkB,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEa,IAAAC,oBAAM,EAAC7B,UAAU,EAAE,QAAQ,EAAED,YAAY,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_reactThemes","_interopRequireDefault","require","_common","_jsxRuntime","defaultTheme","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","iValue","iName","optionValueName","className","onPress","selected","push","jsx","onClick","onKeyDown","e","key","role","tabIndex","children","jsxs","container","_default","exports","default","themed"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'container' | 'label' | 'option' | 'options' | 'selected';\n\ntype PropsT = {\n label?: React.ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<React.ReactNode>>;\n theme: Theme<ThemeKeyT>;\n value?: ValueT;\n};\n\nconst BaseSwitch: React.FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options || !theme.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = theme.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${theme.selected}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={theme.container}>\n {label ? <div className={theme.label}>{label}</div> : null}\n\n <div className={theme.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n\nexport default themed(BaseSwitch, 'Switch', defaultTheme);\n"],"mappings":";;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,OAAA,GAAAD,OAAA;AAImB,IAAAE,WAAA,GAAAF,OAAA;AAAA,MAAAG,YAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAcnB,MAAMC,UAA2C,GAAGA,CAAC;EACnDC,KAAK;EACLC,QAAQ;EACRC,OAAO;EACPC,KAAK;EACLC;AACF,CAAC,KAAK;EACJ,IAAI,CAACF,OAAO,IAAI,CAACC,KAAK,CAACE,MAAM,EAAE,MAAMC,KAAK,CAAC,gBAAgB,CAAC;EAE5D,MAAMC,WAA8B,GAAG,EAAE;EACzC,KAAK,MAAMF,MAAM,IAAIH,OAAO,EAAE;IAC5B,MAAM,CAACM,MAAM,EAAEC,KAAK,CAAC,GAAG,IAAAC,uBAAe,EAACL,MAAM,CAAC;IAE/C,IAAIM,SAAiB,GAAGR,KAAK,CAACE,MAAM;IACpC,IAAIO,OAAiC;IACrC,IAAIJ,MAAM,KAAKJ,KAAK,EAAEO,SAAS,IAAI,IAAIR,KAAK,CAACU,QAAQ,EAAE,CAAC,KACnD,IAAIZ,QAAQ,EAAE;MACjBW,OAAO,GAAGA,CAAA,KAAM;QACdX,QAAQ,CAACO,MAAM,CAAC;MAClB,CAAC;IACH;IAEAD,WAAW,CAACO,IAAI,CACdF,OAAO,gBAEH,IAAAf,WAAA,CAAAkB,GAAA;MACEJ,SAAS,EAAEA,SAAU;MAErBK,OAAO,EAAEJ,OAAQ;MACjBK,SAAS,EAAGC,CAAC,IAAK;QAChB,IAAIA,CAAC,CAACC,GAAG,KAAK,OAAO,EAAEP,OAAO,CAAC,CAAC;MAClC,CAAE;MACFQ,IAAI,EAAC,QAAQ;MACbC,QAAQ,EAAE,CAAE;MAAAC,QAAA,EAEXb;IAAK,GARDD,MASF,CAAC,gBAEN,IAAAX,WAAA,CAAAkB,GAAA;MAAKJ,SAAS,EAAEA,SAAU;MAAAW,QAAA,EAAeb;IAAK,GAAdD,MAAoB,CAC1D,CAAC;EACH;EAEA,oBACE,IAAAX,WAAA,CAAA0B,IAAA;IAAKZ,SAAS,EAAER,KAAK,CAACqB,SAAU;IAAAF,QAAA,GAC7BtB,KAAK,gBAAG,IAAAH,WAAA,CAAAkB,GAAA;MAAKJ,SAAS,EAAER,KAAK,CAACH,KAAM;MAAAsB,QAAA,EAAEtB;IAAK,CAAM,CAAC,GAAG,IAAI,eAE1D,IAAAH,WAAA,CAAAkB,GAAA;MAAKJ,SAAS,EAAER,KAAK,CAACD,OAAQ;MAAAoB,QAAA,EAC3Bf;IAAW,CACT,CAAC;EAAA,CACH,CAAC;AAEV,CAAC;AAAC,IAAAkB,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEa,IAAAC,oBAAM,EAAC7B,UAAU,EAAE,QAAQ,EAAED,YAAY,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"common.js","names":["isValue","x","type","optionValueName","option","value","name"],"sources":["../../../../../src/shared/components/selectors/common.ts"],"sourcesContent":["// The stuff common between different dropdown implementations.\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\ntype ThemeKeyT =\n | 'active'\n | 'arrow'\n | 'container'\n | 'dropdown'\n | 'hiddenOption'\n | 'label'\n | 'option'\n | 'select'\n\n // TODO: This is currently only valid for (native) <Dropdown>,\n // other kinds of selectors should be evaluated, and aligned with this\n // feature, if appropriate.\n | 'invalid'\n\n // TODO: This is only valid for <CustomDropdown>, thus we need to re-factor it\n // into a separate theme spec for that component.\n | 'upward';\n\nexport type ValueT = number | string;\n\nexport type OptionT<NameT> = {\n name?: NameT | null;\n value: ValueT;\n};\n\nexport type OptionsT<NameT> = Readonly<Array<OptionT<NameT> | ValueT>>;\n\nexport type PropsT<\n NameT,\n OnChangeT = React.ChangeEventHandler<HTMLSelectElement>,\n> = {\n filter?: (item: OptionT<NameT> | ValueT) => boolean;\n label?: React.ReactNode;\n onChange?: OnChangeT;\n options: Readonly<OptionsT<NameT>>;\n testId?: string;\n theme: Theme<ThemeKeyT>;\n value?: ValueT;\n};\n\nfunction isValue<T>(x: OptionT<T> | ValueT): x is ValueT {\n const type = typeof x;\n return type === 'number' || type === 'string';\n}\n\n/** Returns option value and name as a tuple. */\nexport function optionValueName<NameT>(\n option: OptionT<NameT> | ValueT,\n): [ValueT, NameT | ValueT] {\n return isValue(option)\n ? [option, option]\n : [option.value, option.name ?? option.value];\n}\n"],"mappings":";;;;;;AAAA;;AA6CA,SAASA,OAAOA,CAAIC,CAAsB,EAAe;EACvD,MAAMC,IAAI,GAAG,OAAOD,CAAC;EACrB,OAAOC,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,QAAQ;AAC/C;;AAEA;AACO,SAASC,eAAeA,CAC7BC,MAA+B,EACL;EAC1B,OAAOJ,OAAO,CAACI,MAAM,CAAC,GAClB,CAACA,MAAM,EAAEA,MAAM,CAAC,GAChB,CAACA,MAAM,CAACC,KAAK,EAAED,MAAM,CAACE,IAAI,IAAIF,MAAM,CAACC,KAAK,CAAC;AACjD","ignoreList":[]}
1
+ {"version":3,"file":"common.js","names":["isValue","x","type","optionValueName","option","value","name"],"sources":["../../../../../src/shared/components/selectors/common.ts"],"sourcesContent":["// The stuff common between different dropdown implementations.\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\ntype ThemeKeyT = 'active'\n | 'arrow'\n | 'container'\n | 'dropdown'\n | 'hiddenOption'\n | 'label'\n | 'option'\n | 'select'\n\n // TODO: This is currently only valid for (native) <Dropdown>,\n // other kinds of selectors should be evaluated, and aligned with this\n // feature, if appropriate.\n | 'invalid'\n\n // TODO: This is only valid for <CustomDropdown>, thus we need to re-factor it\n // into a separate theme spec for that component.\n | 'upward';\n\nexport type ValueT = number | string;\n\nexport type OptionT<NameT> = {\n name?: NameT | null;\n value: ValueT;\n};\n\nexport type OptionsT<NameT> = Readonly<Array<OptionT<NameT> | ValueT>>;\n\nexport type PropsT<\n NameT,\n OnChangeT = React.ChangeEventHandler<HTMLSelectElement>,\n> = {\n filter?: (item: OptionT<NameT> | ValueT) => boolean;\n label?: React.ReactNode;\n onChange?: OnChangeT;\n options: Readonly<OptionsT<NameT>>;\n testId?: string;\n theme: Theme<ThemeKeyT>;\n value?: ValueT;\n};\n\nfunction isValue<T>(x: OptionT<T> | ValueT): x is ValueT {\n const type = typeof x;\n return type === 'number' || type === 'string';\n}\n\n/** Returns option value and name as a tuple. */\nexport function optionValueName<NameT>(\n option: OptionT<NameT> | ValueT,\n): [ValueT, NameT | ValueT] {\n return isValue(option)\n ? [option, option]\n : [option.value, option.name ?? option.value];\n}\n"],"mappings":";;;;;;AAAA;;AA4CA,SAASA,OAAOA,CAAIC,CAAsB,EAAe;EACvD,MAAMC,IAAI,GAAG,OAAOD,CAAC;EACrB,OAAOC,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,QAAQ;AAC/C;;AAEA;AACO,SAASC,eAAeA,CAC7BC,MAA+B,EACL;EAC1B,OAAOJ,OAAO,CAACI,MAAM,CAAC,GAClB,CAACA,MAAM,EAAEA,MAAM,CAAC,GAChB,CAACA,MAAM,CAACC,KAAK,EAAED,MAAM,CAACE,IAAI,IAAIF,MAAM,CAACC,KAAK,CAAC;AACjD","ignoreList":[]}
@@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
7
  exports.default = void 0;
8
- var _path = _interopRequireDefault(require("path"));
8
+ var _nodePath = _interopRequireDefault(require("node:path"));
9
9
  var _lodash = require("lodash");
10
10
  var _experimentalWorker = _interopRequireDefault(require("@babel/register/experimental-worker"));
11
11
  var _jestEnvironmentJsdom = _interopRequireDefault(require("jest-environment-jsdom"));
@@ -51,7 +51,7 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
51
51
  });
52
52
  const factoryPath = this.pragmas['webpack-config-factory'];
53
53
  // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
54
- let factory = require(_path.default.resolve(this.rootDir, factoryPath));
54
+ let factory = require(_nodePath.default.resolve(this.rootDir, factoryPath));
55
55
  factory = 'default' in factory ? factory.default : factory;
56
56
  this.global.webpackConfig = factory(options);
57
57
  const fs = this.global.webpackOutputFs;
@@ -107,7 +107,7 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
107
107
  options.buildInfo ??= this.global.buildInfo;
108
108
  let cleanup;
109
109
  if (options.entry) {
110
- const p = _path.default.resolve(this.testFolder, options.entry);
110
+ const p = _nodePath.default.resolve(this.testFolder, options.entry);
111
111
  // TODO: This sure can be replaced by a dynamic import().
112
112
  // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
113
113
  const module = require(p);
@@ -170,7 +170,7 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
170
170
  projectConfig
171
171
  } = config;
172
172
  this.rootDir = projectConfig.rootDir;
173
- this.testFolder = _path.default.dirname(context.testPath);
173
+ this.testFolder = _nodePath.default.dirname(context.testPath);
174
174
  this.withSsr = !pragmas['no-ssr'];
175
175
  this.ssrRequest = request;
176
176
  this.pragmas = pragmas;
@@ -1 +1 @@
1
- {"version":3,"file":"E2eSsrEnv.js","names":["_path","_interopRequireDefault","require","_lodash","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","_buildInfo","E2eSsrEnv","JsdomEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","defaults","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","path","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","webpack","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","noop","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","ssrFactory","status","markup","ssrRequest","cookie","send","set","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","createFsFromVolume","Volume","dirname","testPath","withSsr","root","process","cwd","register","envName","babelEnv","extensions","setup","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert","exports"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'path';\n\nimport type { Request, Response } from 'express';\nimport { defaults, noop, set } from 'lodash';\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":";;;;;;;AAkBA,IAAAA,KAAA,GAAAC,sBAAA,CAAAC,OAAA;AAGA,IAAAC,OAAA,GAAAD,OAAA;AAMA,IAAAE,mBAAA,GAAAH,sBAAA,CAAAC,OAAA;AAEA,IAAAG,qBAAA,GAAAJ,sBAAA,CAAAC,OAAA;AACA,IAAAI,MAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAN,sBAAA,CAAAC,OAAA;AAQA,IAAAM,SAAA,GAAAP,sBAAA,CAAAC,OAAA;AAEA,IAAAO,UAAA,GAAAP,OAAA;AAzCA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAQA;AACA;AACA;;AAMA;;AAWe,MAAMQ,SAAS,SAASC,6BAAQ,CAAC;EAa9C;AACF;AACA;AACA;EACUC,iBAAiBA,CAAA,EAAG;IAC1B,MAAMC,aAAa,GAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW;IAEtE,MAAMC,OAAO,GAAIF,aAAa,GAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,GAAG,CAAC,CACvC;IAEvB,IAAAK,gBAAQ,EAACH,OAAO,EAAE;MAChBI,OAAO,EAAE,IAAI,CAACC,UAAU;MACxBC,EAAE,EAAE,IAAI,CAACC,MAAM,CAACC;IAClB,CAAC,CAAC;IAEF,MAAMC,WAAW,GAAG,IAAI,CAACV,OAAO,CAAC,wBAAwB,CAAW;IACpE;IACA,IAAIW,OAAO,GAAGvB,OAAO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A;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACAhC,OAAO,CAACmG,KAAK,GAAG,CAAC,CAAC;IAClB,IAAAC,uBAAY,EAACC,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAACX,OAAO,EAAE,MAAM,IAAI,CAACzC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC7B,MAAM,CAACkF,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAMC,QAAQA,CAAA,EAAkB;IAC9B,OAAO,IAAI,CAACnF,MAAM,CAACkF,6BAA6B;;IAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACzG,OAAO,CAACmG,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAO3G,OAAO,CAACmG,KAAK,CAACQ,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFb,2BAAQ,CAACc,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF;AAACM,OAAA,CAAAlF,OAAA,GAAAnB,SAAA","ignoreList":[]}
1
+ {"version":3,"file":"E2eSsrEnv.js","names":["_nodePath","_interopRequireDefault","require","_lodash","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","_buildInfo","E2eSsrEnv","JsdomEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","defaults","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","path","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","webpack","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","noop","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","ssrFactory","status","markup","ssrRequest","cookie","send","set","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","createFsFromVolume","Volume","dirname","testPath","withSsr","root","process","cwd","register","envName","babelEnv","extensions","setup","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert","exports"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\nimport { defaults, noop, set } from 'lodash';\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":";;;;;;;AAkBA,IAAAA,SAAA,GAAAC,sBAAA,CAAAC,OAAA;AAGA,IAAAC,OAAA,GAAAD,OAAA;AAMA,IAAAE,mBAAA,GAAAH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,CAACzG,OAAO,CAACmG,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAO3G,OAAO,CAACmG,KAAK,CAACQ,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFb,2BAAQ,CAACc,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF;AAACM,OAAA,CAAAlF,OAAA,GAAAnB,SAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_react","_client","_react2","_global","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","mockdate","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","act","unmount","remove","snapshot","expect","toMatchSnapshot","createRoot","render","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): string {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT =\n (config: AxiosRequestConfig) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAAA,SAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAEA,IAAAG,OAAA,GAAAH,OAAA;AAQA,IAAAI,OAAA,GAAAL,sBAAA,CAAAC,OAAA;AAtBA;AACA;;AAeA;AACA;AACA;AACA;;AAKAK,MAAM,CAACC,wBAAwB,GAAG,IAAI;AAEtC,MAAMC,uBAAuB,GAAGC,OAAO,CAACC,QAAQ;;AAEhD;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAAS;EACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,EAAE,UAAU,EAAE;IAAEK,KAAK,EAAEC;EAAU,CAAC,CAAC;AAClE;;AAEA;AACA;AACA;AACO,SAASC,gBAAgBA,CAAA,EAAS;EACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,EAAE,UAAU,EAAE;IACzCK,KAAK,EAAEN,uBAAuB;IAC9BS,QAAQ,EAAE;EACZ,CAAC,CAAC;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,WAAWA,CAACC,IAAI,GAAG,CAAC,EAAU;EAC5C,MAAMC,CAAC,GAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC;EAC7C,OAAO,GAAGF,CAAC,CAACG,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAIH,CAAC,CAACG,KAAK,CAAC,CAAC,EAAE,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OAAO,CAAC;IACrB,OAAOc,OAAO,EAAEE,KAAK;EACvB,CAAC,CAAC;EAEF,IAAIpC,GAAG,KAAKlB,SAAS,EAAE,MAAMuD,KAAK,CAAC,eAAe,CAAC;EACnD,IAAIH,OAAO,EAAEE,KAAK,EAAE;IAClB;IACA;IACA;IACA;IACA,OAAO,IAAIE,OAAO,CAAEC,OAAO,IAAK;MAC9B,KAAKJ,OAAO,CAACK,IAAI,CAAC,MAAM;QACtB;QACA;QACA,MAAMC,KAAK,GAAGzC,GAAG,CAAE0C,UAAU,CAAC,CAAC,CAACC,UAAU;QAC1Cb,MAAM,CAACW,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACV,eAAe,CAAC,CAAC;QAClEQ,OAAO,CAACvC,GAAI,CAAC;MACf,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ;EAEA,MAAMyC,KAAK,GAAGzC,GAAG,CAAC0C,UAAU,CAAC,CAAC,CAACC,UAAU;EACzCb,MAAM,CAACW,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACV,eAAe,CAAC,CAAC;EAClE,OAAO/B,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_react","_client","_react2","_global","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","mockdate","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","act","unmount","remove","snapshot","expect","toMatchSnapshot","createRoot","render","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): string {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAAA,SAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAEA,IAAAG,OAAA,GAAAH,OAAA;AAQA,IAAAI,OAAA,GAAAL,sBAAA,CAAAC,OAAA;AAtBA;AACA;;AAeA;AACA;AACA;AACA;;AAKAK,MAAM,CAACC,wBAAwB,GAAG,IAAI;AAEtC,MAAMC,uBAAuB,GAAGC,OAAO,CAACC,QAAQ;;AAEhD;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAAS;EACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO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G,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACV,eAAe,CAAC,CAAC;EAClE,OAAO/B,GAAG;AACZ","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"webpack.js","names":["_isomorphy","require","requireWeak","modulePath","basePath","IS_CLIENT_SIDE","req","eval","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathT from 'path';\n\nimport { IS_CLIENT_SIDE } from './isomorphy';\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n basePath?: string,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n // TODO: On one hand, this try/catch wrap silencing errors is bad, as it may\n // hide legit errors, in a way difficult to notice and understand; but on the\n // other hand it fails for some (unclear, but legit?) reasons in some\n // environments,\n // like during the static code generation for docs. Perhaps, something should\n // be implemented differently here.\n try {\n // eslint-disable-next-line no-eval\n const req = eval('require') as (path: string) => unknown;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = req('path') as typeof PathT;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n const module = req(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned) (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":";;;;;;;AAEA,IAAAA,UAAA,GAAAC,OAAA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,WAAWA,CACzBC,UAAkB,EAClBC,QAAiB,EACU;EAC3B,IAAIC,yBAAc,EAAE,OAAO,IAAI;;EAE/B;EACA;EACA;EACA;EACA;EACA;EACA,IAAI;IACF;IACA,MAAMC,GAAG,GAAGC,IAAI,CAAC,SAAS,CAA8B;;IAExD;IACA,MAAM;MAAEC;IAAQ,CAAC,GAAGF,GAAG,CAAC,MAAM,CAAiB;IAE/C,MAAMG,IAAI,GAAGL,QAAQ,GAAGI,OAAO,CAACJ,QAAQ,EAAED,UAAU,CAAC,GAAGA,UAAU;IAClE,MAAMO,MAAM,GAAGJ,GAAG,CAACG,IAAI,CAAM;IAE7B,IAAI,EAAE,SAAS,IAAIC,MAAM,CAAC,IAAI,CAACA,MAAM,CAACC,OAAO,EAAE,OAAOD,MAAM;IAE5D,MAAM;MAAEC,OAAO,EAAEC,GAAG;MAAE,GAAGC;IAAM,CAAC,GAAGH,MAAM;IAEzC,MAAMI,GAAG,GAAGF,GAAyB;IAErCG,MAAM,CAACC,OAAO,CAACH,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC,CAACC,IAAI,EAAEC,KAAK,CAAC,KAAK;MAC/C,MAAMC,QAAQ,GAAGN,GAAG,CAACI,IAAI,CAA6B;MACtD,IAAIE,QAAQ,EAAGN,GAAG,CAACI,IAAI,CAA6B,GAAeC,KAAK,CAAC,KACpE,IAAIC,QAAQ,KAAKD,KAAK,EAAE;QAC3B,MAAME,KAAK,CAAC,4CAA4C,CAAC;MAC3D;IACF,CAAC,CAAC;IACF,OAAOP,GAAG;EACZ,CAAC,CAAC,MAAM;IACN,OAAO,IAAI;EACb;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASQ,WAAWA,CAACnB,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
1
+ {"version":3,"file":"webpack.js","names":["_isomorphy","require","requireWeak","modulePath","basePath","IS_CLIENT_SIDE","req","eval","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\nimport { IS_CLIENT_SIDE } from './isomorphy';\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n basePath?: string,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n // TODO: On one hand, this try/catch wrap silencing errors is bad, as it may\n // hide legit errors, in a way difficult to notice and understand; but on the\n // other hand it fails for some (unclear, but legit?) reasons in some\n // environments,\n // like during the static code generation for docs. Perhaps, something should\n // be implemented differently here.\n try {\n // eslint-disable-next-line no-eval\n const req = eval('require') as (path: string) => unknown;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = req('path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n const module = req(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned) (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":";;;;;;;AAEA,IAAAA,UAAA,GAAAC,OAAA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,WAAWA,CACzBC,UAAkB,EAClBC,QAAiB,EACU;EAC3B,IAAIC,yBAAc,EAAE,OAAO,IAAI;;EAE/B;EACA;EACA;EACA;EACA;EACA;EACA,IAAI;IACF;IACA,MAAMC,GAAG,GAAGC,IAAI,CAAC,SAAS,CAA8B;;IAExD;IACA,MAAM;MAAEC;IAAQ,CAAC,GAAGF,GAAG,CAAC,MAAM,CAAkB;IAEhD,MAAMG,IAAI,GAAGL,QAAQ,GAAGI,OAAO,CAACJ,QAAQ,EAAED,UAAU,CAAC,GAAGA,UAAU;IAClE,MAAMO,MAAM,GAAGJ,GAAG,CAACG,IAAI,CAAM;IAE7B,IAAI,EAAE,SAAS,IAAIC,MAAM,CAAC,IAAI,CAACA,MAAM,CAACC,OAAO,EAAE,OAAOD,MAAM;IAE5D,MAAM;MAAEC,OAAO,EAAEC,GAAG;MAAE,GAAGC;IAAM,CAAC,GAAGH,MAAM;IAEzC,MAAMI,GAAG,GAAGF,GAAyB;IAErCG,MAAM,CAACC,OAAO,CAACH,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC,CAACC,IAAI,EAAEC,KAAK,CAAC,KAAK;MAC/C,MAAMC,QAAQ,GAAGN,GAAG,CAACI,IAAI,CAA6B;MACtD,IAAIE,QAAQ,EAAGN,GAAG,CAACI,IAAI,CAA6B,GAAeC,KAAK,CAAC,KACpE,IAAIC,QAAQ,KAAKD,KAAK,EAAE;QAC3B,MAAME,KAAK,CAAC,4CAA4C,CAAC;MAC3D;IACF,CAAC,CAAC;IACF,OAAOP,GAAG;EACZ,CAAC,CAAC,MAAM;IACN,OAAO,IAAI;EACb;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASQ,WAAWA,CAACnB,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=launchServer;Object.defineProperty(exports,"errors",{enumerable:true,get:function(){return _utils.errors}});Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});require("source-map-support/register");var _http=_interopRequireDefault(require("http"));var _https=_interopRequireDefault(require("https"));var _lodash=require("lodash");require("raf/polyfill");var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./utils");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}// eslint-disable-next-line import/no-unassigned-import
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=launchServer;Object.defineProperty(exports,"errors",{enumerable:true,get:function(){return _utils.errors}});Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});require("source-map-support/register");var _nodeHttp=_interopRequireDefault(require("node:http"));var _nodeHttps=_interopRequireDefault(require("node:https"));var _lodash=require("lodash");require("raf/polyfill");var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./utils");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}// eslint-disable-next-line import/no-unassigned-import
2
2
  // Polyfill required by ReactJS.
3
3
  // TODO: Double-check, if it is still required by React v19?
4
4
  // eslint-disable-next-line import/no-unassigned-import
@@ -127,5 +127,5 @@
127
127
  */async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=(0,_lodash.cloneDeep)(options);// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
128
128
  ops.port=normalizePort(ops.port||process.env.PORT||3000);(0,_lodash.defaults)(ops,{httpsRedirect:true});// TODO: Need a separate type for normalized options, which guarantees
129
129
  // the logger is set!
130
- ops.logger??=(0,_renderer.newDefaultLogger)({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await(0,_server.default)(webpackConfig,ops);let httpServer;if(ops.https){httpServer=_https.default.createServer({cert:ops.https.cert,key:ops.https.key},expressServer)}else httpServer=_http.default.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=(0,_lodash.isString)(ops.port)?`Pipe ${ops.port}`:`Port ${ops.port}`;/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();const bind=(0,_lodash.isString)(addr)?`pipe ${addr}`:`port ${addr.port}`;ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`)});httpServer.listen(ops.port);return{expressServer,httpServer}}launchServer.SCRIPT_LOCATIONS=_renderer.SCRIPT_LOCATIONS;launchServer.getDefaultCspSettings=_server.getDefaultCspSettings;launchServer.errors=_utils.errors;
130
+ ops.logger??=(0,_renderer.newDefaultLogger)({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await(0,_server.default)(webpackConfig,ops);let httpServer;if(ops.https){httpServer=_nodeHttps.default.createServer({cert:ops.https.cert,key:ops.https.key},expressServer)}else httpServer=_nodeHttp.default.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=(0,_lodash.isString)(ops.port)?`Pipe ${ops.port}`:`Port ${ops.port}`;/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();const bind=(0,_lodash.isString)(addr)?`pipe ${addr}`:`port ${addr.port}`;ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`)});httpServer.listen(ops.port);return{expressServer,httpServer}}launchServer.SCRIPT_LOCATIONS=_renderer.SCRIPT_LOCATIONS;launchServer.getDefaultCspSettings=_server.getDefaultCspSettings;launchServer.errors=_utils.errors;
131
131
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["require","_http","_interopRequireDefault","_https","_lodash","_server","_interopRequireWildcard","_renderer","_utils","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","undefined","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register';\n\nimport http from 'http';\nimport https from 'https';\n\nimport {\n cloneDeep,\n defaults,\n isFinite,\n isNumber,\n isString,\n toNumber,\n} from 'lodash';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport { errors, getDefaultCspSettings, type ServerT };\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String), or false.\n */\nfunction normalizePort(value: number | string) {\n const port = toNumber(value);\n if (isFinite(port)) return port; /* port number */\n if (!isNumber(port)) return value; /* named pipe */\n return false;\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport default async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n }> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\nlaunchServer.getDefaultCspSettings = getDefaultCspSettings;\nlaunchServer.errors = errors;\n"],"mappings":"mZACAA,OAAA,gCAEA,IAAAC,KAAA,CAAAC,sBAAA,CAAAF,OAAA,UACA,IAAAG,MAAA,CAAAD,sBAAA,CAAAF,OAAA,WAEA,IAAAI,OAAA,CAAAJ,OAAA,WAYAA,OAAA,iBAIA,IAAAK,OAAA,CAAAC,uBAAA,CAAAN,OAAA,cAMA,IAAAO,SAAA,CAAAP,OAAA,eAEA,IAAAQ,MAAA,CAAAR,OAAA,YAAiC,SAAAM,wBAAAG,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAL,uBAAA,SAAAA,CAAAG,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA,CAAAG,CAAA,CAAAD,CAAA,KAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,SAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,EAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,CAAAQ,CAAA,YAAAP,CAAA,IAAAD,CAAA,aAAAC,CAAA,KAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,CAAAC,CAAA,KAAAM,CAAA,EAAAD,CAAA,CAAAU,MAAA,CAAAC,cAAA,GAAAD,MAAA,CAAAE,wBAAA,CAAAlB,CAAA,CAAAC,CAAA,KAAAM,CAAA,CAAAK,GAAA,EAAAL,CAAA,CAAAM,GAAA,EAAAP,CAAA,CAAAE,CAAA,CAAAP,CAAA,CAAAM,CAAA,EAAAC,CAAA,CAAAP,CAAA,EAAAD,CAAA,CAAAC,CAAA,UAAAO,CAAA,GAAAR,CAAA,CAAAC,CAAA,EA9BjC;AAeA;AACA;AACA;AAwBA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAkB,aAAaA,CAACC,KAAsB,CAAE,CAC7C,KAAM,CAAAC,IAAI,CAAG,GAAAC,gBAAQ,EAACF,KAAK,CAAC,CAC5B,GAAI,GAAAG,gBAAQ,EAACF,IAAI,CAAC,CAAE,MAAO,CAAAA,IAAI,CAAE,iBACjC,GAAI,CAAC,GAAAG,gBAAQ,EAACH,IAAI,CAAC,CAAE,MAAO,CAAAD,KAAK,CAAE,gBACnC,MAAO,MACT,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACe,cAAe,CAAAK,YAAYA,CACxCC,aAA4B,CAC5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AA+B,CAAC,CACzD,MAAO,CAAApB,OAAO,CAACuB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,YAAY,CACfzB,GAAG,CAACO,MAAM,CAAEa,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC,CAC9C,MAAO,CAAApB,OAAO,CAACuB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,CAAAC,SAAS,CACd,QACE,KAAM,CAAAN,KACV,CACF,CAAC,CAAC,CAEF,iDACAP,UAAU,CAACM,EAAE,CAAC,WAAW,CAAE,IAAM,CAC/B,KAAM,CAAAQ,IAAI,CAAGd,UAAU,CAACe,OAAO,CAAC,CAAE,CAClC,KAAM,CAAAN,IAAI,CAAG,GAAAC,gBAAQ,EAACI,IAAI,CAAC,CAAG,QAAQA,IAAI,EAAE,CAAG,QAAQA,IAAI,CAAClC,IAAI,EAAE,CAClEO,GAAG,CAACO,MAAM,CAAEsB,IAAI,CAAC,uBAAuBP,IAAI,OAC1CpB,OAAO,CAACC,GAAG,CAAC2B,QAAQ,OAAO,CAC/B,CAAC,CAAC,CAEFjB,UAAU,CAACkB,MAAM,CAAC/B,GAAG,CAACP,IAAI,CAAC,CAE3B,MAAO,CACLkB,aAAa,CACbE,UACF,CACF,CAEAhB,YAAY,CAACmC,gBAAgB,CAAGA,0BAAgB,CAChDnC,YAAY,CAACoC,qBAAqB,CAAGA,6BAAqB,CAC1DpC,YAAY,CAACqC,MAAM,CAAGA,aAAM","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["require","_nodeHttp","_interopRequireDefault","_nodeHttps","_lodash","_server","_interopRequireWildcard","_renderer","_utils","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","undefined","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport {\n cloneDeep,\n defaults,\n isFinite,\n isNumber,\n isString,\n toNumber,\n} from 'lodash';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport { errors, getDefaultCspSettings, type ServerT };\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String), or false.\n */\nfunction normalizePort(value: number | string) {\n const port = toNumber(value);\n if (isFinite(port)) return port; /* port number */\n if (!isNumber(port)) return value; /* named pipe */\n return false;\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport default async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\nlaunchServer.getDefaultCspSettings = getDefaultCspSettings;\nlaunchServer.errors = errors;\n"],"mappings":"mZACAA,OAAA,gCAEA,IAAAC,SAAA,CAAAC,sBAAA,CAAAF,OAAA,eACA,IAAAG,UAAA,CAAAD,sBAAA,CAAAF,OAAA,gBAEA,IAAAI,OAAA,CAAAJ,OAAA,WAYAA,OAAA,iBAIA,IAAAK,OAAA,CAAAC,uBAAA,CAAAN,OAAA,cAMA,IAAAO,SAAA,CAAAP,OAAA,eAEA,IAAAQ,MAAA,CAAAR,OAAA,YAAiC,SAAAM,wBAAAG,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAL,uBAAA,SAAAA,CAAAG,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA,CAAAG,CAAA,CAAAD,CAAA,KAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,SAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,EAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,CAAAQ,CAAA,YAAAP,CAAA,IAAAD,CAAA,aAAAC,CAAA,KAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,CAAAC,CAAA,KAAAM,CAAA,EAAAD,CAAA,CAAAU,MAAA,CAAAC,cAAA,GAAAD,MAAA,CAAAE,wBAAA,CAAAlB,CAAA,CAAAC,CAAA,KAAAM,CAAA,CAAAK,GAAA,EAAAL,CAAA,CAAAM,GAAA,EAAAP,CAAA,CAAAE,CAAA,CAAAP,CAAA,CAAAM,CAAA,EAAAC,CAAA,CAAAP,CAAA,EAAAD,CAAA,CAAAC,CAAA,UAAAO,CAAA,GAAAR,CAAA,CAAAC,CAAA,EA9BjC;AAeA;AACA;AACA;AAwBA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAkB,aAAaA,CAACC,KAAsB,CAAE,CAC7C,KAAM,CAAAC,IAAI,CAAG,GAAAC,gBAAQ,EAACF,KAAK,CAAC,CAC5B,GAAI,GAAAG,gBAAQ,EAACF,IAAI,CAAC,CAAE,MAAO,CAAAA,IAAI,CAAE,iBACjC,GAAI,CAAC,GAAAG,gBAAQ,EAACH,IAAI,CAAC,CAAE,MAAO,CAAAD,KAAK,CAAE,gBACnC,MAAO,MACT,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACe,cAAe,CAAAK,YAAYA,CACxCC,aAA4B,CAC5BC,OAAiB,CAAG,CAAC,CAAC,CAIrB,CACD,4BACA,KAAM,CAAAC,GAAG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,CAAC,CACxB,IAAK,YAAY,CACfzB,GAAG,CAACO,MAAM,CAAEa,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC,CAC9C,MAAO,CAAApB,OAAO,CAACuB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,CAAAC,SAAS,CACd,QACE,KAAM,CAAAN,KACV,CACF,CAAC,CAAC,CAEF,iDACAP,UAAU,CAACM,EAAE,CAAC,WAAW,CAAE,IAAM,CAC/B,KAAM,CAAAQ,IAAI,CAAGd,UAAU,CAACe,OAAO,CAAC,CAAE,CAClC,KAAM,CAAAN,IAAI,CAAG,GAAAC,gBAAQ,EAACI,IAAI,CAAC,CAAG,QAAQA,IAAI,EAAE,CAAG,QAAQA,IAAI,CAAClC,IAAI,EAAE,CAClEO,GAAG,CAACO,MAAM,CAAEsB,IAAI,CAAC,uBAAuBP,IAAI,OAC1CpB,OAAO,CAACC,GAAG,CAAC2B,QAAQ,OAAO,CAC/B,CAAC,CAAC,CAEFjB,UAAU,CAACkB,MAAM,CAAC/B,GAAG,CAACP,IAAI,CAAC,CAE3B,MAAO,CACLkB,aAAa,CACbE,UACF,CACF,CAEAhB,YAAY,CAACmC,gBAAgB,CAAGA,0BAAgB,CAChDnC,YAAY,CAACoC,qBAAqB,CAAGA,6BAAqB,CAC1DpC,YAAY,CAACqC,MAAM,CAAGA,aAAM","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ServerSsrContext=exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _stream=require("stream");var _zlib=require("zlib");var _winston=_interopRequireDefault(require("winston"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _jsUtils=require("@dr.pogodin/js-utils");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _static=require("react-dom/static");var _reactHelmet=require("@dr.pogodin/react-helmet");var _reactRouter=require("react-router");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _buildInfo=require("../shared/utils/isomorphy/buildInfo");var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ServerSsrContext=exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _nodeFs=_interopRequireDefault(require("node:fs"));var _nodePath=_interopRequireDefault(require("node:path"));var _nodeStream=require("node:stream");var _nodeZlib=require("node:zlib");var _winston=_interopRequireDefault(require("winston"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _jsUtils=require("@dr.pogodin/js-utils");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _static=require("react-dom/static");var _reactHelmet=require("@dr.pogodin/react-helmet");var _reactRouter=require("react-router");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _buildInfo=require("../shared/utils/isomorphy/buildInfo");var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
2
2
  * ExpressJS middleware for server-side rendering of a ReactJS app.
3
3
  */const sanitizedConfig=(0,_lodash.omit)(_config.default,"SECRET");// Note: These type definitions for logger are copied from Winston logger,
4
4
  // then simplified to make it easier to fit an alternative logger into this
@@ -14,14 +14,14 @@ let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCAT
14
14
  * suitable for cryptographical use.
15
15
  * @param context Webpack context path used during the build.
16
16
  * @return Resolves to the build-time information.
17
- */function getBuildInfo(context){const url=_path.default.resolve(context,".build-info");return JSON.parse(_fs.default.readFileSync(url,"utf8"))}/**
17
+ */function getBuildInfo(context){const url=_nodePath.default.resolve(context,".build-info");return JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}/**
18
18
  * Attempts to read from disk the named chunk groups mapping generated
19
19
  * by Webpack during the compilation.
20
20
  * It will not work for development builds, where these stats should be captured
21
21
  * via compilator callback.
22
22
  * @param buildDir
23
23
  * @return
24
- */function readChunkGroupsJson(buildDir){const url=_path.default.resolve(buildDir,"__chunk_groups__.json");let res;try{res=JSON.parse(_fs.default.readFileSync(url,"utf8"))}catch{// TODO: Should we message the error here somehow?
24
+ */function readChunkGroupsJson(buildDir){const url=_nodePath.default.resolve(buildDir,"__chunk_groups__.json");let res;try{res=JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}catch{// TODO: Should we message the error here somehow?
25
25
  res=null}return res}/**
26
26
  * Prepares a new Cipher for data encryption.
27
27
  * @param key Encryption key (32-bit random key is expected, see
@@ -85,11 +85,11 @@ res=null}return res}/**
85
85
  // server function, and this initialization is for testing uses, where
86
86
  // renderer is imported directly.
87
87
  ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);(0,_buildInfo.setBuildInfo)(buildInfo);// publicPath from webpack.output has a trailing slash at the end.
88
- const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=_fs.default.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
88
+ const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=_nodeFs.default.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
89
89
  const cache=ops.staticCacheController?new _Cache.default(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
90
90
  // eslint-disable-next-line complexity
91
91
  return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
92
- res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer)}else{await new Promise((done,failed)=>{(0,_zlib.brotliDecompress)(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
92
+ res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer)}else{await new Promise((done,failed)=>{(0,_nodeZlib.brotliDecompress)(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
93
93
  // .replaceAll() method instead relying on reg. expression for
94
94
  // global matching.
95
95
  const regex=new RegExp(buffer.nonce,"g");// TODO: It should be implemented more careful.
@@ -110,7 +110,7 @@ let error;const resolve=arg=>{if(error!==undefined)throw Error("Internal error")
110
110
  const helmetContext={};void(0,_static.prerenderToNodeStream)(/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactRouter.StaticRouter,{location:req.url,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactHelmet.HelmetProvider,{context:helmetContext,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(App2,{})})})}),{onError:reject}).then(result=>{({helmet}=helmetContext);resolve(result.prelude)}).catch(reject)});let ssrRound=0;let bailed=false;for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),(0,_jsUtils.timer)(timeout).then(()=>false)]));if(bailed)break}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
111
111
  // to ensure the correct hydration when some pending promises have
112
112
  // resolved and placed their data into the initial global state.
113
- stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return}await new Promise(ready=>{stream.pipe(new _stream.Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done()}}))})}/* Encrypts data to be injected into HTML.
113
+ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return}await new Promise(ready=>{stream.pipe(new _nodeStream.Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done()}}))})}/* Encrypts data to be injected into HTML.
114
114
  * Keep in mind, that this encryption is no way secure: as the JS bundle
115
115
  * contains decryption key and is able to decode it at the client side.
116
116
  * Hovewer, for a number of reasons, encryption of injected data is still
@@ -149,7 +149,7 @@ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} s
149
149
  </body>
150
150
  </html>`;const status=ssrContext.status||200;if(status!==200)res.status(status);if(cacheRef&&status<500){// Note: waiting for the caching to complete is not strictly necessary,
151
151
  // but it greately simplifies testing, and error reporting.
152
- await new Promise((done,failed)=>{(0,_zlib.brotliCompress)(html,(error,buffer)=>{const b=buffer;if(error)failed(error);else{b.nonce=req.nonce;cache.add({buffer:b,status},cacheRef.key,buffer.length);done()}})})}// Note: as caching code above may throw in some cases, sending response
152
+ await new Promise((done,failed)=>{(0,_nodeZlib.brotliCompress)(html,(error,buffer)=>{const b=buffer;if(error)failed(error);else{b.nonce=req.nonce;cache.add({buffer:b,status},cacheRef.key,buffer.length);done()}})})}// Note: as caching code above may throw in some cases, sending response
153
153
  // before it completes will likely hide the error, making it difficult
154
154
  // to debug. Thus, at least for now, lets send response after it.
155
155
  res.send(html)}catch(error){next(error)}}}