@dr.pogodin/react-utils 1.40.2 → 1.40.4
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.
- package/build/development/client/init.js +1 -1
- package/build/development/client/init.js.map +1 -1
- package/build/development/server/renderer.js +1 -1
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +26 -14
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +3 -1
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/utils/isomorphy/buildInfo.js +4 -0
- package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/style.css +21 -0
- package/build/development/web.bundle.js +6 -6
- package/build/production/client/getInj.js +1 -1
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +2 -2
- package/build/production/client/init.js.map +1 -1
- package/build/production/server/index.js +1 -1
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/server.js +3 -3
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +5 -5
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js +1 -1
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Link.js +1 -1
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +2 -2
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +1 -1
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +6 -6
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/utils/isomorphy/buildInfo.js +3 -0
- package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +2 -2
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/global.js +1 -1
- package/build/production/shared/utils/jest/global.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +1 -1
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +3 -3
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/style.css +1 -1
- package/build/production/style.css.map +1 -1
- package/build/production/web.bundle.js +1 -1
- package/build/production/web.bundle.js.map +1 -1
- package/build/types-code/shared/components/Checkbox/index.d.ts +6 -4
- package/build/types-code/shared/components/Modal/index.d.ts +1 -0
- package/build/types-code/shared/utils/isomorphy/buildInfo.d.ts +0 -3
- package/build/types-scss/src/shared/components/Checkbox/theme.scss.d.ts +2 -0
- package/package.json +21 -21
- package/src/client/init.ts +3 -1
- package/src/shared/components/Checkbox/index.tsx +36 -16
- package/src/shared/components/Checkbox/theme.scss +20 -0
- package/src/shared/components/Modal/index.tsx +6 -0
- package/src/shared/utils/isomorphy/buildInfo.ts +4 -6
- package/src/shared/utils/splitComponent.tsx +3 -3
|
@@ -566,6 +566,17 @@ body {
|
|
|
566
566
|
border-color: blue;
|
|
567
567
|
box-shadow: 0 0 3px 1px lightblue;
|
|
568
568
|
}
|
|
569
|
+
*.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___indeterminate___N9bCb8::after,
|
|
570
|
+
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___context___dNQcC6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___indeterminate___N9bCb8::after,
|
|
571
|
+
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___ad___earXxa.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___hoc___qAPfQ6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___indeterminate___N9bCb8::after {
|
|
572
|
+
background: black;
|
|
573
|
+
border-radius: 0.2em;
|
|
574
|
+
content: "";
|
|
575
|
+
display: block;
|
|
576
|
+
height: 0.2em;
|
|
577
|
+
margin: 0.6em 0.2em;
|
|
578
|
+
width: 1em;
|
|
579
|
+
}
|
|
569
580
|
*.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___container___Kr0g3M,
|
|
570
581
|
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___context___dNQcC6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___container___Kr0g3M,
|
|
571
582
|
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___ad___earXxa.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___hoc___qAPfQ6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___container___Kr0g3M {
|
|
@@ -578,6 +589,16 @@ body {
|
|
|
578
589
|
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___ad___earXxa.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___hoc___qAPfQ6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___label___3dML-O {
|
|
579
590
|
margin: 0 0.6em 0 1.5em;
|
|
580
591
|
}
|
|
592
|
+
*.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___disabled___EzQra1,
|
|
593
|
+
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___context___dNQcC6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___disabled___EzQra1,
|
|
594
|
+
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___ad___earXxa.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___hoc___qAPfQ6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___disabled___EzQra1 {
|
|
595
|
+
opacity: 0.33;
|
|
596
|
+
}
|
|
597
|
+
*.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___disabled___EzQra1 .-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ,
|
|
598
|
+
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___context___dNQcC6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___disabled___EzQra1 .-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ,
|
|
599
|
+
.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___ad___earXxa.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___hoc___qAPfQ6.-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___disabled___EzQra1 .-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ {
|
|
600
|
+
cursor: not-allowed !important;
|
|
601
|
+
}
|
|
581
602
|
/*!**********************************************************************************************************************************************************************************************************************************************************************************************************!*\
|
|
582
603
|
!*** css ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./src/shared/components/Input/theme.scss ***!
|
|
583
604
|
\**********************************************************************************************************************************************************************************************************************************************************************************************************/
|
|
@@ -66,7 +66,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
|
|
|
66
66
|
\**************************************************/
|
|
67
67
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
68
68
|
|
|
69
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @dr.pogodin/react-themes */ \"@dr.pogodin/react-themes\");\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _theme_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./theme.scss */ \"./src/shared/components/Checkbox/theme.scss\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n\n\n\nconst Checkbox = _ref => {\n let {\n checked,\n label,\n onChange,\n theme\n } = _ref;\n return /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsxs)(\"div\", {\n className:
|
|
69
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @dr.pogodin/react-themes */ \"@dr.pogodin/react-themes\");\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _theme_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./theme.scss */ \"./src/shared/components/Checkbox/theme.scss\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n\n\n\nconst Checkbox = _ref => {\n let {\n checked,\n disabled,\n label,\n onChange,\n testId,\n theme\n } = _ref;\n let containerClassName = theme.container;\n if (disabled) containerClassName += ` ${theme.disabled}`;\n let checkboxClassName = theme.checkbox;\n if (checked === 'indeterminate') checkboxClassName += ` ${theme.indeterminate}`;\n return /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsxs)(\"div\", {\n className: containerClassName,\n children: [label === undefined ? null : /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(\"div\", {\n className: theme.label,\n children: label\n }), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(\"input\", {\n checked: checked === undefined ? undefined : checked === true,\n className: checkboxClassName,\n \"data-testid\": false ? 0 : testId,\n disabled: disabled,\n onChange: onChange,\n onClick: e => e.stopPropagation(),\n type: \"checkbox\"\n })]\n });\n};\n/* harmony default export */ __webpack_exports__[\"default\"] = (_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0___default()(Checkbox, 'Checkbox', _theme_scss__WEBPACK_IMPORTED_MODULE_1__[\"default\"]));\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/components/Checkbox/index.tsx?");
|
|
70
70
|
|
|
71
71
|
/***/ }),
|
|
72
72
|
|
|
@@ -116,7 +116,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var reac
|
|
|
116
116
|
\***********************************************/
|
|
117
117
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
118
118
|
|
|
119
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseModal: function() { return /* binding */ BaseModal; }\n/* harmony export */ });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"react\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ \"react-dom\");\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @dr.pogodin/react-themes */ \"@dr.pogodin/react-themes\");\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _base_theme_scss__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base-theme.scss */ \"./src/shared/components/Modal/base-theme.scss\");\n/* harmony import */ var _styles_scss__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./styles.scss */ \"./src/shared/components/Modal/styles.scss\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n/* global document */\n\n\n\n\n\n\n\n/**\n * The `<Modal>` component implements a simple themeable modal window, wrapped\n * into the default theme. `<BaseModal>` exposes the base non-themed component.\n * **Children:** Component children are rendered as the modal content.\n * @param {object} props Component properties. Beside props documented below,\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.\n * @param {function} [props.onCancel] The callback to trigger when user\n * clicks outside the modal, or presses Escape. It is expected to hide the\n * modal.\n * @param {ModalTheme} [props.theme] _Ad hoc_ theme.\n */\nconst BaseModal = _ref => {\n let {\n cancelOnScrolling,\n children,\n containerStyle,\n dontDisableScrolling,\n onCancel,\n style,\n testId,\n theme\n } = _ref;\n const containerRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);\n const overlayRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);\n const [portal, setPortal] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)();\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {\n const p = document.createElement('div');\n document.body.appendChild(p);\n setPortal(p);\n return () => {\n document.body.removeChild(p);\n };\n }, []);\n\n // Sets up modal cancellation of scrolling, if opted-in.\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {\n if (cancelOnScrolling && onCancel) {\n window.addEventListener('scroll', onCancel);\n window.addEventListener('wheel', onCancel);\n }\n return () => {\n if (cancelOnScrolling && onCancel) {\n window.removeEventListener('scroll', onCancel);\n window.removeEventListener('wheel', onCancel);\n }\n };\n }, [cancelOnScrolling, onCancel]);\n\n // Disables window scrolling, if it is not opted-out.\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {\n if (!dontDisableScrolling) {\n document.body.classList.add(_styles_scss__WEBPACK_IMPORTED_MODULE_4__[\"default\"].scrollingDisabledByModal);\n }\n return () => {\n if (!dontDisableScrolling) {\n document.body.classList.remove(_styles_scss__WEBPACK_IMPORTED_MODULE_4__[\"default\"].scrollingDisabledByModal);\n }\n };\n }, [dontDisableScrolling]);\n const focusLast = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)(\"div\", {\n onFocus: () => {\n var _containerRef$current, _overlayRef$current;\n const elems = (_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.querySelectorAll('*');\n for (let i = elems.length - 1; i >= 0; --i) {\n var _elems$i;\n (_elems$i = elems[i]) === null || _elems$i === void 0 || _elems$i.focus();\n if (document.activeElement === elems[i]) return;\n }\n (_overlayRef$current = overlayRef.current) === null || _overlayRef$current === void 0 || _overlayRef$current.focus();\n }\n /* eslint-disable jsx-a11y/no-noninteractive-tabindex */,\n tabIndex: 0\n /* eslint-enable jsx-a11y/no-noninteractive-tabindex */\n }), []);\n return portal ? /*#__PURE__*/react_dom__WEBPACK_IMPORTED_MODULE_1___default().createPortal(
|
|
119
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseModal: function() { return /* binding */ BaseModal; }\n/* harmony export */ });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"react\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ \"react-dom\");\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @dr.pogodin/react-themes */ \"@dr.pogodin/react-themes\");\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _base_theme_scss__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base-theme.scss */ \"./src/shared/components/Modal/base-theme.scss\");\n/* harmony import */ var _styles_scss__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./styles.scss */ \"./src/shared/components/Modal/styles.scss\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n/* global document */\n\n\n\n\n\n\n\n/**\n * The `<Modal>` component implements a simple themeable modal window, wrapped\n * into the default theme. `<BaseModal>` exposes the base non-themed component.\n * **Children:** Component children are rendered as the modal content.\n * @param {object} props Component properties. Beside props documented below,\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.\n * @param {function} [props.onCancel] The callback to trigger when user\n * clicks outside the modal, or presses Escape. It is expected to hide the\n * modal.\n * @param {ModalTheme} [props.theme] _Ad hoc_ theme.\n */\nconst BaseModal = _ref => {\n let {\n cancelOnScrolling,\n children,\n containerStyle,\n dontDisableScrolling,\n onCancel,\n style,\n testId,\n testIdForOverlay,\n theme\n } = _ref;\n const containerRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);\n const overlayRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);\n const [portal, setPortal] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)();\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {\n const p = document.createElement('div');\n document.body.appendChild(p);\n setPortal(p);\n return () => {\n document.body.removeChild(p);\n };\n }, []);\n\n // Sets up modal cancellation of scrolling, if opted-in.\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {\n if (cancelOnScrolling && onCancel) {\n window.addEventListener('scroll', onCancel);\n window.addEventListener('wheel', onCancel);\n }\n return () => {\n if (cancelOnScrolling && onCancel) {\n window.removeEventListener('scroll', onCancel);\n window.removeEventListener('wheel', onCancel);\n }\n };\n }, [cancelOnScrolling, onCancel]);\n\n // Disables window scrolling, if it is not opted-out.\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {\n if (!dontDisableScrolling) {\n document.body.classList.add(_styles_scss__WEBPACK_IMPORTED_MODULE_4__[\"default\"].scrollingDisabledByModal);\n }\n return () => {\n if (!dontDisableScrolling) {\n document.body.classList.remove(_styles_scss__WEBPACK_IMPORTED_MODULE_4__[\"default\"].scrollingDisabledByModal);\n }\n };\n }, [dontDisableScrolling]);\n const focusLast = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)(\"div\", {\n onFocus: () => {\n var _containerRef$current, _overlayRef$current;\n const elems = (_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.querySelectorAll('*');\n for (let i = elems.length - 1; i >= 0; --i) {\n var _elems$i;\n (_elems$i = elems[i]) === null || _elems$i === void 0 || _elems$i.focus();\n if (document.activeElement === elems[i]) return;\n }\n (_overlayRef$current = overlayRef.current) === null || _overlayRef$current === void 0 || _overlayRef$current.focus();\n }\n /* eslint-disable jsx-a11y/no-noninteractive-tabindex */,\n tabIndex: 0\n /* eslint-enable jsx-a11y/no-noninteractive-tabindex */\n }), []);\n return portal ? /*#__PURE__*/react_dom__WEBPACK_IMPORTED_MODULE_1___default().createPortal(/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsxs)(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.Fragment, {\n children: [focusLast, /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)(\"div\", {\n \"aria-label\": \"Cancel\",\n className: theme.overlay,\n \"data-testid\": false ? 0 : testIdForOverlay,\n onClick: e => {\n if (onCancel) {\n onCancel();\n e.stopPropagation();\n }\n },\n onKeyDown: e => {\n if (e.key === 'Escape' && onCancel) {\n onCancel();\n e.stopPropagation();\n }\n },\n ref: node => {\n if (node && node !== overlayRef.current) {\n overlayRef.current = node;\n node.focus();\n }\n },\n role: \"button\",\n tabIndex: 0\n }), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)(\"div\", {\n \"aria-modal\": \"true\",\n className: theme.container,\n \"data-testid\": false ? 0 : testId,\n onClick: e => e.stopPropagation(),\n onWheel: event => event.stopPropagation(),\n ref: containerRef,\n role: \"dialog\",\n style: style !== null && style !== void 0 ? style : containerStyle,\n children: children\n }), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)(\"div\", {\n onFocus: () => {\n var _overlayRef$current2;\n (_overlayRef$current2 = overlayRef.current) === null || _overlayRef$current2 === void 0 || _overlayRef$current2.focus();\n }\n /* eslint-disable jsx-a11y/no-noninteractive-tabindex */,\n tabIndex: 0\n /* eslint-enable jsx-a11y/no-noninteractive-tabindex */\n }), focusLast]\n }), portal) : null;\n};\n/* harmony default export */ __webpack_exports__[\"default\"] = (_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_2___default()(BaseModal, 'Modal', _base_theme_scss__WEBPACK_IMPORTED_MODULE_3__[\"default\"]));\n\n/* Non-themed version of the Modal. */\n\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/components/Modal/index.tsx?");
|
|
120
120
|
|
|
121
121
|
/***/ }),
|
|
122
122
|
|
|
@@ -206,7 +206,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
|
|
|
206
206
|
\**************************************************************************/
|
|
207
207
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
208
208
|
|
|
209
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ areEqual: function() { return /* binding */ areEqual; }\n/* harmony export */ });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"react\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _Modal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Modal */ \"./src/shared/components/Modal/index.tsx\");\n/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./style.scss */ \"./src/shared/components/selectors/CustomDropdown/Options/style.scss\");\n/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../common */ \"./src/shared/components/selectors/common.ts\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n\n\n\n\n\nfunction areEqual(a, b) {\n return (a === null || a === void 0 ? void 0 : a.left) === (b === null || b === void 0 ? void 0 : b.left) && (a === null || a === void 0 ? void 0 : a.top) === (b === null || b === void 0 ? void 0 : b.top) && (a === null || a === void 0 ? void 0 : a.width) === (b === null || b === void 0 ? void 0 : b.width);\n}\nconst Options = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)((_ref, ref) => {\n let {\n containerClass,\n containerStyle,\n filter,\n onCancel,\n onChange,\n optionClass,\n options\n } = _ref;\n const opsRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, () => ({\n measure: () => {\n var _opsRef$current, _opsRef$current2;\n const e = (_opsRef$current = opsRef.current) === null || _opsRef$current === void 0 ? void 0 : _opsRef$current.parentElement;\n if (!e) return undefined;\n const rect = (_opsRef$current2 = opsRef.current) === null || _opsRef$current2 === void 0 ? void 0 : _opsRef$current2.getBoundingClientRect();\n const style = window.getComputedStyle(e);\n const mBottom = parseFloat(style.marginBottom);\n const mTop = parseFloat(style.marginTop);\n rect.height += mBottom + mTop;\n return rect;\n }\n }), []);\n const optionNodes = [];\n for (let i = 0; i < options.length; ++i) {\n const option = options[i];\n if (option !== undefined && (!filter || filter(option))) {\n const [iValue, iName] = (0,_common__WEBPACK_IMPORTED_MODULE_3__.optionValueName)(option);\n optionNodes.push(
|
|
209
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ areEqual: function() { return /* binding */ areEqual; }\n/* harmony export */ });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"react\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _Modal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Modal */ \"./src/shared/components/Modal/index.tsx\");\n/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./style.scss */ \"./src/shared/components/selectors/CustomDropdown/Options/style.scss\");\n/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../common */ \"./src/shared/components/selectors/common.ts\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n\n\n\n\n\nfunction areEqual(a, b) {\n return (a === null || a === void 0 ? void 0 : a.left) === (b === null || b === void 0 ? void 0 : b.left) && (a === null || a === void 0 ? void 0 : a.top) === (b === null || b === void 0 ? void 0 : b.top) && (a === null || a === void 0 ? void 0 : a.width) === (b === null || b === void 0 ? void 0 : b.width);\n}\nconst Options = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)((_ref, ref) => {\n let {\n containerClass,\n containerStyle,\n filter,\n onCancel,\n onChange,\n optionClass,\n options\n } = _ref;\n const opsRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, () => ({\n measure: () => {\n var _opsRef$current, _opsRef$current2;\n const e = (_opsRef$current = opsRef.current) === null || _opsRef$current === void 0 ? void 0 : _opsRef$current.parentElement;\n if (!e) return undefined;\n const rect = (_opsRef$current2 = opsRef.current) === null || _opsRef$current2 === void 0 ? void 0 : _opsRef$current2.getBoundingClientRect();\n const style = window.getComputedStyle(e);\n const mBottom = parseFloat(style.marginBottom);\n const mTop = parseFloat(style.marginTop);\n rect.height += mBottom + mTop;\n return rect;\n }\n }), []);\n const optionNodes = [];\n for (let i = 0; i < options.length; ++i) {\n const option = options[i];\n if (option !== undefined && (!filter || filter(option))) {\n const [iValue, iName] = (0,_common__WEBPACK_IMPORTED_MODULE_3__.optionValueName)(option);\n optionNodes.push(/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)(\"div\", {\n className: optionClass,\n onClick: e => {\n onChange(iValue);\n e.stopPropagation();\n },\n onKeyDown: e => {\n if (e.key === 'Enter') {\n onChange(iValue);\n e.stopPropagation();\n }\n },\n role: \"button\",\n tabIndex: 0,\n children: iName\n }, iValue));\n }\n }\n return /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)(_Modal__WEBPACK_IMPORTED_MODULE_1__.BaseModal\n // Closes the dropdown (cancels the selection) on any page scrolling attempt.\n // This is the same native <select> elements do on scrolling, and at least for\n // now we have no reason to deal with complications needed to support open\n // dropdowns during the scrolling (that would need to re-position it in\n // response to the position changes of the root dropdown element).\n , {\n cancelOnScrolling: true,\n containerStyle: containerStyle,\n dontDisableScrolling: true,\n onCancel: onCancel,\n theme: {\n ad: '',\n hoc: '',\n container: containerClass,\n context: '',\n overlay: _style_scss__WEBPACK_IMPORTED_MODULE_2__[\"default\"].overlay\n },\n children: /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__.jsx)(\"div\", {\n ref: opsRef,\n children: optionNodes\n })\n });\n});\n/* harmony default export */ __webpack_exports__[\"default\"] = (Options);\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/components/selectors/CustomDropdown/Options/index.tsx?");
|
|
210
210
|
|
|
211
211
|
/***/ }),
|
|
212
212
|
|
|
@@ -226,7 +226,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var reac
|
|
|
226
226
|
\******************************************************************/
|
|
227
227
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
228
228
|
|
|
229
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @dr.pogodin/react-themes */ \"@dr.pogodin/react-themes\");\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _theme_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./theme.scss */ \"./src/shared/components/selectors/NativeDropdown/theme.scss\");\n/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../common */ \"./src/shared/components/selectors/common.ts\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n// Implements dropdown based on the native HTML <select> element.\n\n\n\n\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\n\nconst Dropdown = _ref => {\n let {\n filter,\n label,\n onChange,\n options,\n testId,\n theme,\n value\n } = _ref;\n if (!options) throw Error('Internal error');\n let isValidValue = false;\n const optionElements = [];\n for (let i = 0; i < options.length; ++i) {\n const option = options[i];\n if (option !== undefined && (!filter || filter(option))) {\n const [iValue, iName] = (0,_common__WEBPACK_IMPORTED_MODULE_2__.optionValueName)(option);\n isValidValue || (isValidValue = iValue === value);\n optionElements.push(
|
|
229
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @dr.pogodin/react-themes */ \"@dr.pogodin/react-themes\");\n/* harmony import */ var _dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _theme_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./theme.scss */ \"./src/shared/components/selectors/NativeDropdown/theme.scss\");\n/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../common */ \"./src/shared/components/selectors/common.ts\");\n/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react/jsx-runtime */ \"./node_modules/react/jsx-runtime.js\");\n// Implements dropdown based on the native HTML <select> element.\n\n\n\n\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\n\nconst Dropdown = _ref => {\n let {\n filter,\n label,\n onChange,\n options,\n testId,\n theme,\n value\n } = _ref;\n if (!options) throw Error('Internal error');\n let isValidValue = false;\n const optionElements = [];\n for (let i = 0; i < options.length; ++i) {\n const option = options[i];\n if (option !== undefined && (!filter || filter(option))) {\n const [iValue, iName] = (0,_common__WEBPACK_IMPORTED_MODULE_2__.optionValueName)(option);\n isValidValue || (isValidValue = iValue === value);\n optionElements.push(/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(\"option\", {\n className: theme.option,\n value: iValue,\n children: iName\n }, iValue));\n }\n }\n\n // NOTE: This element represents the current `value` when it does not match\n // any valid option. In Chrome, and some other browsers, we are able to hide\n // it from the opened dropdown; in others, e.g. Safari, the best we can do is\n // to show it as disabled.\n const hiddenOption = isValidValue ? null : /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(\"option\", {\n disabled: true,\n className: theme.hiddenOption,\n value: value,\n children: value\n }, \"__reactUtilsHiddenOption\");\n let selectClassName = theme.select;\n if (!isValidValue) selectClassName += ` ${theme.invalid}`;\n return /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)(\"div\", {\n className: theme.container,\n children: [label === undefined ? null : /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(\"div\", {\n className: theme.label,\n children: label\n }), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)(\"div\", {\n className: theme.dropdown,\n children: [/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsxs)(\"select\", {\n className: selectClassName,\n \"data-testid\": false ? 0 : testId,\n onChange: onChange,\n value: value,\n children: [hiddenOption, optionElements]\n }), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(\"div\", {\n className: theme.arrow\n })]\n })]\n });\n};\n/* harmony default export */ __webpack_exports__[\"default\"] = (_dr_pogodin_react_themes__WEBPACK_IMPORTED_MODULE_0___default()(Dropdown, 'Dropdown', _theme_scss__WEBPACK_IMPORTED_MODULE_1__[\"default\"]));\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/components/selectors/NativeDropdown/index.tsx?");
|
|
230
230
|
|
|
231
231
|
/***/ }),
|
|
232
232
|
|
|
@@ -296,7 +296,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
|
|
|
296
296
|
\*************************************************/
|
|
297
297
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
298
298
|
|
|
299
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getBuildInfo: function() { return /* binding */ getBuildInfo; },\n/* harmony export */ setBuildInfo: function() { return /* binding */ setBuildInfo; }\n/* harmony export */ });\n// Encapsulates access to \"Build Info\" data.\n\n// BEWARE: This should match the type of build info object generated by\n// Webpack build (see \"/config/webpack/app-base.js\"), and currently this\n// match is not checked automatically.\n\nlet buildInfo;\n\n// On the client side \"BUILD_INFO\" should be injected by Webpack. Note, however,\n// that in test environment we may need situations were environment is mocked as\n// client-side, although no proper Webpack compilation is executed, thus no info\n// injected; because of this we don't do a hard environment check here.\nif (typeof window.__DEV_BUILD_INFO__ !== 'undefined') buildInfo = window.__DEV_BUILD_INFO__;\n\n/**\n * In scenarious where \"BUILD_INFO\" is not injected by Webpack (server-side,\n * tests, etc.) we expect the host codebase to explicitly set it before it is\n * ever requested. As a precaution, this function throws if build info has been\n * set already, unless `force` flag is explicitly set.\n * @param info\n * @param force\n */\nfunction setBuildInfo(info) {\n let force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (buildInfo !== undefined && !force) {\n throw Error('\"Build Info\" is already initialized');\n }\n buildInfo = info;\n}\n\n/**\n * Returns \"Build Info\" object; throws if it has not been initialized yet.\n * @returns\n */\nfunction getBuildInfo() {\n if (buildInfo === undefined) {\n throw Error('\"Build Info\" has not been initialized yet');\n }\n return buildInfo;\n}\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/utils/isomorphy/buildInfo.ts?");
|
|
299
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getBuildInfo: function() { return /* binding */ getBuildInfo; },\n/* harmony export */ setBuildInfo: function() { return /* binding */ setBuildInfo; }\n/* harmony export */ });\n// Encapsulates access to \"Build Info\" data.\n\n// BEWARE: This should match the type of build info object generated by\n// Webpack build (see \"/config/webpack/app-base.js\"), and currently this\n// match is not checked automatically.\n\n// Depending on the build mode & environment, BUILD_INFO is either a global\n// variable defined at the app launch, or it is replaced by the actual value\n// by the Webpack build.\n\nlet buildInfo;\n\n// On the client side \"BUILD_INFO\" should be injected by Webpack. Note, however,\n// that in test environment we may need situations were environment is mocked as\n// client-side, although no proper Webpack compilation is executed, thus no info\n// injected; because of this we don't do a hard environment check here.\nif (typeof window.__DEV_BUILD_INFO__ !== 'undefined') buildInfo = window.__DEV_BUILD_INFO__;\n\n/**\n * In scenarious where \"BUILD_INFO\" is not injected by Webpack (server-side,\n * tests, etc.) we expect the host codebase to explicitly set it before it is\n * ever requested. As a precaution, this function throws if build info has been\n * set already, unless `force` flag is explicitly set.\n * @param info\n * @param force\n */\nfunction setBuildInfo(info) {\n let force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (buildInfo !== undefined && !force) {\n throw Error('\"Build Info\" is already initialized');\n }\n buildInfo = info;\n}\n\n/**\n * Returns \"Build Info\" object; throws if it has not been initialized yet.\n * @returns\n */\nfunction getBuildInfo() {\n if (buildInfo === undefined) {\n throw Error('\"Build Info\" has not been initialized yet');\n }\n return buildInfo;\n}\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/utils/isomorphy/buildInfo.ts?");
|
|
300
300
|
|
|
301
301
|
/***/ }),
|
|
302
302
|
|
|
@@ -366,7 +366,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n// extracted by mini-css-extr
|
|
|
366
366
|
\***************************************************/
|
|
367
367
|
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
368
368
|
|
|
369
|
-
eval("__webpack_require__.r(__webpack_exports__);\n// extracted by mini-css-extract-plugin\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\"checkbox\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ\",\"context\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___context___dNQcC6\",\"ad\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___ad___earXxa\",\"hoc\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___hoc___qAPfQ6\",\"container\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___container___Kr0g3M\",\"label\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___label___3dML-O\"});\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/components/Checkbox/theme.scss?");
|
|
369
|
+
eval("__webpack_require__.r(__webpack_exports__);\n// extracted by mini-css-extract-plugin\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\"checkbox\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___checkbox___A-f8qJ\",\"context\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___context___dNQcC6\",\"ad\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___ad___earXxa\",\"hoc\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___hoc___qAPfQ6\",\"indeterminate\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___indeterminate___N9bCb8\",\"container\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___container___Kr0g3M\",\"label\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___label___3dML-O\",\"disabled\":\"-dr-pogodin-react-utils___src-shared-components-Checkbox-theme___disabled___EzQra1\"});\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/shared/components/Checkbox/theme.scss?");
|
|
370
370
|
|
|
371
371
|
/***/ }),
|
|
372
372
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=getInj;var _forge=_interopRequireDefault(require("node-forge/lib/forge"));require("node-forge/lib/aes");var _buildInfo=require("../shared/utils/isomorphy/buildInfo");// Encapsulates retrieval of server-side data injection into HTML template.
|
|
2
|
-
/* global document
|
|
2
|
+
/* global document */// Note: this way, only required part of "node-forge": AES, and some utils,
|
|
3
3
|
// is bundled into client-side code.
|
|
4
4
|
// Safeguard is needed here, because the server-side version of Docusaurus docs
|
|
5
5
|
// is compiled (at least now) with settings suggesting it is a client-side
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInj.js","names":["_forge","_interopRequireDefault","require","_buildInfo","inj","metaElement","document","querySelector","remove","data","forge","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document !== 'undefined'\n ? document.querySelector('meta[itemprop=\"drpruinj\"]') : null;\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n inj = eval(`(${data})`); // eslint-disable-line no-eval\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":"gLAMA,IAAAA,MAAA,CAAAC,sBAAA,CAAAC,OAAA,0BACAA,OAAA,uBAIA,IAAAC,UAAA,CAAAD,OAAA,wCAXA;AAEA,
|
|
1
|
+
{"version":3,"file":"getInj.js","names":["_forge","_interopRequireDefault","require","_buildInfo","inj","metaElement","document","querySelector","remove","data","forge","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document !== 'undefined'\n ? document.querySelector('meta[itemprop=\"drpruinj\"]') : null;\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n inj = eval(`(${data})`); // eslint-disable-line no-eval\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":"gLAMA,IAAAA,MAAA,CAAAC,sBAAA,CAAAC,OAAA,0BACAA,OAAA,uBAIA,IAAAC,UAAA,CAAAD,OAAA,wCAXA;AAEA,qBAEA;AACA;AAQA;AACA;AACA;AACA,GAAI,CAAAE,GAAS,CAAG,CAAC,CAAC,CAElB,KAAM,CAAAC,WAAmC,CAAG,MAAO,CAAAC,QAAQ,GAAK,WAAW,CACvEA,QAAQ,CAACC,aAAa,CAAC,6BAA2B,CAAC,CAAG,IAAI,CAE9D,GAAIF,WAAW,CAAE,CACfA,WAAW,CAACG,MAAM,CAAC,CAAC,CACpB,GAAI,CAAAC,IAAI,CAAGC,cAAK,CAACC,IAAI,CAACC,QAAQ,CAACP,WAAW,CAACQ,OAAO,CAAC,CAEnD,KAAM,CAAEC,GAAI,CAAC,CAAG,GAAAC,uBAAY,EAAC,CAAC,CAC9B,KAAM,CAAAC,CAAC,CAAGN,cAAK,CAACO,MAAM,CAACC,cAAc,CAAC,SAAS,CAAEJ,GAAG,CAAC,CACrDE,CAAC,CAACG,KAAK,CAAC,CAAEC,EAAE,CAAEX,IAAI,CAACY,KAAK,CAAC,CAAC,CAAEP,GAAG,CAACQ,MAAM,CAAE,CAAC,CAAC,CAC1CN,CAAC,CAACO,MAAM,CAACb,cAAK,CAACC,IAAI,CAACa,YAAY,CAACf,IAAI,CAACY,KAAK,CAACP,GAAG,CAACQ,MAAM,CAAC,CAAC,CAAC,CACzDN,CAAC,CAACS,MAAM,CAAC,CAAC,CAEVhB,IAAI,CAAGC,cAAK,CAACC,IAAI,CAACe,UAAU,CAACV,CAAC,CAACW,MAAM,CAAClB,IAAI,CAAC,CAC3CL,GAAG,CAAGwB,IAAI,CAAC,IAAInB,IAAI,GAAG,CAAC,CAAE;AAC3B,CAAC,IAAM,IAAI,MAAO,CAAAoB,MAAM,GAAK,WAAW,EAAIA,MAAM,CAACC,qBAAqB,CAAE,CACxE1B,GAAG,CAAGyB,MAAM,CAACC,qBAAqB,CAClC,MAAO,CAAAD,MAAM,CAACC,qBAChB,CAAC,IAAM,CACL;AACA;AACA;AACA1B,GAAG,CAAG,CAAC,CACT,CAEe,QAAS,CAAA2B,MAAMA,CAAA,CAAS,CACrC,MAAO,CAAA3B,GACT","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=Launch;require("react");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _client=require("react-dom/client");var _reactRouterDom=require("react-router-dom");var _getInj=_interopRequireDefault(require("./getInj"));var _jsxRuntime=require("react/jsx-runtime");// Initialization of client-side code.
|
|
2
|
-
/* global document
|
|
2
|
+
/* global document *//**
|
|
3
3
|
* Prepares and launches the app at client side.
|
|
4
4
|
* @param Application Root application component
|
|
5
5
|
* @param [options={}] Optional. Additional settings.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["require","_reactGlobalState","_client","_reactRouterDom","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","arguments","length","undefined","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","future","v7_relativeSplatPath","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport { type ComponentType } from 'react';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: any;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n) {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE || options.initialState}>\n <BrowserRouter future={{ v7_relativeSplatPath: true }}>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"gLAGAA,OAAA,UAEA,IAAAC,iBAAA,CAAAD,OAAA,mCAEA,IAAAE,OAAA,CAAAF,OAAA,qBACA,IAAAG,eAAA,CAAAH,OAAA,qBAEA,IAAAI,OAAA,CAAAC,sBAAA,CAAAL,OAAA,cAA8B,IAAAM,WAAA,CAAAN,OAAA,sBAV9B;AACA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["require","_reactGlobalState","_client","_reactRouterDom","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","arguments","length","undefined","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","future","v7_relativeSplatPath","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport { type ComponentType } from 'react';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: any;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n) {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE || options.initialState}>\n <BrowserRouter future={{ v7_relativeSplatPath: true }}>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"gLAGAA,OAAA,UAEA,IAAAC,iBAAA,CAAAD,OAAA,mCAEA,IAAAE,OAAA,CAAAF,OAAA,qBACA,IAAAG,eAAA,CAAAH,OAAA,qBAEA,IAAAI,OAAA,CAAAC,sBAAA,CAAAL,OAAA,cAA8B,IAAAM,WAAA,CAAAN,OAAA,sBAV9B;AACA,qBAgBA;AACA;AACA;AACA;AACA,GACe,QAAS,CAAAO,MAAMA,CAC5BC,WAA0B,CAE1B,IADA,CAAAC,OAAiB,CAAAC,SAAA,CAAAC,MAAA,IAAAD,SAAA,MAAAE,SAAA,CAAAF,SAAA,IAAG,CAAC,CAAC,CAEtB,KAAM,CAAAG,SAAS,CAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC,CACvD,GAAI,CAACF,SAAS,CAAE,KAAM,CAAAG,KAAK,CAAC,wCAAwC,CAAC,CACrE,KAAM,CAAAC,KAAK,cACT,GAAAX,WAAA,CAAAY,GAAA,EAACjB,iBAAA,CAAAkB,mBAAmB,EAACC,YAAY,CAAE,GAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,EAAIb,OAAO,CAACW,YAAa,CAAAG,QAAA,cACzE,GAAAjB,WAAA,CAAAY,GAAA,EAACf,eAAA,CAAAqB,aAAa,EAACC,MAAM,CAAE,CAAEC,oBAAoB,CAAE,IAAK,CAAE,CAAAH,QAAA,cACpD,GAAAjB,WAAA,CAAAY,GAAA,EAACV,WAAW,GAAE,CAAC,CACF,CAAC,CACG,CACtB,CAED,GAAIC,OAAO,CAACkB,WAAW,CAAE,CACvB,KAAM,CAAAC,IAAI,CAAG,GAAAC,kBAAU,EAAChB,SAAS,CAAC,CAClCe,IAAI,CAACE,MAAM,CAACb,KAAK,CACnB,CAAC,IAAM,GAAAc,mBAAW,EAAClB,SAAS,CAAEI,KAAK,CACrC","ignoreList":[]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";var _buildInfo=require("../shared/utils/isomorphy/buildInfo");/**
|
|
2
2
|
* Initialization of client-side environment.
|
|
3
|
-
|
|
3
|
+
*//* global window */const buildInfo=(0,_buildInfo.getBuildInfo)();// TODO: Should be moved into buildInfo module?
|
|
4
4
|
if(process.env.NODE_ENV!=="production"){// eslint-disable-next-line no-console
|
|
5
5
|
console.warn("Dev mode: \"BUILD_INFO\" attached to the global \"window\"");// eslint-disable-next-line no-underscore-dangle
|
|
6
|
-
window.__DEV_BUILD_INFO__=BUILD_INFO}/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`.
|
|
6
|
+
window.__DEV_BUILD_INFO__=BUILD_INFO}/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. *//* eslint-disable no-console */const{useServiceWorker}=buildInfo;if(useServiceWorker){const{navigator}=window;if("serviceWorker"in navigator){window.addEventListener("load",async()=>{try{// Note: no matter the "publicPath", we want to serve the service worker
|
|
7
7
|
// from the web app root, to allow it control any and all pages of the
|
|
8
8
|
// web app (otherwise, it will be restricted to the scope of its path).
|
|
9
9
|
// The server takes it into account.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global
|
|
1
|
+
{"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n interface Window {\n // eslint-disable-next-line @typescript-eslint/naming-convention, no-underscore-dangle\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\n/* eslint-disable no-console */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n console.log('SW registered:', reg);\n } catch (err) {\n console.log('SW registration failed:', err);\n }\n });\n }\n}\n/* eslint-enable no-console */\n"],"mappings":"aAMA,IAAAA,UAAA,CAAAC,OAAA,wCANA;AACA;AACA,GAEA,mBAIA,KAAM,CAAAC,SAAS,CAAG,GAAAC,uBAAY,EAAC,CAAC,CAEhC;AAUA,GAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACzC;AACAC,OAAO,CAACC,IAAI,CAAC,4DAAwD,CAAC,CACtE;AACAC,MAAM,CAACC,kBAAkB,CAAGC,UAC9B,CAEA,yEACA,+BACA,KAAM,CAAEC,gBAAiB,CAAC,CAAGV,SAAS,CACtC,GAAIU,gBAAgB,CAAE,CACpB,KAAM,CAAEC,SAAU,CAAC,CAAGJ,MAAM,CAC5B,GAAI,eAAe,EAAI,CAAAI,SAAS,CAAE,CAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,CAAE,SAAY,CAC1C,GAAI,CACF;AACA;AACA;AACA;AACA,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC,CACjDV,OAAO,CAACW,GAAG,CAAC,gBAAgB,CAAEH,GAAG,CACnC,CAAE,MAAOI,GAAG,CAAE,CACZZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,CAAEC,GAAG,CAC5C,CACF,CAAC,CACH,CACF,CACA","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");require("webpack");var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./utils");function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}/* Polyfill required by ReactJS.
|
|
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");require("webpack");var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./utils");function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}/* Polyfill required by ReactJS. *//**
|
|
2
2
|
* Normalizes a port into a number, string, or false.
|
|
3
3
|
* TODO: Drop this function?
|
|
4
4
|
* @param value Port name or number.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["require","_http","_interopRequireDefault","_https","_lodash","_server","_interopRequireWildcard","_renderer","_utils","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","undefined","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["import '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. */\nimport 'raf/polyfill';\n\nimport { type Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport { errors, getDefaultCspSettings };\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)` ⇒ `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` – the cache key for the response;\n * - `maxage?: number` – 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 {Promise<{ expressServer: object, httpServer: object }>} Resolves to\n * an object with created Express and HTTP servers.\n */\nexport default async function launchServer(webpackConfig: Configuration, options: OptionsT) {\n /* Options normalization. */\n const ops = options ? cloneDeep(options) : {};\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 if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\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);\n } else httpServer = http.createServer(expressServer);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as any).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 any).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 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":"mZAAAA,OAAA,gCAEA,IAAAC,KAAA,CAAAC,sBAAA,CAAAF,OAAA,UACA,IAAAG,MAAA,CAAAD,sBAAA,CAAAF,OAAA,WAEA,IAAAI,OAAA,CAAAJ,OAAA,WAUAA,OAAA,iBAEA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GACA,QAAS,CAAAW,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;AACA,GACe,cAAe,CAAAK,YAAYA,CAACC,aAA4B,CAAEC,OAAiB,CAAE,CAC1F,4BACA,KAAM,CAAAC,GAAG,CAAGD,OAAO,CAAG,GAAAE,iBAAS,EAACF,OAAO,CAAC,CAAG,CAAC,CAAC,CAC7CC,GAAG,CAACP,IAAI,CAAGF,aAAa,CAACS,GAAG,CAACP,IAAI,EAAIS,OAAO,CAACC,GAAG,CAACC,IAAI,EAAI,IAAI,CAAC,CAC9D,GAAAC,gBAAQ,EAACL,GAAG,CAAE,CAAEM,aAAa,CAAE,IAAK,CAAC,CAAC,CAEtC;A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P,UAAU,CAACM,EAAE,CAAC,WAAW,CAAE,IAAM,CAC/B,KAAM,CAAAO,IAAI,CAAGb,UAAU,CAACc,OAAO,CAAC,CAAE,CAClC,KAAM,CAAAL,IAAI,CAAG,GAAAC,gBAAQ,EAACG,IAAI,CAAC,CAAG,QAAQA,IAAI,EAAE,CAAG,QAAQA,IAAI,CAAClC,IAAI,EAAE,CAClEO,GAAG,CAACO,MAAM,CAAEsB,IAAI,CAAC,uBAAuBN,IAAI,OAC1CrB,OAAO,CAACC,GAAG,CAAC2B,QAAQ,OAAO,CAC/B,CAAC,CAAC,CAEFhB,UAAU,CAACiB,MAAM,CAAC/B,GAAG,CAACP,IAAI,CAAC,CAE3B,MAAO,CACLmB,aAAa,CACbE,UACF,CACF,CAEAjB,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","_http","_interopRequireDefault","_https","_lodash","_server","_interopRequireWildcard","_renderer","_utils","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","undefined","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["import '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. */\nimport 'raf/polyfill';\n\nimport { type Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport { errors, getDefaultCspSettings };\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)` ⇒ `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` – the cache key for the response;\n * - `maxage?: number` – 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 {Promise<{ expressServer: object, httpServer: object }>} Resolves to\n * an object with created Express and HTTP servers.\n */\nexport default async function launchServer(webpackConfig: Configuration, options: OptionsT) {\n /* Options normalization. */\n const ops = options ? cloneDeep(options) : {};\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 if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\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);\n } else httpServer = http.createServer(expressServer);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as any).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 any).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 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":"mZAAAA,OAAA,gCAEA,IAAAC,KAAA,CAAAC,sBAAA,CAAAF,OAAA,UACA,IAAAG,MAAA,CAAAD,sBAAA,CAAAF,OAAA,WAEA,IAAAI,OAAA,CAAAJ,OAAA,WAUAA,OAAA,iBAEAA,OAAA,YAEA,IAAAK,OAAA,CAAAC,uBAAA,CAAAN,OAAA,cAKA,IAAAO,SAAA,CAAAP,OAAA,eAEA,IAAAQ,MAAA,CAAAR,OAAA,YAAiC,SAAAS,yBAAAC,CAAA,wBAAAC,OAAA,iB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O,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;AACA,GACe,cAAe,CAAAK,YAAYA,CAACC,aAA4B,CAAEC,OAAiB,CAAE,CAC1F,4BACA,KAAM,CAAAC,GAAG,CAAGD,OAAO,CAAG,GAAAE,iBAAS,EAACF,OAAO,CAAC,CAAG,CAAC,CAAC,CAC7CC,GAAG,CAACP,IAAI,CAAGF,aAAa,CAACS,GAAG,CAACP,IAAI,EAAIS,OAAO,CAACC,GAAG,CAACC,IAAI,EAAI,IAAI,CAAC,CAC9D,GAAAC,gBAAQ,EAACL,GAAG,CAAE,CAAEM,aAAa,CAAE,IAAK,CAAC,CAAC,CAEtC;AACA;AACA,GAAIN,GAAG,CAACO,MAAM,GAAKC,SAAS,CAAE,CAC5BR,GAAG,CAACO,MAAM,CAAG,GAAAE,0BAAgB,EAAC,CAC5BC,eAAe,CAAEV,GAAG,CAACW,qBACvB,CAAC,CACH,CAEA,kD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CAAC,CAAG,QAAQA,IAAI,EAAE,CAAG,QAAQA,IAAI,CAAClC,IAAI,EAAE,CAClEO,GAAG,CAACO,MAAM,CAAEsB,IAAI,CAAC,uBAAuBN,IAAI,OAC1CrB,OAAO,CAACC,GAAG,CAAC2B,QAAQ,OAAO,CAC/B,CAAC,CAAC,CAEFhB,UAAU,CAACiB,MAAM,CAAC/B,GAAG,CAACP,IAAI,CAAC,CAE3B,MAAO,CACLmB,aAAa,CACbE,UACF,CACF,CAEAjB,YAAY,CAACmC,gBAAgB,CAAGA,0BAAgB,CAChDnC,YAAY,CAACoC,qBAAqB,CAAGA,6BAAqB,CAC1DpC,YAAY,CAACqC,MAAM,CAAGA,aAAM","ignoreList":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _path=require("path");var _url=require("url");var _lodash=require("lodash");var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _csurf=_interopRequireDefault(require("@dr.pogodin/csurf"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");require("webpack");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
|
|
2
2
|
* Creation of standard ExpressJS server for ReactJS apps.
|
|
3
|
-
|
|
3
|
+
*//**
|
|
4
4
|
* Default Content Security Policy settings.
|
|
5
5
|
* @ignore
|
|
6
6
|
*/const defaultCspSettings={directives:(0,_lodash.mapValues)(_helmet.default.contentSecurityPolicy.getDefaultDirectives(),// 'https:' options (automatic re-write of insecure URLs to secure ones)
|
|
@@ -38,11 +38,11 @@ write:options.logger.info.bind(options.logger)}}));// Note: no matter the "publi
|
|
|
38
38
|
// for special cases, but this will do for now.
|
|
39
39
|
server.get("/__service-worker.js",_express.default.static(webpackConfig.output?.path||"",{setHeaders:res=>res.set("Cache-Control","no-cache")}));/* Setup of Hot Module Reloading for development environment.
|
|
40
40
|
* These dependencies are not used, nor installed for production use,
|
|
41
|
-
* hence we should violate some import-related lint rules.
|
|
41
|
+
* hence we should violate some import-related lint rules. *//* eslint-disable global-require *//* eslint-disable import/no-extraneous-dependencies *//* eslint-disable import/no-unresolved */if(options.devMode){// This is a workaround for SASS bug:
|
|
42
42
|
// https://github.com/dart-lang/sdk/issues/27979
|
|
43
43
|
// which manifests itself sometimes when webpack dev middleware is used
|
|
44
44
|
// (in dev mode), and app modules are imported in some unfortunate ways.
|
|
45
|
-
if(!global.location){global.location={href:`${(0,_url.pathToFileURL)(process.cwd()).href}${_path.sep}`}}const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require
|
|
45
|
+
if(!global.location){global.location={href:`${(0,_url.pathToFileURL)(process.cwd()).href}${_path.sep}`}}const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require *//* eslint-enable import/no-extraneous-dependencies *//* eslint-enable import/no-unresolved */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next((0,_errors.newError)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
|
|
46
46
|
// what the default ExpressJS error handler does anyway, see:
|
|
47
47
|
// https://expressjs.com/en/guide/error-handling.html
|
|
48
48
|
//
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV","undefined"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\nimport { type Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\ntype ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?: (server: ServerT) => Promise<boolean>;\n beforeExpressJsSetup?: (server: ServerT) => Promise<void>;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n) {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path || '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: any,\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) return next(error);\n\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n return undefined;\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,IAAAA,KAAA,CAAAC,OAAA,SACA,IAAAC,IAAA,CAAAD,OAAA,QAEA,IAAAE,OAAA,CAAAF,OAAA,WAMA,IAAAG,YAAA,CAAAC,sBAAA,CAAAJ,OAAA,iBACA,IAAAK,aAAA,CAAAD,sBAAA,CAAAJ,OAAA,mBACA,IAAAM,MAAA,CAAAF,sBAAA,CAAAJ,OAAA,uBAEA,IAAAO,QAAA,CAAAH,sBAAA,CAAAJ,OAAA,aAOA,IAAAQ,aAAA,CAAAJ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AAM,CAAAC,UAAU,CAAGF,MAAM,EAAIL,aAAK,CAACM,qBAAqB,CAExD;AACAhF,OAAO,CAACU,MAAM,CAAEwE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAAC,CAE1D,GAAI,CAAAM,OAAO,CAAGN,KAAK,CAACM,OAAO,EAAI,GAAAC,uBAAe,EAACL,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAInB,OAAO,CAACuB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDH,OAAO,CAAGX,cAAM,CAACQ,qBACnB,CAEAlE,GAAG,CAACiE,MAAM,CAACA,MAAM,CAAC,CAAC7C,IAAI,CAACiD,OAAO,CAAC,CAChC,MAAO,CAAAI,SACT,CAAC,CACH,CAEA,MAAO,CAAAhF,MACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV","undefined"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\nimport { type Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\ntype ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?: (server: ServerT) => Promise<boolean>;\n beforeExpressJsSetup?: (server: ServerT) => Promise<void>;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n) {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path || '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: any,\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) return next(error);\n\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n return undefined;\n });\n }\n\n return server;\n}\n"],"m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6B,CAAE,CAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACApE,MAAM,CAACK,GAAG,CAAC,CACTiE,KAAU,CACVhE,GAAY,CACZC,GAAa,CACbC,IAAkB,GACf,CACH;AACA;AACA,GAAID,GAAG,CAACgE,WAAW,CAAE,MAAO,CAAA/D,IAAI,CAAC8D,KAAK,CAAC,CAEvC,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAIL,aAAK,CAACM,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAIL,aAAK,CAACM,qBAAqB,CAExD;AACAhF,OAAO,CAACU,MAAM,CAAEwE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAAC,CAE1D,GAAI,CAAAM,OAAO,CAAGN,KAAK,CAACM,OAAO,EAAI,GAAAC,uBAAe,EAACL,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAInB,OAAO,CAACuB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDH,OAAO,CAAGX,cAAM,CAACQ,qBACnB,CAEAlE,GAAG,CAACiE,MAAM,CAACA,MAAM,CAAC,CAAC7C,IAAI,CAACiD,OAAO,CAAC,CAChC,MAAO,CAAAI,SACT,CAAC,CACH,CAEA,MAAO,CAAAhF,MACT","ignoreList":[]}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* const { errors } = server;
|
|
8
8
|
* ```
|
|
9
9
|
* Server-side helpers for error handling.
|
|
10
|
-
|
|
10
|
+
*//**
|
|
11
11
|
* @static
|
|
12
12
|
* @const CODES
|
|
13
13
|
* @desc An alias for
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* import { server } from '@dr.pogodin/react-utils';
|
|
18
18
|
* const { CODES } = server.errors;
|
|
19
19
|
* console.log(CODES.BAD_REQUEST); // Prints: 400
|
|
20
|
-
|
|
20
|
+
*//**
|
|
21
21
|
* @static
|
|
22
22
|
* @const ERRORS
|
|
23
23
|
* @desc An alias for
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
* import { server } from '@dr.pogodin/react-utils';
|
|
28
28
|
* const { ERRORS } = server.errors;
|
|
29
29
|
* console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request
|
|
30
|
-
|
|
30
|
+
*//**
|
|
31
31
|
* @static
|
|
32
32
|
* @func getErrorForCode
|
|
33
33
|
* @desc An alias for
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
* @example
|
|
39
39
|
* import { server } from '@dr.pogodin/react-utils';
|
|
40
40
|
* console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request
|
|
41
|
-
|
|
41
|
+
*//**
|
|
42
42
|
* @static
|
|
43
43
|
* @const joi
|
|
44
44
|
* @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
* const requestBodySchema = joi.object({
|
|
51
51
|
* sampleKey: joi.string().max(16).required(),
|
|
52
52
|
* });
|
|
53
|
-
|
|
53
|
+
*/// TODO: It could accept the status code as a constructor argument.
|
|
54
54
|
class ErrorWithStatus extends Error{status=_httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR}/**
|
|
55
55
|
* ```js
|
|
56
56
|
* import { server } from '@dr.pogodin/react-utils';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","ErrorWithStatus","Error","status","CODES","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param message Error message.\n * @param [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n */\nexport function fail(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param value\n * @param schema\n * @param [message] Error message.\n * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n */\nexport function assert(\n value: any,\n schema: joi.AnySchema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":"8oBAWA,IAAAA,gBAAA,CAAAC,OAAA,sBAMA,IAAAC,IAAA,CAAAC,sBAAA,CAAAF,OAAA,SAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,
|
|
1
|
+
{"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","ErrorWithStatus","Error","status","CODES","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param message Error message.\n * @param [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n */\nexport function fail(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param value\n * @param schema\n * @param [message] Error message.\n * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n */\nexport function assert(\n value: any,\n schema: joi.AnySchema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":"8oBAWA,IAAAA,gBAAA,CAAAC,OAAA,sBAMA,IAAAC,IAAA,CAAAC,sBAAA,CAAAF,OAAA,SAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAGA;AACA,KAAM,CAAAG,eAAe,QAAS,CAAAC,KAAM,CAClCC,MAAM,CAAWC,4BAAK,CAACC,qBACzB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAC,QAAQA,CAACC,OAAe,CAAEC,UAAU,CAAGJ,4BAAK,CAACC,qBAAqB,CAAE,CAClF,KAAM,CAAAI,KAAK,CAAG,GAAI,CAAAR,eAAe,CAACM,OAAO,CAAC,CAC1CE,KAAK,CAACN,MAAM,CAAGK,UAAU,CACzB,MAAO,CAAAC,KACT,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAC,IAAIA,CAACH,OAAe,CAAEC,UAAU,CAAGJ,4BAAK,CAACC,qBAAqB,CAAE,CAC9E,KAAM,CAAAC,QAAQ,CAACC,OAAO,CAAEC,UAAU,CACpC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAG,MAAMA,CACpBC,KAAU,CACVC,MAAqB,CACrBN,OAAO,CAAG,EAAE,CACZC,UAAU,CAAGJ,4BAAK,CAACU,WAAW,CAC9B,CACA,KAAM,CAAEL,KAAM,CAAC,CAAGI,MAAM,CAACE,QAAQ,CAACH,KAAK,CAAE,CAAEI,UAAU,CAAE,KAAM,CAAC,CAAC,CAC/D,GAAIP,KAAK,CAAE,CACTC,IAAI,CAACH,OAAO,CAACU,MAAM,CAACV,OAAO,CAAG,IAAI,CAAG,EAAE,CAAEE,KAAK,CAACF,OAAO,CAAC,CAAEC,UAAU,CACrE,CACF","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _reactThemes=_interopRequireDefault(require("@dr.pogodin/react-themes"));var _jsxRuntime=require("react/jsx-runtime");const defaultTheme={"context":"dNQcC6","ad":"earXxa","hoc":"qAPfQ6","checkbox":"A-f8qJ","container":"Kr0g3M","label":"_3dML-O"};const Checkbox=({checked,label,onChange,theme})
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _reactThemes=_interopRequireDefault(require("@dr.pogodin/react-themes"));var _jsxRuntime=require("react/jsx-runtime");const defaultTheme={"context":"dNQcC6","ad":"earXxa","hoc":"qAPfQ6","checkbox":"A-f8qJ","indeterminate":"N9bCb8","container":"Kr0g3M","label":"_3dML-O","disabled":"EzQra1"};const Checkbox=({checked,disabled,label,onChange,testId,theme})=>{let containerClassName=theme.container;if(disabled)containerClassName+=` ${theme.disabled}`;let checkboxClassName=theme.checkbox;if(checked==="indeterminate")checkboxClassName+=` ${theme.indeterminate}`;return/*#__PURE__*/(0,_jsxRuntime.jsxs)("div",{className:containerClassName,children:[label===undefined?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:theme.label,children:label}),/*#__PURE__*/(0,_jsxRuntime.jsx)("input",{checked:checked===undefined?undefined:checked===true,className:checkboxClassName,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,disabled:disabled,onChange:onChange,onClick:e=>e.stopPropagation(),type:"checkbox"})]})};var _default=exports.default=(0,_reactThemes.default)(Checkbox,"Checkbox",defaultTheme);
|
|
2
2
|
//# sourceMappingURL=index.js.map
|